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

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