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

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: Resolve review comments 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 const DesktopVector& dpi() const { return dpi_; }
151
152 int32_t AddRef() {
153 return ++ref_count_;
154 }
155
156 int32_t Release() {
157 int32_t ref_count;
158 ref_count = --ref_count_;
159 if (ref_count == 0) {
160 delete this;
161 }
162 return ref_count;
163 }
164
165 const DesktopRegion& updated_region() {
166 return updated_region_;
167 }
168
169 const DesktopRegion& copied_region() {
170 return copied_region_;
171 }
172
173 private:
174 // Texture should only be deleted by Release function.
175 ~Texture() = default;
176
177 // Initializes stage_ from a CPU inaccessible IDXGIResource. Returns false
178 // if it fails to execute windows api.
179 bool InitializeStage(ID3D11Texture2D* texture) {
180 RTC_DCHECK(texture);
181 D3D11_TEXTURE2D_DESC desc = {0};
182 texture->GetDesc(&desc);
183 desc.BindFlags = 0;
184 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
185 desc.MiscFlags = 0;
186 desc.Usage = D3D11_USAGE_STAGING;
187 if (stage_) {
188 // Make sure stage_ and surface_ are always pointing to a same object.
189 // We need an ID3D11Texture2D instance for
190 // ID3D11DeviceContext::CopySubresourceRegion, but an IDXGISurface for
191 // IDXGISurface::Map.
192 {
193 ComPtr<IUnknown> left;
194 ComPtr<IUnknown> right;
195 bool left_result = SUCCEEDED(stage_.As(&left));
196 bool right_result = SUCCEEDED(surface_.As(&right));
197 RTC_DCHECK(left_result);
198 RTC_DCHECK(right_result);
199 RTC_DCHECK(left.Get() == right.Get());
200 }
201
202 // This buffer should be used already.
203 _com_error error = _com_error(surface_->Unmap());
204 if (error.Error() == S_OK) {
205 D3D11_TEXTURE2D_DESC current_desc;
206 stage_->GetDesc(&current_desc);
207 if (memcmp(&desc, &current_desc, sizeof(D3D11_TEXTURE2D_DESC)) == 0) {
208 return true;
209 }
210 } else {
211 // Let's recreate stage_ and surface_ later.
212 LOG(LS_ERROR) << "Failed to unmap surface, error "
213 << error.ErrorMessage() << ", code " << error.Error();
214 }
215
216 stage_.Reset();
217 surface_.Reset();
218 } else {
219 RTC_DCHECK(!surface_);
220 }
221
222 HDC hdc = GetDC(nullptr);
223 // Use old DPI value if failed.
224 if (hdc != nullptr) {
225 dpi_.set(GetDeviceCaps(hdc, LOGPIXELSX), GetDeviceCaps(hdc, LOGPIXELSY));
226 ReleaseDC(nullptr, hdc);
227 }
228
229 _com_error error = _com_error(g_container->device->CreateTexture2D(
230 &desc, nullptr, stage_.GetAddressOf()));
231 if (error.Error() != S_OK || !stage_) {
232 LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, "
233 "error "
234 << error.ErrorMessage() << ", code " << error.Error();
235 return false;
236 }
237
238 error = _com_error(stage_.As(&surface_));
239 if (error.Error() != S_OK || !surface_) {
240 LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, "
241 "error "
242 << error.ErrorMessage() << ", code " << error.Error();
243 return false;
244 }
245
246 size_.set(desc.Width, desc.Height);
247 return true;
248 }
249
250 ComPtr<ID3D11Texture2D> stage_;
251 ComPtr<IDXGISurface> surface_;
252 DXGI_MAPPED_RECT rect_;
253 DesktopSize size_;
254 Atomic32 ref_count_;
255 // The updated region from Windows API.
256 DesktopRegion updated_region_;
257 // Combination of updated regions from both current frame and previous frame.
258 DesktopRegion copied_region_;
259 // The DPI of current frame.
260 DesktopVector dpi_;
261 };
262
263 // A DesktopFrame which does not own the data buffer, and also does not have
264 // shared memory. This uses in IT2ME scenario only.
265 class ScreenCapturerWinDirectx::DxgiDesktopFrame : public DesktopFrame {
266 public:
267 DxgiDesktopFrame(
268 const rtc::scoped_refptr<ScreenCapturerWinDirectx::Texture>& texture)
269 : DesktopFrame(texture.get()->size(),
270 texture.get()->pitch(),
271 texture.get()->bits(),
272 nullptr),
273 texture_(texture) {
274 set_dpi(texture->dpi());
275 }
276
277 virtual ~DxgiDesktopFrame() {}
278
279 private:
280 // Keep a reference to the Texture instance to make sure we can still access
281 // its bytes array.
282 rtc::scoped_refptr<ScreenCapturerWinDirectx::Texture> texture_;
283 };
284
285 bool ScreenCapturerWinDirectx::Initialize() {
286 if (!g_container) {
287 rtc::GlobalLockScope lock(&g_initialize_lock);
288 if (!g_container) {
289 g_container = new DxgiContainer();
290 g_container->initialize_result = DoInitialize();
291 if (g_container->initialize_result) {
292 return true;
293 }
294
295 // Clean up if DirectX cannot work on the system.
296 if (g_container->duplication) {
297 g_container->duplication.Reset();
298 }
299
300 if (g_container->output1) {
301 g_container->output1->Release();
302 g_container->output1 = nullptr;
303 }
304
305 if (g_container->context) {
306 g_container->context->Release();
307 g_container->context = nullptr;
308 }
309
310 if (g_container->device) {
311 g_container->device->Release();
312 g_container->device = nullptr;
313 }
314
315 return false;
316 }
317 }
318
319 return g_container->initialize_result;
320 }
321
322 bool ScreenCapturerWinDirectx::DoInitialize() {
323 D3D_FEATURE_LEVEL feature_level;
324 _com_error error = D3D11CreateDevice(
325 nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
326 D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED,
327 nullptr, 0, D3D11_SDK_VERSION, &g_container->device, &feature_level,
328 &g_container->context);
329 if (error.Error() != S_OK || !g_container->device || !g_container->context) {
330 LOG(LS_WARNING) << "D3D11CreateDeivce returns error "
331 << error.ErrorMessage() << " with code " << error.Error();
332 return false;
333 }
334
335 if (feature_level < D3D_FEATURE_LEVEL_11_0) {
336 LOG(LS_WARNING) << "D3D11CreateDevice returns an instance without DirectX "
337 "11 support, level "
338 << feature_level;
339 return false;
340 }
341
342 ComPtr<IDXGIDevice> device;
343 error = _com_error(g_container->device->QueryInterface(
344 __uuidof(IDXGIDevice), reinterpret_cast<void**>(device.GetAddressOf())));
345 if (error.Error() != S_OK || !device) {
346 LOG(LS_WARNING) << "ID3D11Device is not an implementation of IDXGIDevice, "
347 "this usually means the system does not support DirectX "
348 "11";
349 return false;
350 }
351
352 ComPtr<IDXGIAdapter> adapter;
353 error = _com_error(device->GetAdapter(adapter.GetAddressOf()));
354 if (error.Error() != S_OK || !adapter) {
355 LOG(LS_WARNING) << "Failed to get an IDXGIAdapter implementation from "
356 "IDXGIDevice.";
357 return false;
358 }
359
360 ComPtr<IDXGIOutput> output;
361 for (int i = 0;; i++) {
362 error = _com_error(adapter->EnumOutputs(i, output.GetAddressOf()));
363 if (error.Error() == DXGI_ERROR_NOT_FOUND) {
364 LOG(LS_WARNING) << "No output detected.";
365 return false;
366 }
367 if (error.Error() == S_OK && output) {
368 DXGI_OUTPUT_DESC desc;
369 error = _com_error(output->GetDesc(&desc));
370 if (error.Error() == S_OK) {
371 if (desc.AttachedToDesktop) {
372 // Current output instance is the device attached to desktop.
373 break;
374 }
375 } else {
376 LOG(LS_WARNING) << "Failed to get output description of device " << i
377 << ", ignore.";
378 }
379 }
380 }
381
382 RTC_DCHECK(output);
383 error = _com_error(output.CopyTo(
384 __uuidof(IDXGIOutput1), reinterpret_cast<void**>(&g_container->output1)));
385 if (error.Error() != S_OK || !g_container->output1) {
386 LOG(LS_WARNING) << "Failed to convert IDXGIOutput to IDXGIOutput1, this "
387 "usually means the system does not support DirectX 11";
388 return false;
389 }
390
391 return DuplicateOutput();
392 }
393
394 bool ScreenCapturerWinDirectx::DuplicateOutput() {
395 // We are updating the instance.
396 rtc::CritScope lock(&g_container->duplication_lock);
397 // Make sure nobody is using current instance.
398 rtc::CritScope lock2(&g_container->acquire_lock);
399 if (g_container->duplication) {
400 g_container->duplication->ReleaseFrame();
401 g_container->duplication.Reset();
402 }
403
404 for (int i = 0; i < kDuplicateOutputAttempts; i++) {
405 _com_error error = g_container->output1->DuplicateOutput(
406 static_cast<IUnknown*>(g_container->device),
407 g_container->duplication.GetAddressOf());
408 if (error.Error() == S_OK && g_container->duplication) {
409 memset(&g_container->duplication_desc, 0, sizeof(DXGI_OUTDUPL_DESC));
410 g_container->duplication->GetDesc(&g_container->duplication_desc);
411 if (g_container->duplication_desc.ModeDesc.Format !=
412 DXGI_FORMAT_B8G8R8A8_UNORM) {
413 LOG(LS_ERROR) << "IDXGIDuplicateOutput does not use RGBA (8 bit) "
414 "format, which is required by downstream components, "
415 "format is "
416 << g_container->duplication_desc.ModeDesc.Format;
417 return false;
418 }
419 return true;
420 } else {
421 // Make sure we have correct signal and duplicate the output next time.
422 g_container->duplication.Reset();
423 LOG(LS_WARNING) << "Failed to duplicate output from IDXGIOutput1, error "
424 << error.ErrorMessage() << ", with code "
425 << error.Error();
426 Sleep(kDuplicateOutputWaitMs);
427 }
428 }
429
430 return false;
431 }
432
433 ScreenCapturerWinDirectx::ScreenCapturerWinDirectx(
434 const DesktopCaptureOptions& options)
435 : callback_(nullptr), set_thread_execution_state_failed_(false) {
436 RTC_DCHECK(g_container && g_container->initialize_result);
437
438 // Texture instance won't change forever.
439 while (!surfaces_.current_frame()) {
440 surfaces_.ReplaceCurrentFrame(
441 new rtc::scoped_refptr<Texture>(new Texture()));
442 surfaces_.MoveToNextFrame();
443 }
444 }
445
446 ScreenCapturerWinDirectx::~ScreenCapturerWinDirectx() {}
447
448 void ScreenCapturerWinDirectx::Start(Callback* callback) {
449 RTC_DCHECK(!callback_);
450 RTC_DCHECK(callback);
451
452 callback_ = callback;
453 }
454
455 void ScreenCapturerWinDirectx::SetSharedMemoryFactory(
456 std::unique_ptr<SharedMemoryFactory> shared_memory_factory) {
457 shared_memory_factory_ = std::move(shared_memory_factory);
458 }
459
460 bool ScreenCapturerWinDirectx::HandleDetectUpdatedRegionError(
461 const _com_error& error,
462 const char* stage) {
463 if (error.Error() != S_OK) {
464 if (error.Error() == DXGI_ERROR_ACCESS_LOST) {
465 DuplicateOutput();
466 } else {
467 LOG(LS_ERROR) << "Failed to get " << stage << " rectangles, error "
468 << error.ErrorMessage() << ", code " << error.Error();
469 }
470 // Send entire desktop as we cannot get dirty or move rectangles.
471 return false;
472 }
473
474 return true;
475 }
476
477 bool ScreenCapturerWinDirectx::DetectUpdatedRegion(
478 const DXGI_OUTDUPL_FRAME_INFO& frame_info,
479 DesktopRegion* updated_region) {
480 RTC_DCHECK(g_container->duplication);
481 RTC_DCHECK(updated_region);
482 updated_region->Clear();
483 if (frame_info.TotalMetadataBufferSize == 0) {
484 // This should not happen, since frame_info.AccumulatedFrames > 0.
485 LOG(LS_ERROR) << "frame_info.AccumulatedFrames > 0, "
486 "but TotalMetadataBufferSize == 0";
487 return false;
488 }
489
490 if (g_container->metadata.capacity() < frame_info.TotalMetadataBufferSize) {
491 g_container->metadata.clear(); // Avoid data copy
492 g_container->metadata.reserve(frame_info.TotalMetadataBufferSize);
493 }
494
495 UINT buff_size = 0;
496 DXGI_OUTDUPL_MOVE_RECT* move_rects =
497 reinterpret_cast<DXGI_OUTDUPL_MOVE_RECT*>(g_container->metadata.data());
498 size_t move_rects_count = 0;
499 _com_error error = _com_error(g_container->duplication->GetFrameMoveRects(
500 static_cast<UINT>(g_container->metadata.capacity()),
501 move_rects, &buff_size));
502 if (!HandleDetectUpdatedRegionError(error, "move")) {
503 return false;
504 }
505 move_rects_count = buff_size / sizeof(DXGI_OUTDUPL_MOVE_RECT);
506
507 RECT* dirty_rects =
508 reinterpret_cast<RECT*>(g_container->metadata.data() + buff_size);
509 size_t dirty_rects_count = 0;
510 error = _com_error(g_container->duplication->GetFrameDirtyRects(
511 static_cast<UINT>(g_container->metadata.capacity()) - buff_size,
512 dirty_rects, &buff_size));
513 if (!HandleDetectUpdatedRegionError(error, "dirty")) {
514 return false;
515 }
516 dirty_rects_count = buff_size / sizeof(RECT);
517
518 while (move_rects_count > 0) {
519 updated_region->AddRect(DesktopRect::MakeXYWH(
520 move_rects->SourcePoint.x, move_rects->SourcePoint.y,
521 move_rects->DestinationRect.right - move_rects->DestinationRect.left,
522 move_rects->DestinationRect.bottom - move_rects->DestinationRect.top));
523 updated_region->AddRect(DesktopRect::MakeLTRB(
524 move_rects->DestinationRect.left, move_rects->DestinationRect.top,
525 move_rects->DestinationRect.right, move_rects->DestinationRect.bottom));
526 move_rects++;
527 move_rects_count--;
528 }
529
530 while (dirty_rects_count > 0) {
531 updated_region->AddRect(DesktopRect::MakeLTRB(
532 dirty_rects->left, dirty_rects->top,
533 dirty_rects->right, dirty_rects->bottom));
534 dirty_rects++;
535 dirty_rects_count--;
536 }
537
538 return true;
539 }
540
541 std::unique_ptr<DesktopFrame> ScreenCapturerWinDirectx::ProcessFrame(
542 const DXGI_OUTDUPL_FRAME_INFO& frame_info,
543 IDXGIResource* resource) {
544 RTC_DCHECK(resource);
545 RTC_DCHECK(frame_info.AccumulatedFrames > 0);
546 // We have something to update, so move to next surface.
547 surfaces_.MoveToNextFrame();
548 RTC_DCHECK(surfaces_.current_frame());
549 if (!surfaces_.current_frame()->get()->CopyFrom(frame_info, resource,
550 surfaces_.previous_frame()->get()->updated_region())) {
551 return std::unique_ptr<DesktopFrame>();
552 }
553
554 std::unique_ptr<DesktopFrame> result;
555 if (shared_memory_factory_) {
556 frames_.MoveToNextFrame();
557 // When using shared memory, |frames_| is used to store a queue of
558 // SharedMemoryDesktopFrame's.
559 if (!frames_.current_frame() ||
560 !frames_.current_frame()->size().equals(
561 surfaces_.current_frame()->get()->size())) {
562 // Current frame does not have a same size as last captured surface.
563 std::unique_ptr<DesktopFrame> new_frame =
564 SharedMemoryDesktopFrame::Create(
565 surfaces_.current_frame()->get()->size(),
566 shared_memory_factory_.get());
567 if (!new_frame) {
568 LOG(LS_ERROR) << "Failed to allocate a new SharedMemoryDesktopFrame";
569 return std::unique_ptr<DesktopFrame>();
570 }
571 frames_.ReplaceCurrentFrame(
572 SharedDesktopFrame::Wrap(new_frame.release()));
573 }
574 result.reset(frames_.current_frame()->Share());
575
576 std::unique_ptr<DesktopFrame> frame(
577 new DxgiDesktopFrame(*surfaces_.current_frame()));
578 // Copy data into SharedMemory.
579 for (DesktopRegion::Iterator it(
580 surfaces_.current_frame()->get()->copied_region());
581 !it.IsAtEnd();
582 it.Advance()) {
583 result->CopyPixelsFrom(*frame, it.rect().top_left(), it.rect());
584 }
585 result->set_dpi(frame->dpi());
586 } else {
587 result.reset(new DxgiDesktopFrame(*surfaces_.current_frame()));
588 }
589 RTC_DCHECK(result);
590 *result->mutable_updated_region() =
591 surfaces_.current_frame()->get()->updated_region();
592 return result;
593 }
594
595 void ScreenCapturerWinDirectx::Capture(const DesktopRegion& region) {
596 RTC_DCHECK(g_container->duplication);
597 RTC_DCHECK(callback_);
598
599 if (!g_container->duplication && !DuplicateOutput()) {
600 // Receive a capture request when application is shutting down, or between
601 // mode change.
602 callback_->OnCaptureCompleted(nullptr);
603 return;
604 }
605
606 int64_t capture_start_time_nanos = rtc::TimeNanos();
607
608 if (!SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED)) {
609 if (!set_thread_execution_state_failed_) {
610 set_thread_execution_state_failed_ = true;
611 LOG(LS_WARNING) << "Failed to make system & display power assertion: "
612 << GetLastError();
613 }
614 }
615
616 DXGI_OUTDUPL_FRAME_INFO frame_info;
617 memset(&frame_info, 0, sizeof(DXGI_OUTDUPL_FRAME_INFO));
618 ComPtr<IDXGIResource> resource;
619 rtc::CritScope lock(&g_container->acquire_lock);
620 _com_error error = g_container->duplication->AcquireNextFrame(
621 kAcquireTimeoutMs, &frame_info, resource.GetAddressOf());
622 if (error.Error() == DXGI_ERROR_ACCESS_LOST) {
623 LOG(LS_ERROR) << "Access lost " << error.ErrorMessage();
624 if (DuplicateOutput()) {
625 EmitCurrentFrame();
626 } else {
627 callback_->OnCaptureCompleted(nullptr);
628 }
629 return;
630 }
631
632 if (error.Error() == DXGI_ERROR_WAIT_TIMEOUT) {
633 // Nothing changed.
634 EmitCurrentFrame();
635 return;
636 }
637
638 if (error.Error() != S_OK) {
639 LOG(LS_ERROR) << "Failed to capture frame, error " << error.ErrorMessage()
640 << ", code " << error.Error();
641 callback_->OnCaptureCompleted(nullptr);
642 return;
643 }
644
645 if (frame_info.AccumulatedFrames == 0) {
646 g_container->duplication->ReleaseFrame();
647 EmitCurrentFrame();
648 return;
649 }
650
651 // Everything looks good so far, build next frame.
652 std::unique_ptr<DesktopFrame> result =
653 ProcessFrame(frame_info, resource.Get());
654 // DetectUpdatedRegion may release last g_container->duplication. But
655 // DuplicateOutput function will always release last frame, so there is no
656 // potential leak.
657 if (g_container->duplication) {
658 g_container->duplication->ReleaseFrame();
659 }
660 if (!result) {
661 callback_->OnCaptureCompleted(nullptr);
662 return;
663 }
664
665 result->set_capture_time_ms(
666 (rtc::TimeNanos() - capture_start_time_nanos) /
667 rtc::kNumNanosecsPerMillisec);
668 callback_->OnCaptureCompleted(result.release());
669 }
670
671 bool ScreenCapturerWinDirectx::GetScreenList(ScreenList* screens) {
672 return true;
673 }
674
675 bool ScreenCapturerWinDirectx::SelectScreen(ScreenId id) {
676 // Only full desktop capture is supported.
677 return id == kFullDesktopScreenId;
678 }
679
680 void ScreenCapturerWinDirectx::EmitCurrentFrame() {
681 if (!surfaces_.current_frame()->get()->bits()) {
682 // At the very begining, we have not captured any frames.
683 callback_->OnCaptureCompleted(nullptr);
684 return;
685 }
686
687 if (shared_memory_factory_) {
688 // If shared_memory_factory_ is provided, last frame is stored in frames_
689 // queue. If there is not an existing frame (at the very begining), we can
690 // only return a nullptr.
691 if (frames_.current_frame()) {
Sergey Ulanov 2016/05/20 19:21:58 I don't think you need this. The first if in this
Hzj_jie 2016/05/20 19:44:05 Not really, if one attempts failed around line 590
692 std::unique_ptr<SharedDesktopFrame> frame(
693 frames_.current_frame()->Share());
694 frame->mutable_updated_region()->Clear();
695 callback_->OnCaptureCompleted(frame.release());
696 } else {
697 callback_->OnCaptureCompleted(nullptr);
698 }
699 return;
700 }
701
702 // If there is no shared_memory_factory_, last frame is stored in surfaces_
703 // queue.
704 std::unique_ptr<DesktopFrame> frame(
705 new DxgiDesktopFrame(*surfaces_.current_frame()));
706 callback_->OnCaptureCompleted(frame.release());
707 }
708
709 } // 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