OLD | NEW |
---|---|
(Empty) | |
1 /* | |
2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. | |
3 * | |
4 * Use of this source code is governed by a BSD-style license | |
5 * that can be found in the LICENSE file in the root of the source | |
6 * tree. An additional intellectual property rights grant can be found | |
7 * in the file PATENTS. All contributing project authors may | |
8 * be found in the AUTHORS file in the root of the source tree. | |
9 */ | |
10 | |
11 #include "webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" | |
12 | |
13 #include <string.h> | |
14 | |
15 #include <comdef.h> | |
16 #include <wincodec.h> | |
17 #include <DXGI.h> | |
18 | |
19 #include "webrtc/base/checks.h" | |
20 #include "webrtc/base/criticalsection.h" | |
21 #include "webrtc/base/scoped_ref_ptr.h" | |
22 #include "webrtc/base/timeutils.h" | |
23 #include "webrtc/modules/desktop_capture/desktop_frame.h" | |
24 #include "webrtc/modules/desktop_capture/win/screen_capture_utils.h" | |
25 #include "webrtc/system_wrappers/include/atomic32.h" | |
26 #include "webrtc/system_wrappers/include/logging.h" | |
27 | |
28 namespace webrtc { | |
29 | |
30 using Microsoft::WRL::ComPtr; | |
31 using rtc::CriticalSection; | |
32 using rtc::CritScope; | |
33 using std::unique_ptr; | |
34 | |
35 namespace { | |
36 | |
37 // Timeout for AcquireNextFrame() call | |
38 const int kAcquireTimeoutMs = 10; | |
39 | |
40 // Wait time between two DuplicateOutput operations, DuplicateOutput may fail if | |
41 // display mode is changing. | |
42 const int kDuplicateOutputWaitMs = 50; | |
43 | |
44 // How many times we attempt to DuplicateOutput before returning an error to | |
45 // upstream components. | |
46 const int kDuplicateOutputAttempts = 10; | |
47 | |
48 rtc::GlobalLockPod g_initialize_lock; | |
49 | |
50 // A container of all the objects we need to call Windows API. Note, one | |
51 // application can only have one IDXGIOutputDuplication instance, that's the | |
52 // reason the container is singleton. | |
53 struct DxgiContainer { | |
54 CriticalSection duplication_lock; | |
55 CriticalSection acquire_lock; | |
56 bool initialize_result GUARDED_BY(g_initialize_lock) = false; | |
57 ID3D11Device* device GUARDED_BY(g_initialize_lock) = nullptr; | |
58 ID3D11DeviceContext* context GUARDED_BY(g_initialize_lock) = nullptr; | |
59 IDXGIOutput1* output1 GUARDED_BY(g_initialize_lock) = nullptr; | |
60 ComPtr<IDXGIOutputDuplication> duplication | |
61 GUARDED_BY(duplication_lock); | |
62 DXGI_OUTDUPL_DESC duplication_desc; | |
63 std::vector<uint8_t> metadata GUARDED_BY(acquire_lock); | |
64 }; | |
65 | |
66 DxgiContainer* g_container GUARDED_BY(g_initialize_lock); | |
67 | |
68 } // namespace | |
69 | |
70 // A pair of an ID3D11Texture2D and an IDXGISurface. We need an | |
71 // ID3D11Texture2D instance to copy GPU texture to RAM, but an IDXGISurface to | |
72 // map the texture into a bitmap buffer. These two instances are always | |
73 // pointing to a same object. | |
74 // | |
75 // This class is not thread safe. | |
76 class ScreenCapturerWinDirectx::Texture { | |
77 public: | |
78 // Copy a frame represented by frame_info and resource. Returns false if | |
79 // anything wrong. If |updated_region| is provided, copy only updated regions, | |
80 // otherwise, copy entire resource. | |
81 bool CopyFrom(const DXGI_OUTDUPL_FRAME_INFO& frame_info, | |
82 IDXGIResource* resource, | |
83 DesktopRegion* updated_region) { | |
84 if (!resource || frame_info.AccumulatedFrames == 0) { | |
85 // Nothing updated, but current data is still valid. | |
86 return false; | |
87 } | |
88 | |
89 ComPtr<ID3D11Texture2D> texture; | |
90 _com_error error = resource->QueryInterface( | |
91 __uuidof(ID3D11Texture2D), | |
92 reinterpret_cast<void**>(texture.GetAddressOf())); | |
93 if (error.Error() != S_OK || !texture) { | |
94 LOG(LS_ERROR) << "Failed to convert IDXGIResource to ID3D11Texture2D, " | |
95 "error " | |
96 << error.ErrorMessage() << ", code " << error.Error(); | |
97 return false; | |
98 } | |
99 | |
100 // AcquireNextFrame returns a CPU inaccessible IDXGIResource, so we need to | |
101 // make a copy. | |
102 if (!InitializeStage(texture.Get())) { | |
103 return false; | |
104 } | |
105 | |
106 if (updated_region) { | |
107 updated_region->IntersectWith(DesktopRect::MakeSize(size())); | |
108 for (DesktopRegion::Iterator it(*updated_region); | |
109 !it.IsAtEnd(); | |
110 it.Advance()) { | |
111 D3D11_BOX box; | |
112 box.left = it.rect().left(); | |
113 box.top = it.rect().top(); | |
114 box.right = it.rect().right(); | |
115 box.bottom = it.rect().bottom(); | |
116 box.front = 0; | |
117 box.back = 1; | |
118 g_container->context->CopySubresourceRegion( | |
119 static_cast<ID3D11Resource*>(stage_.Get()), | |
120 0, it.rect().left(), it.rect().top(), 0, | |
121 static_cast<ID3D11Resource*>(texture.Get()), | |
122 0, &box); | |
123 } | |
124 } else { | |
125 g_container->context->CopyResource( | |
126 static_cast<ID3D11Resource*>(stage_.Get()), | |
127 static_cast<ID3D11Resource*>(texture.Get())); | |
128 } | |
129 | |
130 rect_ = {0}; | |
131 error = _com_error(surface_->Map(&rect_, DXGI_MAP_READ)); | |
132 if (error.Error() != S_OK) { | |
133 LOG(LS_ERROR) << "Failed to map the IDXGISurface to a bitmap, error " | |
134 << error.ErrorMessage() << ", code " << error.Error(); | |
135 return false; | |
136 } | |
137 | |
138 // surface_->Unmap() will be called next time we capture an image to avoid | |
139 // memory copy without shared_memory. | |
140 return true; | |
141 } | |
142 | |
143 uint8_t* bits() const { return static_cast<uint8_t*>(rect_.pBits); } | |
144 int pitch() const { return static_cast<int>(rect_.Pitch); } | |
145 const DesktopSize& size() const { return size_; } | |
146 | |
147 int32_t AddRef() { | |
148 return ++ref_count_; | |
149 } | |
150 | |
151 int32_t Release() { | |
152 int32_t ref_count; | |
153 ref_count = --ref_count_; | |
154 if (ref_count == 0) { | |
155 delete this; | |
156 } | |
157 return ref_count; | |
158 } | |
159 | |
160 private: | |
161 // Texture should only be deleted by Release function. | |
162 ~Texture() = default; | |
163 | |
164 // Initializes stage_ from a CPU inaccessible IDXGIResource. Returns false | |
165 // if it fails to execute windows api. | |
166 bool InitializeStage(ID3D11Texture2D* texture) { | |
167 RTC_DCHECK(texture); | |
168 D3D11_TEXTURE2D_DESC desc = {0}; | |
169 texture->GetDesc(&desc); | |
170 desc.BindFlags = 0; | |
171 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; | |
172 desc.MiscFlags = 0; | |
173 desc.Usage = D3D11_USAGE_STAGING; | |
174 if (stage_) { | |
175 // Make sure stage_ and surface_ are always pointing to a same object. | |
176 // We need an ID3D11Texture2D instance for | |
177 // ID3D11DeviceContext::CopySubresourceRegion, but an IDXGISurface for | |
178 // IDXGISurface::Map. | |
179 { | |
180 ComPtr<IUnknown> left; | |
181 ComPtr<IUnknown> right; | |
182 bool left_result = SUCCEEDED(stage_.As(&left)); | |
183 bool right_result = SUCCEEDED(surface_.As(&right)); | |
184 RTC_DCHECK(left_result); | |
185 RTC_DCHECK(right_result); | |
186 RTC_DCHECK(left.Get() == right.Get()); | |
187 } | |
188 | |
189 // This buffer should be used already. | |
190 _com_error error = _com_error(surface_->Unmap()); | |
191 if (error.Error() == S_OK) { | |
192 D3D11_TEXTURE2D_DESC current_desc; | |
193 stage_->GetDesc(¤t_desc); | |
194 if (memcmp(&desc, ¤t_desc, sizeof(D3D11_TEXTURE2D_DESC)) == 0) { | |
195 return true; | |
196 } | |
197 } else { | |
198 // Let's recreate stage_ and surface_ later. | |
199 LOG(LS_ERROR) << "Failed to unmap surface, error " | |
200 << error.ErrorMessage() << ", code " << error.Error(); | |
201 } | |
202 | |
203 stage_.Reset(); | |
204 surface_.Reset(); | |
205 } else { | |
206 RTC_DCHECK(!surface_); | |
207 } | |
208 | |
209 _com_error error = _com_error(g_container->device->CreateTexture2D( | |
210 &desc, nullptr, stage_.GetAddressOf())); | |
211 if (error.Error() != S_OK || !stage_) { | |
212 LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, " | |
213 "error " | |
214 << error.ErrorMessage() << ", code " << error.Error(); | |
215 return false; | |
216 } | |
217 | |
218 error = _com_error(stage_.As(&surface_)); | |
219 if (error.Error() != S_OK || !surface_) { | |
220 LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, " | |
221 "error " | |
222 << error.ErrorMessage() << ", code " << error.Error(); | |
223 return false; | |
224 } | |
225 | |
226 size_.set(desc.Width, desc.Height); | |
227 return true; | |
228 } | |
229 | |
230 Microsoft::WRL::ComPtr<ID3D11Texture2D> stage_; | |
231 Microsoft::WRL::ComPtr<IDXGISurface> surface_; | |
232 DXGI_MAPPED_RECT rect_; | |
233 DesktopSize size_; | |
234 Atomic32 ref_count_; | |
235 }; | |
236 | |
237 // A DesktopFrame which does not own the data buffer, and also does not have | |
238 // shared memory. This uses in IT2ME scenario only. | |
239 class ScreenCapturerWinDirectx::DxgiDesktopFrame : public DesktopFrame { | |
240 public: | |
241 DxgiDesktopFrame( | |
242 const rtc::scoped_refptr<ScreenCapturerWinDirectx::Texture>& texture) | |
243 : DesktopFrame(texture.get()->size(), | |
244 texture.get()->pitch(), | |
245 texture.get()->bits(), | |
246 nullptr), | |
247 texture_(texture.get()) { | |
248 } | |
249 | |
250 virtual ~DxgiDesktopFrame() {} | |
251 | |
252 private: | |
253 // Keep a reference to the Texture instance to make sure we can still access | |
254 // its bytes array. | |
255 rtc::scoped_refptr<ScreenCapturerWinDirectx::Texture> texture_; | |
256 }; | |
257 | |
258 bool ScreenCapturerWinDirectx::Initialize() { | |
259 if (!g_container) { | |
260 rtc::GlobalLockScope lock(&g_initialize_lock); | |
261 if (!g_container) { | |
262 g_container = new DxgiContainer(); | |
263 g_container->initialize_result = DoInitialize(); | |
264 if (g_container->initialize_result) { | |
265 return true; | |
266 } | |
267 | |
268 // Clean up if DirectX cannot work on the system. | |
269 if (g_container->duplication) { | |
270 g_container->duplication.Reset(); | |
271 } | |
272 | |
273 if (g_container->output1) { | |
274 g_container->output1->Release(); | |
275 g_container->output1 = nullptr; | |
276 } | |
277 | |
278 if (g_container->context) { | |
279 g_container->context->Release(); | |
280 g_container->context = nullptr; | |
281 } | |
282 | |
283 if (g_container->device) { | |
284 g_container->device->Release(); | |
285 g_container->device = nullptr; | |
286 } | |
287 | |
288 return false; | |
289 } | |
290 } | |
291 | |
292 return g_container->initialize_result; | |
293 } | |
294 | |
295 bool ScreenCapturerWinDirectx::DoInitialize() { | |
296 D3D_FEATURE_LEVEL feature_level; | |
297 _com_error error = D3D11CreateDevice( | |
298 nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, | |
299 D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED, | |
300 nullptr, 0, D3D11_SDK_VERSION, &g_container->device, &feature_level, | |
301 &g_container->context); | |
302 if (error.Error() != S_OK || !g_container->device || !g_container->context) { | |
303 LOG(LS_WARNING) << "D3D11CreateDeivce returns error " | |
304 << error.ErrorMessage() << " with code " << error.Error(); | |
305 return false; | |
306 } | |
307 | |
308 if (feature_level < D3D_FEATURE_LEVEL_11_0) { | |
309 LOG(LS_WARNING) << "D3D11CreateDevice returns an instance without DirectX " | |
310 "11 support, level " | |
311 << feature_level; | |
312 return false; | |
313 } | |
314 | |
315 ComPtr<IDXGIDevice> device; | |
316 error = _com_error(g_container->device->QueryInterface( | |
317 __uuidof(IDXGIDevice), reinterpret_cast<void**>(device.GetAddressOf()))); | |
318 if (error.Error() != S_OK || !device) { | |
319 LOG(LS_WARNING) << "ID3D11Device is not an implementation of IDXGIDevice, " | |
320 "this usually means the system does not support DirectX " | |
321 "11"; | |
322 return false; | |
323 } | |
324 | |
325 ComPtr<IDXGIAdapter> adapter; | |
326 error = _com_error(device->GetAdapter(adapter.GetAddressOf())); | |
327 if (error.Error() != S_OK || !adapter) { | |
328 LOG(LS_WARNING) << "Failed to get an IDXGIAdapter implementation from " | |
329 "IDXGIDevice."; | |
330 return false; | |
331 } | |
332 | |
333 ComPtr<IDXGIOutput> output; | |
334 for (int i = 0;; i++) { | |
335 error = _com_error(adapter->EnumOutputs(i, output.GetAddressOf())); | |
336 if (error.Error() == DXGI_ERROR_NOT_FOUND) { | |
337 LOG(LS_WARNING) << "No output detected."; | |
338 return false; | |
339 } | |
340 if (error.Error() == S_OK && output) { | |
341 DXGI_OUTPUT_DESC desc; | |
342 error = _com_error(output->GetDesc(&desc)); | |
343 if (error.Error() == S_OK) { | |
344 if (desc.AttachedToDesktop) { | |
345 // Current output instance is the device attached to desktop. | |
346 break; | |
347 } | |
348 } else { | |
349 LOG(LS_WARNING) << "Failed to get output description of device " << i | |
350 << ", ignore."; | |
351 } | |
352 } | |
353 } | |
354 | |
355 RTC_DCHECK(output); | |
356 error = _com_error(output.CopyTo( | |
357 __uuidof(IDXGIOutput1), reinterpret_cast<void**>(&g_container->output1))); | |
358 if (error.Error() != S_OK || !g_container->output1) { | |
359 LOG(LS_WARNING) << "Failed to convert IDXGIOutput to IDXGIOutput1, this " | |
360 "usually means the system does not support DirectX 11"; | |
361 return false; | |
362 } | |
363 | |
364 return DuplicateOutput(); | |
365 } | |
366 | |
367 bool ScreenCapturerWinDirectx::DuplicateOutput() { | |
368 // We are updating the instance. | |
369 CritScope lock(&g_container->duplication_lock); | |
370 // Make sure nobody is using current instance. | |
371 CritScope lock2(&g_container->acquire_lock); | |
372 if (g_container->duplication) { | |
373 g_container->duplication->ReleaseFrame(); | |
374 g_container->duplication.Reset(); | |
375 } | |
376 | |
377 for (int i = 0; i < kDuplicateOutputAttempts; i++) { | |
378 _com_error error = g_container->output1->DuplicateOutput( | |
379 static_cast<IUnknown*>(g_container->device), | |
380 g_container->duplication.GetAddressOf()); | |
381 if (error.Error() == S_OK && g_container->duplication) { | |
382 memset(&g_container->duplication_desc, 0, sizeof(DXGI_OUTDUPL_DESC)); | |
383 g_container->duplication->GetDesc(&g_container->duplication_desc); | |
384 if (g_container->duplication_desc.ModeDesc.Format != | |
385 DXGI_FORMAT_B8G8R8A8_UNORM) { | |
386 LOG(LS_ERROR) << "IDXGIDuplicateOutput does not use RGBA (8 bit) " | |
387 "format, which is required by downstream components, " | |
388 "format is " | |
389 << g_container->duplication_desc.ModeDesc.Format; | |
390 return false; | |
391 } | |
392 | |
393 return true; | |
394 } else { | |
395 // Make sure we have correct signal and duplicate the output next time. | |
396 g_container->duplication.Reset(); | |
397 LOG(LS_WARNING) << "Failed to duplicate output from IDXGIOutput1, error " | |
398 << error.ErrorMessage() << ", with code " | |
399 << error.Error(); | |
400 Sleep(kDuplicateOutputWaitMs); | |
401 } | |
402 } | |
403 | |
404 return false; | |
405 } | |
406 | |
407 ScreenCapturerWinDirectx::ScreenCapturerWinDirectx( | |
408 const DesktopCaptureOptions& options) | |
409 : callback_(nullptr), set_thread_execution_state_failed_(false) { | |
410 RTC_DCHECK(g_container && g_container->initialize_result); | |
411 | |
412 // Texture instance won't change forever. | |
413 while (!surfaces_.current_frame()) { | |
414 surfaces_.ReplaceCurrentFrame( | |
415 new rtc::scoped_refptr<Texture>(new Texture())); | |
416 surfaces_.MoveToNextFrame(); | |
417 } | |
418 } | |
419 | |
420 ScreenCapturerWinDirectx::~ScreenCapturerWinDirectx() {} | |
421 | |
422 void ScreenCapturerWinDirectx::Start(Callback* callback) { | |
423 RTC_DCHECK(!callback_); | |
424 RTC_DCHECK(callback); | |
425 | |
426 callback_ = callback; | |
427 } | |
428 | |
429 void ScreenCapturerWinDirectx::SetSharedMemoryFactory( | |
430 rtc::scoped_ptr<SharedMemoryFactory> shared_memory_factory) { | |
431 shared_memory_factory_ = | |
432 rtc::ScopedToUnique(std::move(shared_memory_factory)); | |
433 } | |
434 | |
435 bool ScreenCapturerWinDirectx::HandleDetectUpdatedRegionError( | |
436 const _com_error& error, | |
437 const char* stage) { | |
438 if (error.Error() != S_OK) { | |
439 if (error.Error() == DXGI_ERROR_ACCESS_LOST) { | |
440 DuplicateOutput(); | |
441 } else { | |
442 LOG(LS_ERROR) << "Failed to get " << stage << " rectangles, error " | |
443 << error.ErrorMessage() << ", code " << error.Error(); | |
444 } | |
445 // Send entire desktop as we cannot get dirty or move rectangles. | |
446 return false; | |
447 } | |
448 | |
449 return true; | |
450 } | |
451 | |
452 bool ScreenCapturerWinDirectx::DetectUpdatedRegion( | |
453 const DXGI_OUTDUPL_FRAME_INFO& frame_info, | |
454 DesktopRegion* updated_region) { | |
455 RTC_DCHECK(g_container->duplication); | |
456 RTC_DCHECK(updated_region); | |
457 updated_region->Clear(); | |
458 if (frame_info.TotalMetadataBufferSize == 0) { | |
459 // This should not happen, since frame_info.AccumulatedFrames > 0. | |
460 LOG(LS_ERROR) << "frame_info.AccumulatedFrames > 0, " | |
461 "but TotalMetadataBufferSize == 0"; | |
462 return false; | |
463 } | |
464 | |
465 if (g_container->metadata.capacity() < frame_info.TotalMetadataBufferSize) { | |
466 g_container->metadata.clear(); // Avoid data copy | |
467 g_container->metadata.reserve(frame_info.TotalMetadataBufferSize); | |
468 } | |
469 | |
470 UINT buff_size = 0; | |
471 DXGI_OUTDUPL_MOVE_RECT* move_rects = | |
472 reinterpret_cast<DXGI_OUTDUPL_MOVE_RECT*>(g_container->metadata.data()); | |
473 size_t move_rects_count = 0; | |
474 _com_error error = _com_error(g_container->duplication->GetFrameMoveRects( | |
475 static_cast<UINT>(g_container->metadata.capacity()), | |
476 move_rects, &buff_size)); | |
477 if (!HandleDetectUpdatedRegionError(error, "move")) { | |
478 return false; | |
479 } | |
480 move_rects_count = buff_size / sizeof(DXGI_OUTDUPL_MOVE_RECT); | |
481 | |
482 RECT* dirty_rects = | |
483 reinterpret_cast<RECT*>(g_container->metadata.data() + buff_size); | |
484 size_t dirty_rects_count = 0; | |
485 error = _com_error(g_container->duplication->GetFrameDirtyRects( | |
486 static_cast<UINT>(g_container->metadata.capacity()) - buff_size, | |
487 dirty_rects, &buff_size)); | |
488 if (!HandleDetectUpdatedRegionError(error, "dirty")) { | |
489 return false; | |
490 } | |
491 dirty_rects_count = buff_size / sizeof(RECT); | |
492 | |
493 // The edges need to be aligned 8 pixels for the VPX encoder and 1 extra pixel | |
494 // for YUV conversion. | |
495 while (move_rects_count > 0) { | |
496 DesktopRect rect = DesktopRect::MakeXYWH( | |
497 move_rects->SourcePoint.x, move_rects->SourcePoint.y, | |
498 move_rects->DestinationRect.right - move_rects->DestinationRect.left, | |
499 move_rects->DestinationRect.bottom - move_rects->DestinationRect.top); | |
500 rect.Expand(9); | |
Sergey Ulanov
2016/05/16 19:18:52
we don't want to expand the updated_region here. u
Hzj_jie
2016/05/17 03:11:46
Done.
| |
501 updated_region->AddRect(rect); | |
502 rect = DesktopRect::MakeLTRB( | |
503 move_rects->DestinationRect.left, move_rects->DestinationRect.top, | |
504 move_rects->DestinationRect.right, move_rects->DestinationRect.bottom); | |
505 rect.Expand(9); | |
506 updated_region->AddRect(rect); | |
507 move_rects++; | |
508 move_rects_count--; | |
509 } | |
510 | |
511 while (dirty_rects_count > 0) { | |
512 DesktopRect rect = DesktopRect::MakeLTRB( | |
513 dirty_rects->left, dirty_rects->top, | |
514 dirty_rects->right, dirty_rects->bottom); | |
515 rect.Expand(9); | |
516 updated_region->AddRect(rect); | |
517 dirty_rects++; | |
518 dirty_rects_count--; | |
519 } | |
520 | |
521 return true; | |
522 } | |
523 | |
524 DesktopFrame* ScreenCapturerWinDirectx::ProcessFrame( | |
525 const DXGI_OUTDUPL_FRAME_INFO& frame_info, | |
526 IDXGIResource* resource) { | |
527 RTC_DCHECK(resource); | |
528 RTC_DCHECK(frame_info.AccumulatedFrames > 0); | |
529 // We have something to update, so move to next surface. | |
530 surfaces_.MoveToNextFrame(); | |
531 RTC_DCHECK(surfaces_.current_frame()); | |
532 DesktopRegion updated_region; | |
533 if (DetectUpdatedRegion(frame_info, &updated_region)) { | |
534 if (!surfaces_.current_frame()->get()->CopyFrom( | |
535 frame_info, resource, &updated_region)) { | |
536 return nullptr; | |
537 } | |
538 } else { | |
539 if (!surfaces_.current_frame()->get()->CopyFrom( | |
540 frame_info, resource, nullptr)) { | |
541 return nullptr; | |
542 } | |
543 updated_region.Clear(); | |
544 updated_region.AddRect( | |
545 DesktopRect::MakeSize(surfaces_.current_frame()->get()->size())); | |
546 } | |
547 | |
548 unique_ptr<DesktopFrame> result; | |
549 if (shared_memory_factory_) { | |
550 // When using shared memory, |frames_| is used to store a queue of | |
551 // SharedMemoryDesktopFrame's. | |
552 SharedMemoryDesktopFrame* shared_memory_frame = nullptr; | |
553 if (frames_.current_frame()) { | |
554 shared_memory_frame = static_cast<SharedMemoryDesktopFrame*>( | |
555 frames_.current_frame()->GetUnderlyingFrame()); | |
556 } | |
557 if (!shared_memory_frame || | |
558 !shared_memory_frame->size().equals( | |
559 surfaces_.current_frame()->get()->size())) { | |
560 // Current frame does not have a same size as last captured surface. | |
561 unique_ptr<DesktopFrame> new_frame = SharedMemoryDesktopFrame::Create( | |
562 surfaces_.current_frame()->get()->size(), | |
563 shared_memory_factory_.get()); | |
564 if (!new_frame) { | |
565 LOG(LS_ERROR) << "Failed to allocate a new SharedMemoryDesktopFrame"; | |
566 return nullptr; | |
567 } | |
568 frames_.ReplaceCurrentFrame( | |
569 SharedDesktopFrame::Wrap(new_frame.release())); | |
570 } | |
571 result.reset(frames_.current_frame()->Share()); | |
572 | |
573 unique_ptr<DesktopFrame> frame( | |
574 new DxgiDesktopFrame(*surfaces_.current_frame())); | |
575 // Copy data into SharedMemory. | |
576 for (DesktopRegion::Iterator it(updated_region); | |
577 !it.IsAtEnd(); | |
578 it.Advance()) { | |
579 result->CopyPixelsFrom(*frame, it.rect().top_left(), it.rect()); | |
580 } | |
581 } else { | |
582 result.reset(new DxgiDesktopFrame(*surfaces_.current_frame())); | |
583 } | |
584 RTC_DCHECK(result); | |
585 result->mutable_updated_region()->Swap(&updated_region); | |
586 return result.release(); | |
587 } | |
588 | |
589 void ScreenCapturerWinDirectx::Capture(const DesktopRegion& region) { | |
590 RTC_DCHECK(g_container->duplication); | |
591 RTC_DCHECK(callback_); | |
592 | |
593 if (!g_container->duplication && !DuplicateOutput()) { | |
594 // Receive a capture request when application is shutting down, or between | |
595 // mode change. | |
596 callback_->OnCaptureCompleted(nullptr); | |
597 return; | |
598 } | |
599 | |
600 int64_t capture_start_time_nanos = rtc::TimeNanos(); | |
601 | |
602 if (!SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED)) { | |
603 if (!set_thread_execution_state_failed_) { | |
604 set_thread_execution_state_failed_ = true; | |
605 LOG(LS_WARNING) << "Failed to make system & display power assertion: " | |
606 << GetLastError(); | |
607 } | |
608 } | |
609 | |
610 DXGI_OUTDUPL_FRAME_INFO frame_info; | |
611 memset(&frame_info, 0, sizeof(DXGI_OUTDUPL_FRAME_INFO)); | |
612 ComPtr<IDXGIResource> resource; | |
613 CritScope lock(&g_container->acquire_lock); | |
614 _com_error error = g_container->duplication->AcquireNextFrame( | |
615 kAcquireTimeoutMs, &frame_info, resource.GetAddressOf()); | |
616 if (error.Error() == DXGI_ERROR_ACCESS_LOST) { | |
617 LOG(LS_ERROR) << "Access lost " << error.ErrorMessage(); | |
618 if (DuplicateOutput()) { | |
619 EmitCurrentFrame(); | |
620 } else { | |
621 callback_->OnCaptureCompleted(nullptr); | |
622 } | |
623 return; | |
624 } | |
625 | |
626 if (error.Error() == DXGI_ERROR_WAIT_TIMEOUT) { | |
627 // Nothing changed. | |
628 EmitCurrentFrame(); | |
629 return; | |
630 } | |
631 | |
632 if (error.Error() != S_OK) { | |
633 LOG(LS_ERROR) << "Failed to capture frame, error " << error.ErrorMessage() | |
634 << ", code " << error.Error(); | |
635 callback_->OnCaptureCompleted(nullptr); | |
636 return; | |
637 } | |
638 | |
639 if (frame_info.AccumulatedFrames == 0) { | |
640 g_container->duplication->ReleaseFrame(); | |
641 EmitCurrentFrame(); | |
642 return; | |
643 } | |
644 | |
645 // Everything looks good so far, build next frame. | |
646 DesktopFrame* result = ProcessFrame(frame_info, resource.Get()); | |
647 // DetectUpdatedRegion may release last g_container->duplication. But | |
648 // DuplicateOutput function will always release last frame, so there is no | |
649 // potential leak. | |
650 if (g_container->duplication) { | |
651 g_container->duplication->ReleaseFrame(); | |
652 } | |
653 if (result) { | |
654 result->set_capture_time_ms( | |
655 (rtc::TimeNanos() - capture_start_time_nanos) / | |
656 rtc::kNumNanosecsPerMillisec); | |
657 callback_->OnCaptureCompleted(result); | |
658 } else { | |
659 callback_->OnCaptureCompleted(nullptr); | |
660 } | |
661 } | |
662 | |
663 bool ScreenCapturerWinDirectx::GetScreenList(ScreenList* screens) { | |
664 return true; | |
665 } | |
666 | |
667 bool ScreenCapturerWinDirectx::SelectScreen(ScreenId id) { | |
668 // Only full desktop capture is supported. | |
669 return id == kFullDesktopScreenId; | |
670 } | |
671 | |
672 void ScreenCapturerWinDirectx::EmitCurrentFrame() { | |
673 if (frames_.current_frame()) { | |
674 SharedDesktopFrame* frame = frames_.current_frame()->Share(); | |
675 frame->mutable_updated_region()->Clear(); | |
676 callback_->OnCaptureCompleted(frame); | |
677 } else if (shared_memory_factory_) { | |
678 // If shared memory is used, upstream components always expect a valid frame | |
679 // with shared memory are returned. Otherwise the service will crash. | |
680 static const unique_ptr<SharedDesktopFrame> dummy = | |
681 unique_ptr<SharedDesktopFrame>(SharedDesktopFrame::Wrap( | |
682 SharedMemoryDesktopFrame::Create( | |
683 DesktopSize(100, 100), | |
684 shared_memory_factory_.get()).release())); | |
685 RTC_DCHECK(dummy); | |
686 callback_->OnCaptureCompleted(dummy->Share()); | |
687 } else { | |
688 callback_->OnCaptureCompleted(nullptr); | |
689 } | |
690 } | |
691 | |
692 } // namespace webrtc | |
OLD | NEW |