wgc_capturer.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "wgc_capturer.h"
  2. #include "wgc/winrt.h"
  3. #include <QWidget>
  4. winrt::Windows::System::DispatcherQueue* WgcCapturer::queuePtr = nullptr;
  5. winrt::Windows::UI::Composition::ContainerVisual* WgcCapturer::rootPtr = nullptr;
  6. std::list<WgcCapturer*> WgcCapturer::_capturers;
  7. QWidget* __widget = nullptr;
  8. void WgcCapturer::Init()
  9. {
  10. if (queuePtr != nullptr) {
  11. return;
  12. }
  13. // Init COM
  14. init_apartment(apartment_type::single_threaded);
  15. // Create a DispatcherQueue for our thread
  16. static auto controller = CreateDispatcherQueueController();
  17. // Initialize Composition
  18. static auto compositor = Compositor();
  19. __widget = new QWidget;
  20. // __widget->resize(800, 600);
  21. // __widget->show();
  22. static auto target = CreateDesktopWindowTarget(compositor, (HWND)__widget->winId());
  23. static auto root = compositor.CreateContainerVisual();
  24. root.RelativeSizeAdjustment({1.0f, 1.0f});
  25. target.Root(root);
  26. // Enqueue our capture work on the dispatcher
  27. static auto queue = controller.DispatcherQueue();
  28. queuePtr = &queue;
  29. rootPtr = &root;
  30. // 首先 New 一个 Capturer 备用
  31. New();
  32. }
  33. void WgcCapturer::Uninit()
  34. {
  35. delete __widget;
  36. while (!_capturers.empty()) {
  37. delete *_capturers.begin();
  38. _capturers.erase(_capturers.begin());
  39. }
  40. }
  41. WgcCapturer* WgcCapturer::New()
  42. {
  43. // 将上一个 new 好的对象返回,并重新预备一个新的
  44. if (_capturers.empty()) {
  45. _capturers.push_back(new WgcCapturer);
  46. }
  47. return *(--_capturers.end());
  48. }
  49. void WgcCapturer::Delete(WgcCapturer* ptr)
  50. {
  51. // auto iter = std::find(_capturers.begin(), _capturers.end(), ptr);
  52. // if (iter == _capturers.end()) {
  53. // return;
  54. // }
  55. // if (*iter != nullptr) {
  56. // delete *iter;
  57. // }
  58. // _capturers.erase(iter);
  59. }
  60. WgcCapturer::WgcCapturer()
  61. {
  62. _app = new App;
  63. _isAppInit = false;
  64. auto success = queuePtr->TryEnqueue([=]() -> void {
  65. _app->Initialize(*rootPtr);
  66. _isAppInit = true;
  67. });
  68. WINRT_VERIFY(success);
  69. }
  70. WgcCapturer::~WgcCapturer()
  71. {
  72. if (_app) {
  73. delete _app;
  74. _app = nullptr;
  75. }
  76. }
  77. bool WgcCapturer::StartCapturerMonitor(HMONITOR monitor, int width, int height)
  78. {
  79. return _app->StartCaptureMonitor(monitor, width, height);
  80. }
  81. bool WgcCapturer::StartCapturerWindow(HWND hwnd, int width, int height)
  82. {
  83. return _app->StartCaptureWindow(hwnd, width, height);
  84. }