wgc_capturer.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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->hide();
  21. // __widget->resize(800, 600);
  22. // __widget->show();
  23. static auto target = CreateDesktopWindowTarget(compositor, (HWND)__widget->winId());
  24. static auto root = compositor.CreateContainerVisual();
  25. root.RelativeSizeAdjustment({1.0f, 1.0f});
  26. target.Root(root);
  27. // Enqueue our capture work on the dispatcher
  28. static auto queue = controller.DispatcherQueue();
  29. queuePtr = &queue;
  30. rootPtr = &root;
  31. // 首先 New 一个 Capturer 备用
  32. New();
  33. }
  34. void WgcCapturer::Uninit()
  35. {
  36. delete __widget;
  37. while (!_capturers.empty()) {
  38. delete *_capturers.begin();
  39. _capturers.erase(_capturers.begin());
  40. }
  41. }
  42. WgcCapturer* WgcCapturer::New()
  43. {
  44. // 将上一个 new 好的对象返回,并重新预备一个新的
  45. if (_capturers.empty()) {
  46. _capturers.push_back(new WgcCapturer);
  47. }
  48. return *(--_capturers.end());
  49. }
  50. void WgcCapturer::Delete(WgcCapturer* ptr)
  51. {
  52. // auto iter = std::find(_capturers.begin(), _capturers.end(), ptr);
  53. // if (iter == _capturers.end()) {
  54. // return;
  55. // }
  56. // if (*iter != nullptr) {
  57. // delete *iter;
  58. // }
  59. // _capturers.erase(iter);
  60. }
  61. WgcCapturer::WgcCapturer()
  62. {
  63. _app = new App;
  64. _isAppInit = false;
  65. auto success = queuePtr->TryEnqueue([=]() -> void {
  66. _app->Initialize(*rootPtr);
  67. _isAppInit = true;
  68. });
  69. WINRT_VERIFY(success);
  70. }
  71. WgcCapturer::~WgcCapturer()
  72. {
  73. if (_app) {
  74. delete _app;
  75. _app = nullptr;
  76. }
  77. }
  78. bool WgcCapturer::StartCapturerMonitor(HMONITOR monitor, int width, int height)
  79. {
  80. return _app->StartCaptureMonitor(monitor, width, height);
  81. }
  82. bool WgcCapturer::StartCapturerWindow(HWND hwnd, int width, int height)
  83. {
  84. return _app->StartCaptureWindow(hwnd, width, height);
  85. }