Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(183)

Side by Side Diff: webrtc/modules/desktop_capture/win/screen_capturer_win_directx.cc

Issue 1845113002: DirectX based screen capturer logic (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Remove unchanged files Created 4 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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 <wingdi.h>
18 #include <DXGI.h>
19
20 #include "webrtc/base/checks.h"
21 #include "webrtc/base/criticalsection.h"
22 #include "webrtc/base/scoped_ref_ptr.h"
23 #include "webrtc/base/timeutils.h"
24 #include "webrtc/modules/desktop_capture/desktop_frame.h"
25 #include "webrtc/modules/desktop_capture/win/screen_capture_utils.h"
26 #include "webrtc/system_wrappers/include/atomic32.h"
27 #include "webrtc/system_wrappers/include/logging.h"
28
29 namespace webrtc {
30
31 using Microsoft::WRL::ComPtr;
32
33 namespace {
34
35 // Timeout for AcquireNextFrame() call.
36 const int kAcquireTimeoutMs = 10;
37
38 // Wait time between two DuplicateOutput operations, DuplicateOutput may fail if
39 // display mode is changing.
40 const int kDuplicateOutputWaitMs = 50;
41
42 // How many times we attempt to DuplicateOutput before returning an error to
43 // upstream components.
44 const int kDuplicateOutputAttempts = 10;
45
46 rtc::GlobalLockPod g_initialize_lock;
47
48 // A container of all the objects we need to call Windows API. Note, one
49 // application can only have one IDXGIOutputDuplication instance, that's the
50 // reason the container is singleton.
51 struct DxgiContainer {
52 rtc::CriticalSection duplication_lock;
53 rtc::CriticalSection acquire_lock;
54 bool initialize_result GUARDED_BY(g_initialize_lock) = false;
55 ID3D11Device* device GUARDED_BY(g_initialize_lock) = nullptr;
56 ID3D11DeviceContext* context GUARDED_BY(g_initialize_lock) = nullptr;
57 IDXGIOutput1* output1 GUARDED_BY(g_initialize_lock) = nullptr;
58 ComPtr<IDXGIOutputDuplication> duplication
59 GUARDED_BY(duplication_lock);
60 DXGI_OUTDUPL_DESC duplication_desc;
61 std::vector<uint8_t> metadata GUARDED_BY(acquire_lock);
62 };
63
64 DxgiContainer* g_container GUARDED_BY(g_initialize_lock);
65
66 } // namespace
67
68 // A pair of an ID3D11Texture2D and an IDXGISurface. We need an
69 // ID3D11Texture2D instance to copy GPU texture to RAM, but an IDXGISurface to
70 // map the texture into a bitmap buffer. These two instances are always
71 // pointing to a same object.
72 // This class also has two DesktopRegions, one is the updated region from
73 // returned from Windows API, the other is the region intersects with the
74 // updated region of last frame.
75 //
76 // This class is not thread safe.
77 class ScreenCapturerWinDirectx::Texture {
78 public:
79 // Copy a frame represented by frame_info and resource. Returns false if
80 // anything wrong.
81 bool CopyFrom(const DXGI_OUTDUPL_FRAME_INFO& frame_info,
82 IDXGIResource* resource,
83 const DesktopRegion& last_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 updated_region_.Clear();
107 if (!DetectUpdatedRegion(frame_info, &updated_region_)) {
108 updated_region_.SetRect(DesktopRect::MakeSize(size()));
109 }
110 // We need to copy changed area in both this frame and last frame, since
111 // currently this frame stores the bitmap of the one before last frame.
112 copied_region_.Clear();
113 copied_region_.AddRegion(updated_region_);
114 copied_region_.AddRegion(last_updated_region);
115 copied_region_.IntersectWith(DesktopRect::MakeSize(size()));
116
117 for (DesktopRegion::Iterator it(copied_region_);
118 !it.IsAtEnd();
119 it.Advance()) {
120 D3D11_BOX box;
121 box.left = it.rect().left();
122 box.top = it.rect().top();
123 box.right = it.rect().right();
124 box.bottom = it.rect().bottom();
125 box.front = 0;
126 box.back = 1;
127 g_container->context->CopySubresourceRegion(
128 static_cast<ID3D11Resource*>(stage_.Get()),
129 0, it.rect().left(), it.rect().top(), 0,
130 static_cast<ID3D11Resource*>(texture.Get()),
131 0, &box);
132 }
133
134 rect_ = {0};
135 error = _com_error(surface_->Map(&rect_, DXGI_MAP_READ));
136 if (error.Error() != S_OK) {
137 LOG(LS_ERROR) << "Failed to map the IDXGISurface to a bitmap, error "
138 << error.ErrorMessage() << ", code " << error.Error();
139 return false;
140 }
141
142 // surface_->Unmap() will be called next time we capture an image to avoid
143 // memory copy without shared_memory.
144 return true;
145 }
146
147 uint8_t* bits() const { return static_cast<uint8_t*>(rect_.pBits); }
148 int pitch() const { return static_cast<int>(rect_.Pitch); }
149 const DesktopSize& size() const { return size_; }
150
151 int32_t AddRef() {
152 return ++ref_count_;
153 }
154
155 int32_t Release() {
156 int32_t ref_count;
157 ref_count = --ref_count_;
158 if (ref_count == 0) {
159 delete this;
160 }
161 return ref_count;
162 }
163
164 const DesktopRegion& updated_region() {
165 return updated_region_;
166 }
167
168 const DesktopRegion& copied_region() {
169 return copied_region_;
170 }
171
172 private:
173 // Texture should only be deleted by Release function.
174 ~Texture() = default;
175
176 // Initializes stage_ from a CPU inaccessible IDXGIResource. Returns false
177 // if it fails to execute windows api.
178 bool InitializeStage(ID3D11Texture2D* texture) {
179 RTC_DCHECK(texture);
180 D3D11_TEXTURE2D_DESC desc = {0};
181 texture->GetDesc(&desc);
182 desc.BindFlags = 0;
183 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
184 desc.MiscFlags = 0;
185 desc.Usage = D3D11_USAGE_STAGING;
186 if (stage_) {
187 // Make sure stage_ and surface_ are always pointing to a same object.
188 // We need an ID3D11Texture2D instance for
189 // ID3D11DeviceContext::CopySubresourceRegion, but an IDXGISurface for
190 // IDXGISurface::Map.
191 {
192 ComPtr<IUnknown> left;
193 ComPtr<IUnknown> right;
194 bool left_result = SUCCEEDED(stage_.As(&left));
195 bool right_result = SUCCEEDED(surface_.As(&right));
196 RTC_DCHECK(left_result);
197 RTC_DCHECK(right_result);
198 RTC_DCHECK(left.Get() == right.Get());
199 }
200
201 // This buffer should be used already.
202 _com_error error = _com_error(surface_->Unmap());
203 if (error.Error() == S_OK) {
204 D3D11_TEXTURE2D_DESC current_desc;
205 stage_->GetDesc(&current_desc);
206 if (memcmp(&desc, &current_desc, sizeof(D3D11_TEXTURE2D_DESC)) == 0) {
207 return true;
208 }
209 } else {
210 // Let's recreate stage_ and surface_ later.
211 LOG(LS_ERROR) << "Failed to unmap surface, error "
212 << error.ErrorMessage() << ", code " << error.Error();
213 }
214
215 stage_.Reset();
216 surface_.Reset();
217 } else {
218 RTC_DCHECK(!surface_);
219 }
220
221 _com_error error = _com_error(g_container->device->CreateTexture2D(
222 &desc, nullptr, stage_.GetAddressOf()));
223 if (error.Error() != S_OK || !stage_) {
224 LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, "
225 "error "
226 << error.ErrorMessage() << ", code " << error.Error();
227 return false;
228 }
229
230 error = _com_error(stage_.As(&surface_));
231 if (error.Error() != S_OK || !surface_) {
232 LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, "
233 "error "
234 << error.ErrorMessage() << ", code " << error.Error();
235 return false;
236 }
237
238 size_.set(desc.Width, desc.Height);
239 return true;
240 }
241
242 ComPtr<ID3D11Texture2D> stage_;
243 ComPtr<IDXGISurface> surface_;
244 DXGI_MAPPED_RECT rect_;
245 DesktopSize size_;
246 Atomic32 ref_count_;
247 // The updated region from Windows API.
248 DesktopRegion updated_region_;
249 // Combination of updated regions from both current frame and previous frame.
250 DesktopRegion copied_region_;
251 };
252
253 // A DesktopFrame which does not own the data buffer, and also does not have
254 // shared memory. This uses in IT2ME scenario only.
255 class ScreenCapturerWinDirectx::DxgiDesktopFrame : public DesktopFrame {
256 public:
257 DxgiDesktopFrame(
258 const rtc::scoped_refptr<ScreenCapturerWinDirectx::Texture>& texture)
259 : DesktopFrame(texture.get()->size(),
260 texture.get()->pitch(),
261 texture.get()->bits(),
262 nullptr),
263 texture_(texture) {
264 }
265
266 virtual ~DxgiDesktopFrame() {}
267
268 private:
269 // Keep a reference to the Texture instance to make sure we can still access
270 // its bytes array.
271 rtc::scoped_refptr<ScreenCapturerWinDirectx::Texture> texture_;
272 };
273
274 bool ScreenCapturerWinDirectx::Initialize() {
275 if (!g_container) {
276 rtc::GlobalLockScope lock(&g_initialize_lock);
277 if (!g_container) {
278 g_container = new DxgiContainer();
279 g_container->initialize_result = DoInitialize();
280 if (g_container->initialize_result) {
281 return true;
282 }
283
284 // Clean up if DirectX cannot work on the system.
285 if (g_container->duplication) {
286 g_container->duplication.Reset();
287 }
288
289 if (g_container->output1) {
290 g_container->output1->Release();
291 g_container->output1 = nullptr;
292 }
293
294 if (g_container->context) {
295 g_container->context->Release();
296 g_container->context = nullptr;
297 }
298
299 if (g_container->device) {
300 g_container->device->Release();
301 g_container->device = nullptr;
302 }
303
304 return false;
305 }
306 }
307
308 return g_container->initialize_result;
309 }
310
311 bool ScreenCapturerWinDirectx::DoInitialize() {
312 D3D_FEATURE_LEVEL feature_level;
313 _com_error error = D3D11CreateDevice(
314 nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
315 D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED,
316 nullptr, 0, D3D11_SDK_VERSION, &g_container->device, &feature_level,
317 &g_container->context);
318 if (error.Error() != S_OK || !g_container->device || !g_container->context) {
319 LOG(LS_WARNING) << "D3D11CreateDeivce returns error "
320 << error.ErrorMessage() << " with code " << error.Error();
321 return false;
322 }
323
324 if (feature_level < D3D_FEATURE_LEVEL_11_0) {
325 LOG(LS_WARNING) << "D3D11CreateDevice returns an instance without DirectX "
326 "11 support, level "
327 << feature_level;
328 return false;
329 }
330
331 ComPtr<IDXGIDevice> device;
332 error = _com_error(g_container->device->QueryInterface(
333 __uuidof(IDXGIDevice), reinterpret_cast<void**>(device.GetAddressOf())));
334 if (error.Error() != S_OK || !device) {
335 LOG(LS_WARNING) << "ID3D11Device is not an implementation of IDXGIDevice, "
336 "this usually means the system does not support DirectX "
337 "11";
338 return false;
339 }
340
341 ComPtr<IDXGIAdapter> adapter;
342 error = _com_error(device->GetAdapter(adapter.GetAddressOf()));
343 if (error.Error() != S_OK || !adapter) {
344 LOG(LS_WARNING) << "Failed to get an IDXGIAdapter implementation from "
345 "IDXGIDevice.";
346 return false;
347 }
348
349 ComPtr<IDXGIOutput> output;
350 for (int i = 0;; i++) {
351 error = _com_error(adapter->EnumOutputs(i, output.GetAddressOf()));
352 if (error.Error() == DXGI_ERROR_NOT_FOUND) {
353 LOG(LS_WARNING) << "No output detected.";
354 return false;
355 }
356 if (error.Error() == S_OK && output) {
357 DXGI_OUTPUT_DESC desc;
358 error = _com_error(output->GetDesc(&desc));
359 if (error.Error() == S_OK) {
360 if (desc.AttachedToDesktop) {
361 // Current output instance is the device attached to desktop.
362 break;
363 }
364 } else {
365 LOG(LS_WARNING) << "Failed to get output description of device " << i
366 << ", ignore.";
367 }
368 }
369 }
370
371 RTC_DCHECK(output);
372 error = _com_error(output.CopyTo(
373 __uuidof(IDXGIOutput1), reinterpret_cast<void**>(&g_container->output1)));
374 if (error.Error() != S_OK || !g_container->output1) {
375 LOG(LS_WARNING) << "Failed to convert IDXGIOutput to IDXGIOutput1, this "
376 "usually means the system does not support DirectX 11";
377 return false;
378 }
379
380 return DuplicateOutput();
381 }
382
383 bool ScreenCapturerWinDirectx::DuplicateOutput() {
384 // We are updating the instance.
385 rtc::CritScope lock(&g_container->duplication_lock);
386 // Make sure nobody is using current instance.
387 rtc::CritScope lock2(&g_container->acquire_lock);
388 if (g_container->duplication) {
389 g_container->duplication->ReleaseFrame();
390 g_container->duplication.Reset();
391 }
392
393 for (int i = 0; i < kDuplicateOutputAttempts; i++) {
394 _com_error error = g_container->output1->DuplicateOutput(
395 static_cast<IUnknown*>(g_container->device),
396 g_container->duplication.GetAddressOf());
397 if (error.Error() == S_OK && g_container->duplication) {
398 memset(&g_container->duplication_desc, 0, sizeof(DXGI_OUTDUPL_DESC));
399 g_container->duplication->GetDesc(&g_container->duplication_desc);
400 if (g_container->duplication_desc.ModeDesc.Format !=
401 DXGI_FORMAT_B8G8R8A8_UNORM) {
402 LOG(LS_ERROR) << "IDXGIDuplicateOutput does not use RGBA (8 bit) "
403 "format, which is required by downstream components, "
404 "format is "
405 << g_container->duplication_desc.ModeDesc.Format;
406 return false;
407 }
408 return true;
409 } else {
410 // Make sure we have correct signal and duplicate the output next time.
411 g_container->duplication.Reset();
412 LOG(LS_WARNING) << "Failed to duplicate output from IDXGIOutput1, error "
413 << error.ErrorMessage() << ", with code "
414 << error.Error();
415 Sleep(kDuplicateOutputWaitMs);
416 }
417 }
418
419 return false;
420 }
421
422 ScreenCapturerWinDirectx::ScreenCapturerWinDirectx(
423 const DesktopCaptureOptions& options)
424 : callback_(nullptr), set_thread_execution_state_failed_(false) {
425 RTC_DCHECK(g_container && g_container->initialize_result);
426
427 // Texture instance won't change forever.
428 while (!surfaces_.current_frame()) {
429 surfaces_.ReplaceCurrentFrame(
430 new rtc::scoped_refptr<Texture>(new Texture()));
431 surfaces_.MoveToNextFrame();
432 }
433 }
434
435 ScreenCapturerWinDirectx::~ScreenCapturerWinDirectx() {}
436
437 void ScreenCapturerWinDirectx::Start(Callback* callback) {
438 RTC_DCHECK(!callback_);
439 RTC_DCHECK(callback);
440
441 callback_ = callback;
442 }
443
444 void ScreenCapturerWinDirectx::SetSharedMemoryFactory(
445 std::unique_ptr<SharedMemoryFactory> shared_memory_factory) {
446 shared_memory_factory_ = std::move(shared_memory_factory);
447 }
448
449 bool ScreenCapturerWinDirectx::HandleDetectUpdatedRegionError(
450 const _com_error& error,
451 const char* stage) {
452 if (error.Error() != S_OK) {
453 if (error.Error() == DXGI_ERROR_ACCESS_LOST) {
454 DuplicateOutput();
455 } else {
456 LOG(LS_ERROR) << "Failed to get " << stage << " rectangles, error "
457 << error.ErrorMessage() << ", code " << error.Error();
458 }
459 // Send entire desktop as we cannot get dirty or move rectangles.
460 return false;
461 }
462
463 return true;
464 }
465
466 bool ScreenCapturerWinDirectx::DetectUpdatedRegion(
467 const DXGI_OUTDUPL_FRAME_INFO& frame_info,
468 DesktopRegion* updated_region) {
469 RTC_DCHECK(g_container->duplication);
470 RTC_DCHECK(updated_region);
471 updated_region->Clear();
472 if (frame_info.TotalMetadataBufferSize == 0) {
473 // This should not happen, since frame_info.AccumulatedFrames > 0.
474 LOG(LS_ERROR) << "frame_info.AccumulatedFrames > 0, "
475 "but TotalMetadataBufferSize == 0";
476 return false;
477 }
478
479 if (g_container->metadata.capacity() < frame_info.TotalMetadataBufferSize) {
480 g_container->metadata.clear(); // Avoid data copy
481 g_container->metadata.reserve(frame_info.TotalMetadataBufferSize);
482 }
483
484 UINT buff_size = 0;
485 DXGI_OUTDUPL_MOVE_RECT* move_rects =
486 reinterpret_cast<DXGI_OUTDUPL_MOVE_RECT*>(g_container->metadata.data());
487 size_t move_rects_count = 0;
488 _com_error error = _com_error(g_container->duplication->GetFrameMoveRects(
489 static_cast<UINT>(g_container->metadata.capacity()),
490 move_rects, &buff_size));
491 if (!HandleDetectUpdatedRegionError(error, "move")) {
492 return false;
493 }
494 move_rects_count = buff_size / sizeof(DXGI_OUTDUPL_MOVE_RECT);
495
496 RECT* dirty_rects =
497 reinterpret_cast<RECT*>(g_container->metadata.data() + buff_size);
498 size_t dirty_rects_count = 0;
499 error = _com_error(g_container->duplication->GetFrameDirtyRects(
500 static_cast<UINT>(g_container->metadata.capacity()) - buff_size,
501 dirty_rects, &buff_size));
502 if (!HandleDetectUpdatedRegionError(error, "dirty")) {
503 return false;
504 }
505 dirty_rects_count = buff_size / sizeof(RECT);
506
507 while (move_rects_count > 0) {
508 updated_region->AddRect(DesktopRect::MakeXYWH(
509 move_rects->SourcePoint.x, move_rects->SourcePoint.y,
510 move_rects->DestinationRect.right - move_rects->DestinationRect.left,
511 move_rects->DestinationRect.bottom - move_rects->DestinationRect.top));
512 updated_region->AddRect(DesktopRect::MakeLTRB(
513 move_rects->DestinationRect.left, move_rects->DestinationRect.top,
514 move_rects->DestinationRect.right, move_rects->DestinationRect.bottom));
515 move_rects++;
516 move_rects_count--;
517 }
518
519 while (dirty_rects_count > 0) {
520 updated_region->AddRect(DesktopRect::MakeLTRB(
521 dirty_rects->left, dirty_rects->top,
522 dirty_rects->right, dirty_rects->bottom));
523 dirty_rects++;
524 dirty_rects_count--;
525 }
526
527 return true;
528 }
529
530 std::unique_ptr<DesktopFrame> ScreenCapturerWinDirectx::ProcessFrame(
531 const DXGI_OUTDUPL_FRAME_INFO& frame_info,
532 IDXGIResource* resource) {
533 RTC_DCHECK(resource);
534 RTC_DCHECK(frame_info.AccumulatedFrames > 0);
535 // We have something to update, so move to next surface.
536 surfaces_.MoveToNextFrame();
537 RTC_DCHECK(surfaces_.current_frame());
538 if (!surfaces_.current_frame()->get()->CopyFrom(frame_info, resource,
539 surfaces_.previous_frame()->get()->updated_region())) {
540 return std::unique_ptr<DesktopFrame>();
541 }
542
543 std::unique_ptr<DesktopFrame> result;
544 if (shared_memory_factory_) {
545 frames_.MoveToNextFrame();
546 // When using shared memory, |frames_| is used to store a queue of
547 // SharedMemoryDesktopFrame's.
548 if (!frames_.current_frame() ||
549 !frames_.current_frame()->size().equals(
550 surfaces_.current_frame()->get()->size())) {
551 // Current frame does not have a same size as last captured surface.
552 std::unique_ptr<DesktopFrame> new_frame =
553 SharedMemoryDesktopFrame::Create(
554 surfaces_.current_frame()->get()->size(),
555 shared_memory_factory_.get());
556 if (!new_frame) {
557 LOG(LS_ERROR) << "Failed to allocate a new SharedMemoryDesktopFrame";
558 return std::unique_ptr<DesktopFrame>();
559 }
560 frames_.ReplaceCurrentFrame(
561 SharedDesktopFrame::Wrap(new_frame.release()));
562 }
563 result.reset(frames_.current_frame()->Share());
564
565 std::unique_ptr<DesktopFrame> frame(
566 new DxgiDesktopFrame(*surfaces_.current_frame()));
567 // Copy data into SharedMemory.
568 for (DesktopRegion::Iterator it(
569 surfaces_.current_frame()->get()->copied_region());
570 !it.IsAtEnd();
571 it.Advance()) {
572 result->CopyPixelsFrom(*frame, it.rect().top_left(), it.rect());
573 }
574 } else {
575 result.reset(new DxgiDesktopFrame(*surfaces_.current_frame()));
576 }
577 RTC_DCHECK(result);
578 *result->mutable_updated_region() =
579 surfaces_.current_frame()->get()->updated_region();
580 HDC hdc = GetDC(nullptr);
581 if (hdc != nullptr) {
582 result->set_dpi(DesktopVector(GetDeviceCaps(hdc, LOGPIXELSX),
583 GetDeviceCaps(hdc, LOGPIXELSY)));
584 ReleaseDC(nullptr, hdc);
585 }
586 return result;
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 rtc::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 std::unique_ptr<DesktopFrame> result =
647 ProcessFrame(frame_info, resource.Get());
648 // DetectUpdatedRegion may release last g_container->duplication. But
649 // DuplicateOutput function will always release last frame, so there is no
650 // potential leak.
651 if (g_container->duplication) {
652 g_container->duplication->ReleaseFrame();
653 }
654 if (!result) {
655 callback_->OnCaptureCompleted(nullptr);
656 return;
657 }
658
659 result->set_capture_time_ms(
660 (rtc::TimeNanos() - capture_start_time_nanos) /
661 rtc::kNumNanosecsPerMillisec);
662 callback_->OnCaptureCompleted(result.release());
663 }
664
665 bool ScreenCapturerWinDirectx::GetScreenList(ScreenList* screens) {
666 return true;
667 }
668
669 bool ScreenCapturerWinDirectx::SelectScreen(ScreenId id) {
670 // Only full desktop capture is supported.
671 return id == kFullDesktopScreenId;
672 }
673
674 void ScreenCapturerWinDirectx::EmitCurrentFrame() {
Sergey Ulanov 2016/05/20 00:34:14 I think there is one more problem with this functi
Hzj_jie 2016/05/20 01:12:23 Done.
675 // If last callback_->OnCaptureCompleted(nullptr) does not take any effect,
676 // both frames_->current_frame() and surfaces_->current_frame() may not be
677 // consistent with screen.
Sergey Ulanov 2016/05/20 00:34:13 I don't understand this comment. OnCaptureComplete
Hzj_jie 2016/05/20 01:12:23 Done.
678 if (shared_memory_factory_) {
679 // In me2me scenario, last frame should coming from frames_ queue, if there
Sergey Ulanov 2016/05/20 00:34:13 "me2me" is a concept specific to remoting. We shou
Hzj_jie 2016/05/20 01:12:23 Done.
680 // is not an existing frame (at the very begining), we can only return a
681 // nullptr.
682 if (frames_.current_frame()) {
Sergey Ulanov 2016/05/20 00:34:13 I think the error case can be pulled out of the if
Hzj_jie 2016/05/20 01:12:23 Done.
683 std::unique_ptr<SharedDesktopFrame> frame(
684 frames_.current_frame()->Share());
685 frame->mutable_updated_region()->Clear();
686 callback_->OnCaptureCompleted(frame.release());
687 } else {
688 callback_->OnCaptureCompleted(nullptr);
689 }
690 } else {
691 // In it2me scenario, last frame should coming from surfaces_ queue, if
Sergey Ulanov 2016/05/20 00:34:13 same here. It's not about me2me vs it2me. It's abo
Hzj_jie 2016/05/20 01:12:23 Done.
692 // there is not an existing frame (at the very begining), we can only reutrn
693 // a nullptr.
694 if (surfaces_.current_frame()) {
695 std::unique_ptr<DesktopFrame> frame(
696 new DxgiDesktopFrame(*surfaces_.current_frame()));
697 callback_->OnCaptureCompleted(frame.release());
698 } else {
699 callback_->OnCaptureCompleted(nullptr);
700 }
701 }
702 }
703
704 } // namespace webrtc
OLDNEW
« no previous file with comments | « webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698