record_desktop_duplication.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. #include "record_desktop_duplication.h"
  2. #include "system_lib.h"
  3. #include "d3d_helper.h"
  4. #include "d3d_pixelshader.h"
  5. #include "d3d_vertexshader.h"
  6. #include "utils_string.h"
  7. #include "system_error.h"
  8. #include "error_define.h"
  9. #include "log_helper.h"
  10. namespace am {
  11. record_desktop_duplication::record_desktop_duplication()
  12. {
  13. _data_type = RECORD_DESKTOP_DATA_TYPES::AT_DESKTOP_BGRA;
  14. _buffer = NULL;
  15. _buffer_size = 0;
  16. _d3d11 = nullptr;
  17. _dxgi = nullptr;
  18. _d3d_device = nullptr;
  19. _d3d_ctx = nullptr;
  20. _d3d_vshader = nullptr;
  21. _d3d_pshader = nullptr;
  22. _d3d_inlayout = nullptr;
  23. _d3d_samplerlinear = nullptr;
  24. _duplication = nullptr;
  25. _image = nullptr;
  26. _output_des = { 0 };
  27. _output_index = 0;
  28. ZeroMemory(&_cursor_info, sizeof(_cursor_info));
  29. }
  30. record_desktop_duplication::~record_desktop_duplication()
  31. {
  32. stop();
  33. clean_up();
  34. }
  35. int record_desktop_duplication::init(const RECORD_DESKTOP_RECT & rect, const int fps)
  36. {
  37. int error = AE_NO;
  38. if (_inited == true) {
  39. return error;
  40. }
  41. _fps = fps;
  42. _rect = rect;
  43. do {
  44. _d3d11 = load_system_library("d3d11.dll");
  45. _dxgi = load_system_library("dxgi.dll");
  46. if (!_d3d11 || !_dxgi) {
  47. error = AE_D3D_LOAD_FAILED;
  48. break;
  49. }
  50. error = init_d3d11();
  51. if (error != AE_NO)
  52. break;
  53. _width = rect.right - rect.left;
  54. _height = rect.bottom - rect.top;
  55. _buffer_size = (_width * 32 + 31) / 32 * _height * 4;
  56. _buffer = new uint8_t[_buffer_size];
  57. _start_time = av_gettime_relative();
  58. _time_base = { 1,AV_TIME_BASE };
  59. _pixel_fmt = AV_PIX_FMT_BGRA;
  60. error = init_duplication();
  61. if (error != AE_NO) {
  62. break;
  63. }
  64. _inited = true;
  65. } while (0);
  66. if (error != AE_NO) {
  67. al_debug("%s,last error:%s", err2str(error), system_error::error2str(GetLastError()).c_str());
  68. }
  69. return error;
  70. }
  71. int record_desktop_duplication::start()
  72. {
  73. if (_running == true) {
  74. al_warn("record desktop duplication is already running");
  75. return AE_NO;
  76. }
  77. if (_inited == false) {
  78. return AE_NEED_INIT;
  79. }
  80. _running = true;
  81. _thread = std::thread(std::bind(&record_desktop_duplication::record_func, this));
  82. return AE_NO;
  83. }
  84. int record_desktop_duplication::pause()
  85. {
  86. _paused = true;
  87. return AE_NO;
  88. }
  89. int record_desktop_duplication::resume()
  90. {
  91. _paused = false;
  92. return AE_NO;
  93. }
  94. int record_desktop_duplication::stop()
  95. {
  96. _running = false;
  97. if (_thread.joinable())
  98. _thread.join();
  99. return AE_NO;
  100. }
  101. void record_desktop_duplication::clean_up()
  102. {
  103. _inited = false;
  104. if (_buffer)
  105. delete[] _buffer;
  106. _buffer = nullptr;
  107. if (_cursor_info.buff) {
  108. delete[] _cursor_info.buff;
  109. _cursor_info.buff = nullptr;
  110. }
  111. ZeroMemory(&_cursor_info, sizeof(_cursor_info));
  112. //Clean up duplication interfaces
  113. clean_duplication();
  114. //Clean up d3d11 interfaces
  115. clean_d3d11();
  116. //finally free d3d11 & dxgi library
  117. if (_d3d11) free_system_library(_d3d11);
  118. _d3d11 = nullptr;
  119. if (_dxgi) free_system_library(_dxgi);
  120. _dxgi = nullptr;
  121. }
  122. int record_desktop_duplication::get_dst_adapter(IDXGIAdapter ** adapter)
  123. {
  124. int error = AE_NO;
  125. do {
  126. auto adapters = d3d_helper::get_adapters(&error, true);
  127. if (error != AE_NO || adapters.size() == 0)
  128. break;
  129. for (std::list<IDXGIAdapter *>::iterator itr = adapters.begin(); itr != adapters.end(); itr++) {
  130. IDXGIOutput *adapter_output = nullptr;
  131. DXGI_ADAPTER_DESC adapter_desc = { 0 };
  132. DXGI_OUTPUT_DESC adapter_output_desc = { 0 };
  133. (*itr)->GetDesc(&adapter_desc);
  134. al_debug("adaptor:%s", utils_string::unicode_ascii(adapter_desc.Description).c_str());
  135. unsigned int n = 0;
  136. RECT output_rect;
  137. while ((*itr)->EnumOutputs(n, &adapter_output) != DXGI_ERROR_NOT_FOUND)
  138. {
  139. HRESULT hr = adapter_output->GetDesc(&adapter_output_desc);
  140. if (FAILED(hr)) continue;
  141. output_rect = adapter_output_desc.DesktopCoordinates;
  142. al_debug(" output:%s left:%d top:%d right:%d bottom:%d",
  143. utils_string::unicode_ascii(adapter_output_desc.DeviceName).c_str(),
  144. output_rect.left, output_rect.top, output_rect.right, output_rect.bottom);
  145. if (output_rect.left <= _rect.left &&
  146. output_rect.top <= _rect.top &&
  147. output_rect.right >= _rect.right &&
  148. output_rect.bottom >= _rect.bottom) {
  149. error = AE_NO;
  150. break;
  151. }
  152. ++n;
  153. }
  154. if (error != AE_DXGI_FOUND_ADAPTER_FAILED) {
  155. *adapter = *itr;
  156. break;
  157. }
  158. }
  159. } while (0);
  160. return error;
  161. }
  162. int record_desktop_duplication::create_d3d_device(IDXGIAdapter *adapter, ID3D11Device ** device)
  163. {
  164. int error = AE_NO;
  165. do {
  166. PFN_D3D11_CREATE_DEVICE create_device =
  167. (PFN_D3D11_CREATE_DEVICE)GetProcAddress(_d3d11, "D3D11CreateDevice");
  168. if (!create_device) {
  169. error = AE_D3D_GET_PROC_FAILED;
  170. break;
  171. }
  172. HRESULT hr = S_OK;
  173. // Driver types supported
  174. // If you set the pAdapter parameter to a non - NULL value,
  175. // you must also set the DriverType parameter to the D3D_DRIVER_TYPE_UNKNOWN value.
  176. D3D_DRIVER_TYPE driver_types[] =
  177. {
  178. D3D_DRIVER_TYPE_UNKNOWN,
  179. D3D_DRIVER_TYPE_HARDWARE,
  180. D3D_DRIVER_TYPE_WARP,
  181. D3D_DRIVER_TYPE_REFERENCE,
  182. };
  183. UINT n_driver_types = ARRAYSIZE(driver_types);
  184. // Feature levels supported
  185. D3D_FEATURE_LEVEL feature_levels[] =
  186. {
  187. D3D_FEATURE_LEVEL_11_0,
  188. D3D_FEATURE_LEVEL_10_1,
  189. D3D_FEATURE_LEVEL_10_0,
  190. D3D_FEATURE_LEVEL_9_1
  191. };
  192. UINT n_feature_levels = ARRAYSIZE(feature_levels);
  193. D3D_FEATURE_LEVEL feature_level;
  194. // Create device
  195. for (UINT driver_index = 0; driver_index < n_driver_types; ++driver_index)
  196. {
  197. hr = create_device(adapter, driver_types[driver_index], nullptr, 0, feature_levels, n_feature_levels,
  198. D3D11_SDK_VERSION, device, &feature_level, &_d3d_ctx);
  199. if (SUCCEEDED(hr)) break;
  200. }
  201. if (FAILED(hr))
  202. {
  203. error = AE_D3D_CREATE_DEVICE_FAILED;
  204. break;
  205. }
  206. } while (0);
  207. return error;
  208. }
  209. int record_desktop_duplication::init_d3d11()
  210. {
  211. int error = AE_NO;
  212. do {
  213. IDXGIAdapter *adapter = nullptr;
  214. error = get_dst_adapter(&adapter);
  215. if (error != AE_NO )
  216. break;
  217. error = create_d3d_device(adapter, &_d3d_device);
  218. if (error != AE_NO)
  219. break;
  220. //No need for grab full screen,but in move & dirty rects copy
  221. #if 0
  222. // VERTEX shader
  223. UINT Size = ARRAYSIZE(g_VS);
  224. HRESULT hr = _d3d_device->CreateVertexShader(g_VS, Size, nullptr, &_d3d_vshader);
  225. if (FAILED(hr))
  226. {
  227. error = AE_D3D_CREATE_VERTEX_SHADER_FAILED;
  228. break;
  229. }
  230. // Input layout
  231. D3D11_INPUT_ELEMENT_DESC layouts[] =
  232. {
  233. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  234. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
  235. };
  236. UINT n_layouts = ARRAYSIZE(layouts);
  237. hr = _d3d_device->CreateInputLayout(layouts, n_layouts, g_VS, Size, &_d3d_inlayout);
  238. if (FAILED(hr))
  239. {
  240. error = AE_D3D_CREATE_INLAYOUT_FAILED;
  241. break;
  242. }
  243. _d3d_ctx->IASetInputLayout(_d3d_inlayout);
  244. // Pixel shader
  245. Size = ARRAYSIZE(g_PS);
  246. hr = _d3d_device->CreatePixelShader(g_PS, Size, nullptr, &_d3d_pshader);
  247. if (FAILED(hr))
  248. {
  249. error = AE_D3D_CREATE_PIXEL_SHADER_FAILED;
  250. break;
  251. }
  252. // Set up sampler
  253. D3D11_SAMPLER_DESC sampler_desc;
  254. RtlZeroMemory(&sampler_desc, sizeof(sampler_desc));
  255. sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  256. sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
  257. sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
  258. sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
  259. sampler_desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
  260. sampler_desc.MinLOD = 0;
  261. sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;
  262. hr = _d3d_device->CreateSamplerState(&sampler_desc, &_d3d_samplerlinear);
  263. if (FAILED(hr))
  264. {
  265. error = AE_D3D_CREATE_SAMPLERSTATE_FAILED;
  266. break;
  267. }
  268. #endif
  269. } while (0);
  270. return error;
  271. }
  272. void record_desktop_duplication::clean_d3d11()
  273. {
  274. if (_d3d_device) _d3d_device->Release();
  275. _d3d_device = nullptr;
  276. if (_d3d_ctx) _d3d_ctx->Release();
  277. _d3d_ctx = nullptr;
  278. if (_d3d_vshader) _d3d_vshader->Release();
  279. _d3d_vshader = nullptr;
  280. if (_d3d_pshader) _d3d_pshader->Release();
  281. _d3d_pshader = nullptr;
  282. if (_d3d_inlayout) _d3d_inlayout->Release();
  283. _d3d_inlayout = nullptr;
  284. if (_d3d_samplerlinear) _d3d_samplerlinear->Release();
  285. _d3d_samplerlinear = nullptr;
  286. }
  287. int record_desktop_duplication::init_duplication()
  288. {
  289. int error = AE_NO;
  290. do {
  291. // Get DXGI device
  292. IDXGIDevice* dxgi_device = nullptr;
  293. HRESULT hr = _d3d_device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgi_device));
  294. if (FAILED(hr))
  295. {
  296. error = AE_D3D_QUERYINTERFACE_FAILED;
  297. break;
  298. }
  299. // Get DXGI adapter
  300. IDXGIAdapter* dxgi_adapter = nullptr;
  301. hr = dxgi_device->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&dxgi_adapter));
  302. dxgi_device->Release();
  303. dxgi_device = nullptr;
  304. if (FAILED(hr))
  305. {
  306. error = AE_DUP_GET_PARENT_FAILED;
  307. break;
  308. }
  309. // Get output
  310. IDXGIOutput* dxgi_output = nullptr;
  311. hr = dxgi_adapter->EnumOutputs(_output_index, &dxgi_output);
  312. dxgi_adapter->Release();
  313. dxgi_adapter = nullptr;
  314. if (FAILED(hr))
  315. {
  316. error = AE_DUP_ENUM_OUTPUT_FAILED;
  317. break;
  318. }
  319. dxgi_output->GetDesc(&_output_des);
  320. // QI for Output 1
  321. IDXGIOutput1* dxgi_output1 = nullptr;
  322. hr = dxgi_output->QueryInterface(__uuidof(dxgi_output1), reinterpret_cast<void**>(&dxgi_output1));
  323. dxgi_output->Release();
  324. dxgi_output = nullptr;
  325. if (FAILED(hr))
  326. {
  327. error = AE_DUP_QI_FAILED;
  328. break;
  329. }
  330. // Create desktop duplication
  331. hr = dxgi_output1->DuplicateOutput(_d3d_device, &_duplication);
  332. dxgi_output1->Release();
  333. dxgi_output1 = nullptr;
  334. if (FAILED(hr))
  335. {
  336. error = AE_DUP_DUPLICATE_FAILED;
  337. if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE)
  338. {
  339. error = AE_DUP_DUPLICATE_MAX_FAILED;
  340. }
  341. al_error("duplicate output failed,%lld", hr);
  342. break;
  343. }
  344. } while (0);
  345. return error;
  346. }
  347. int record_desktop_duplication::free_duplicated_frame()
  348. {
  349. HRESULT hr = _duplication->ReleaseFrame();
  350. if (FAILED(hr))
  351. {
  352. return AE_DUP_RELEASE_FRAME_FAILED;
  353. }
  354. if (_image)
  355. {
  356. _image->Release();
  357. _image = nullptr;
  358. }
  359. return AE_DUP_RELEASE_FRAME_FAILED;
  360. }
  361. void record_desktop_duplication::clean_duplication()
  362. {
  363. if (_duplication) _duplication->Release();
  364. if (_image) _image->Release();
  365. _duplication = nullptr;
  366. _image = nullptr;
  367. }
  368. bool record_desktop_duplication::attatch_desktop()
  369. {
  370. HDESK desktop = nullptr;
  371. desktop = OpenInputDesktop(0, FALSE, GENERIC_ALL);
  372. if (!desktop)
  373. {
  374. // We do not have access to the desktop so request a retry
  375. return false;
  376. }
  377. // Attach desktop to this thread
  378. bool battached = SetThreadDesktop(desktop) != 0;
  379. CloseDesktop(desktop);
  380. if (!battached)
  381. {
  382. // We do not have access to the desktop so request a retry
  383. return false;
  384. }
  385. return true;
  386. }
  387. int record_desktop_duplication::get_desktop_image(DXGI_OUTDUPL_FRAME_INFO *frame_info)
  388. {
  389. IDXGIResource* dxgi_res = nullptr;
  390. // Get new frame
  391. HRESULT hr = _duplication->AcquireNextFrame(500, frame_info, &dxgi_res);
  392. // Timeout will return when desktop has no chane
  393. if (hr == DXGI_ERROR_WAIT_TIMEOUT) return AE_TIMEOUT;
  394. if (FAILED(hr))
  395. return AE_DUP_ACQUIRE_FRAME_FAILED;
  396. // QI for IDXGIResource
  397. hr = dxgi_res->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&_image));
  398. dxgi_res->Release();
  399. dxgi_res = nullptr;
  400. if (FAILED(hr)) return AE_DUP_QI_FRAME_FAILED;
  401. // Copy old description
  402. D3D11_TEXTURE2D_DESC frame_desc;
  403. _image->GetDesc(&frame_desc);
  404. // Create a new staging buffer for fill frame image
  405. ID3D11Texture2D *new_image = NULL;
  406. frame_desc.Usage = D3D11_USAGE_STAGING;
  407. frame_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
  408. frame_desc.BindFlags = 0;
  409. frame_desc.MiscFlags = 0;
  410. frame_desc.MipLevels = 1;
  411. frame_desc.ArraySize = 1;
  412. frame_desc.SampleDesc.Count = 1;
  413. frame_desc.SampleDesc.Quality = 0;
  414. hr = _d3d_device->CreateTexture2D(&frame_desc, NULL, &new_image);
  415. if (FAILED(hr)) return AE_DUP_CREATE_TEXTURE_FAILED;
  416. // Copy next staging buffer to new staging buffer
  417. _d3d_ctx->CopyResource(new_image, _image);
  418. #if 1
  419. // Should calc the row pitch ,and compare dst row pitch with frame row pitch
  420. // Create staging buffer for map bits
  421. IDXGISurface *dxgi_surface = NULL;
  422. hr = new_image->QueryInterface(__uuidof(IDXGISurface), (void **)(&dxgi_surface));
  423. new_image->Release();
  424. if (FAILED(hr)) return AE_DUP_QI_DXGI_FAILED;
  425. // Map buff to mapped rect structure
  426. DXGI_MAPPED_RECT mapped_rect;
  427. hr = dxgi_surface->Map(&mapped_rect, DXGI_MAP_READ);
  428. if (FAILED(hr)) return AE_DUP_MAP_FAILED;
  429. int dst_offset_x = _rect.left - _output_des.DesktopCoordinates.left;
  430. int dst_offset_y = _rect.top - _output_des.DesktopCoordinates.top;
  431. int dst_rowpitch = min(frame_desc.Width, _rect.right - _rect.left) * 4;
  432. int dst_colpitch = min(_height, _output_des.DesktopCoordinates.bottom - _output_des.DesktopCoordinates.top - dst_offset_y);
  433. for (int h = 0; h < dst_colpitch; h++) {
  434. memcpy_s(_buffer + h*dst_rowpitch, dst_rowpitch,
  435. (BYTE*)mapped_rect.pBits + (h + dst_offset_y)*mapped_rect.Pitch + dst_offset_x * 4, min(mapped_rect.Pitch, dst_rowpitch));
  436. }
  437. dxgi_surface->Unmap();
  438. dxgi_surface->Release();
  439. dxgi_surface = nullptr;
  440. #else
  441. D3D11_MAPPED_SUBRESOURCE resource;
  442. UINT subresource = D3D11CalcSubresource(0, 0, 0);
  443. hr = _d3d_ctx->Map(new_image, subresource, D3D11_MAP_READ_WRITE, 0, &resource);
  444. new_image->Release();
  445. if (FAILED(hr)) return AE_DUP_MAP_FAILED;
  446. int dst_rowpitch = frame_desc.Width * 4;
  447. for (int h = 0; h < frame_desc.Height; h++) {
  448. memcpy_s(_buffer + h*dst_rowpitch, dst_rowpitch, (BYTE*)resource.pData + h*resource.RowPitch, min(resource.RowPitch, dst_rowpitch));
  449. }
  450. #endif
  451. return AE_NO;
  452. }
  453. int record_desktop_duplication::get_desktop_cursor(const DXGI_OUTDUPL_FRAME_INFO *frame_info)
  454. {
  455. // A non-zero mouse update timestamp indicates that there is a mouse position update and optionally a shape change
  456. if (frame_info->LastMouseUpdateTime.QuadPart == 0)
  457. return AE_NO;
  458. bool b_updated = true;
  459. // Make sure we don't update pointer position wrongly
  460. // If pointer is invisible, make sure we did not get an update from another output that the last time that said pointer
  461. // was visible, if so, don't set it to invisible or update.
  462. if (!frame_info->PointerPosition.Visible && (_cursor_info.output_index != _output_index))
  463. b_updated = false;
  464. // If two outputs both say they have a visible, only update if new update has newer timestamp
  465. if (frame_info->PointerPosition.Visible && _cursor_info.visible && (_cursor_info.output_index != _output_index) && (_cursor_info.pre_timestamp.QuadPart > frame_info->LastMouseUpdateTime.QuadPart))
  466. b_updated = false;
  467. // Update position
  468. if (b_updated)
  469. {
  470. _cursor_info.position.x = frame_info->PointerPosition.Position.x + _output_des.DesktopCoordinates.left;
  471. _cursor_info.position.y = frame_info->PointerPosition.Position.y + _output_des.DesktopCoordinates.top;
  472. _cursor_info.output_index = _output_index;
  473. _cursor_info.pre_timestamp = frame_info->LastMouseUpdateTime;
  474. _cursor_info.visible = frame_info->PointerPosition.Visible != 0;
  475. }
  476. // No new shape only update cursor positions & visible state
  477. if (frame_info->PointerShapeBufferSize == 0)
  478. {
  479. return AE_NO;
  480. }
  481. // Old buffer too small
  482. if (frame_info->PointerShapeBufferSize > _cursor_info.size)
  483. {
  484. if (_cursor_info.buff)
  485. {
  486. delete[] _cursor_info.buff;
  487. _cursor_info.buff = nullptr;
  488. }
  489. _cursor_info.buff = new (std::nothrow) BYTE[frame_info->PointerShapeBufferSize];
  490. if (!_cursor_info.buff)
  491. {
  492. _cursor_info.size = 0;
  493. return AE_ALLOCATE_FAILED;
  494. }
  495. // Update buffer size
  496. _cursor_info.size = frame_info->PointerShapeBufferSize;
  497. }
  498. // Get shape
  499. UINT BufferSizeRequired;
  500. HRESULT hr = _duplication->GetFramePointerShape(frame_info->PointerShapeBufferSize, reinterpret_cast<VOID*>(_cursor_info.buff), &BufferSizeRequired, &(_cursor_info.shape));
  501. if (FAILED(hr))
  502. {
  503. delete[] _cursor_info.buff;
  504. _cursor_info.buff = nullptr;
  505. _cursor_info.size = 0;
  506. return AE_DUP_GET_CURSORSHAPE_FAILED;
  507. }
  508. return AE_NO;
  509. }
  510. static unsigned int bit_reverse(unsigned int n)
  511. {
  512. n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa);
  513. n = ((n >> 2) & 0x33333333) | ((n << 2) & 0xcccccccc);
  514. n = ((n >> 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0);
  515. n = ((n >> 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00);
  516. n = ((n >> 16) & 0x0000ffff) | ((n << 16) & 0xffff0000);
  517. return n;
  518. }
  519. void record_desktop_duplication::draw_cursor()
  520. {
  521. if (_cursor_info.visible == false) return;
  522. int cursor_width = 0, cursor_height = 0, left = 0, top = 0;
  523. cursor_width = _cursor_info.shape.Width;
  524. cursor_height = _cursor_info.shape.Height;
  525. // In case that,the value of position is negative value
  526. left = abs(_cursor_info.position.x - _rect.left);
  527. top = abs(_cursor_info.position.y - _rect.top);
  528. // Notice here
  529. if (_cursor_info.shape.Type == DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME)
  530. cursor_height = cursor_height / 2;
  531. //Skip invisible pixel
  532. cursor_width = min(_width - left, cursor_width);
  533. cursor_height = min(_height - top, cursor_height);
  534. //al_debug("left:%d top:%d width:%d height:%d type:%d", left, top, cursor_width, height, _cursor_info.shape.Type);
  535. switch (_cursor_info.shape.Type)
  536. {
  537. // The pointer type is a color mouse pointer,
  538. // which is a color bitmap. The bitmap's size
  539. // is specified by width and height in a 32 bpp
  540. // ARGB DIB format.
  541. // should trans cursor to BGRA?
  542. case DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR:
  543. {
  544. unsigned int *cursor_32 = reinterpret_cast<unsigned int*>(_cursor_info.buff);
  545. unsigned int *screen_32 = reinterpret_cast<unsigned int*>(_buffer);
  546. for (int row = 0; row < cursor_height; row++) {
  547. for (int col = 0; col < cursor_width; col++) {
  548. unsigned int cur_cursor_val = cursor_32[col + (row * (_cursor_info.shape.Pitch / sizeof(UINT)))];
  549. //Skip black or empty value
  550. if (cur_cursor_val == 0x00000000)
  551. continue;
  552. else
  553. screen_32[(abs(top) + row) *_width + abs(left) + col] = cur_cursor_val;//bit_reverse(cur_cursor_val);
  554. }
  555. }
  556. break;
  557. }
  558. // The pointer type is a monochrome mouse pointer,
  559. // which is a monochrome bitmap. The bitmap's size
  560. // is specified by width and height in a 1 bits per
  561. // pixel (bpp) device independent bitmap (DIB) format
  562. // AND mask that is followed by another 1 bpp DIB format
  563. // XOR mask of the same size.
  564. case DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME:
  565. {
  566. unsigned int *cursor_32 = reinterpret_cast<unsigned int*>(_cursor_info.buff);
  567. unsigned int *screen_32 = reinterpret_cast<unsigned int*>(_buffer);
  568. for (int row = 0; row < cursor_height; row++) {
  569. BYTE MASK = 0x80;
  570. for (int col = 0; col < cursor_width; col++) {
  571. // Get masks using appropriate offsets
  572. BYTE AndMask = _cursor_info.buff[(col / 8) + (row * (_cursor_info.shape.Pitch))] & MASK;
  573. BYTE XorMask = _cursor_info.buff[(col / 8) + ((row + cursor_height) * (_cursor_info.shape.Pitch))] & MASK;
  574. UINT AndMask32 = (AndMask) ? 0xFFFFFFFF : 0xFF000000;
  575. UINT XorMask32 = (XorMask) ? 0x00FFFFFF : 0x00000000;
  576. // Set new pixel
  577. screen_32[(abs(top) + row) *_width + abs(left) + col] = (screen_32[(abs(top) + row) *_width + abs(left) + col] & AndMask32) ^ XorMask32;
  578. // Adjust mask
  579. if (MASK == 0x01)
  580. {
  581. MASK = 0x80;
  582. }
  583. else
  584. {
  585. MASK = MASK >> 1;
  586. }
  587. }
  588. }
  589. break;
  590. }
  591. // The pointer type is a masked color mouse pointer.
  592. // A masked color mouse pointer is a 32 bpp ARGB format
  593. // bitmap with the mask value in the alpha bits. The only
  594. // allowed mask values are 0 and 0xFF. When the mask value
  595. // is 0, the RGB value should replace the screen pixel.
  596. // When the mask value is 0xFF, an XOR operation is performed
  597. // on the RGB value and the screen pixel; the result replaces the screen pixel.
  598. case DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MASKED_COLOR:
  599. {
  600. unsigned int *cursor_32 = reinterpret_cast<unsigned int*>(_cursor_info.buff);
  601. unsigned int *screen_32 = reinterpret_cast<unsigned int*>(_buffer);
  602. for (int row = 0; row < cursor_height; row++) {
  603. for (int col = 0; col < cursor_width; col++) {
  604. unsigned int cur_cursor_val = cursor_32[col + (row * (_cursor_info.shape.Pitch / sizeof(UINT)))];
  605. unsigned int cur_screen_val = screen_32[(abs(top) + row) *_width + abs(left) + col];
  606. unsigned int mask_val = 0xFF000000 & cur_cursor_val;
  607. if (mask_val) {
  608. //0xFF: XOR operation is performed on the RGB value and the screen pixel
  609. cur_screen_val = (cur_screen_val ^ cur_cursor_val) | 0xFF000000;
  610. }
  611. else {
  612. //0x00: the RGB value should replace the screen pixel
  613. cur_screen_val = cur_cursor_val | 0xFF000000;
  614. }
  615. }
  616. }
  617. break;
  618. }
  619. default:
  620. break;
  621. }
  622. }
  623. void record_desktop_duplication::do_sleep(int64_t dur, int64_t pre, int64_t now)
  624. {
  625. int64_t delay = now - pre;
  626. dur = delay > dur ? max(0, dur - (delay - dur)) : (dur + dur - delay);
  627. //al_debug("%lld", delay);
  628. if (dur)
  629. av_usleep(dur);
  630. }
  631. void record_desktop_duplication::record_func()
  632. {
  633. AVFrame *frame = av_frame_alloc();
  634. int64_t pre_pts = 0, dur = AV_TIME_BASE / _fps;
  635. int error = AE_NO;
  636. #if 0
  637. if (attatch_desktop() != true) {
  638. al_fatal("duplication attach desktop failed :%s",
  639. system_error::error2str(GetLastError()).c_str());
  640. if (_on_error) _on_error(AE_DUP_ATTATCH_FAILED);
  641. return;
  642. }
  643. #endif
  644. //Should init after desktop attatched
  645. //error = init_duplication();
  646. //if (error != AE_NO) {
  647. // al_fatal("duplication initialize failed %s,last error :%s", err2str(error),
  648. // system_error::error2str(GetLastError()).c_str());
  649. // if (_on_error) _on_error(error);
  650. // return;
  651. //}
  652. DXGI_OUTDUPL_FRAME_INFO frame_info;
  653. while (_running)
  654. {
  655. //Timeout is no new picture,no need to update
  656. if ((error = get_desktop_image(&frame_info)) == AE_TIMEOUT) continue;
  657. if (error != AE_NO) {
  658. while (_running)
  659. {
  660. Sleep(300);
  661. clean_duplication();
  662. if ((error = init_duplication()) != AE_NO) {
  663. if (_on_error) _on_error(error);
  664. }
  665. else break;
  666. }
  667. continue;
  668. }
  669. if ((error = get_desktop_cursor(&frame_info)) == AE_NO)
  670. draw_cursor();
  671. free_duplicated_frame();
  672. frame->pts = av_gettime_relative();
  673. frame->pkt_dts = frame->pts;
  674. frame->pkt_pts = frame->pts;
  675. frame->width = _width;
  676. frame->height = _height;
  677. frame->format = AV_PIX_FMT_BGRA;
  678. frame->pict_type = AV_PICTURE_TYPE_NONE;
  679. frame->pkt_size = _width * _height * 4;
  680. av_image_fill_arrays(frame->data,
  681. frame->linesize,
  682. _buffer,
  683. AV_PIX_FMT_BGRA,
  684. _width,
  685. _height,
  686. 1
  687. );
  688. #if 0
  689. //save bmp to test
  690. BITMAPINFOHEADER bi;
  691. bi.biSize = sizeof(BITMAPINFOHEADER);
  692. bi.biWidth = _width;
  693. bi.biHeight = _height * (-1);
  694. bi.biPlanes = 1;
  695. bi.biBitCount = 32;//should get from system color bits
  696. bi.biCompression = BI_RGB;
  697. bi.biSizeImage = 0;
  698. bi.biXPelsPerMeter = 0;
  699. bi.biYPelsPerMeter = 0;
  700. bi.biClrUsed = 0;
  701. bi.biClrImportant = 0;
  702. BITMAPFILEHEADER bf;
  703. bf.bfType = 0x4d42;
  704. bf.bfReserved1 = 0;
  705. bf.bfReserved2 = 0;
  706. bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
  707. bf.bfSize = bf.bfOffBits + _width * _height * 4;
  708. FILE *fp = fopen("..\\..\\save.bmp", "wb+");
  709. fwrite(&bf, 1, sizeof(bf), fp);
  710. fwrite(&bi, 1, sizeof(bi), fp);
  711. fwrite(_buffer, 1, _buffer_size, fp);
  712. fflush(fp);
  713. fclose(fp);
  714. #endif
  715. if (_on_data) _on_data(frame);
  716. do_sleep(dur, pre_pts, frame->pts);
  717. pre_pts = frame->pts;
  718. }
  719. av_frame_free(&frame);
  720. }
  721. }