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

Side by Side Diff: content/browser/renderer_host/media/web_contents_video_capture_device.cc

Issue 12090109: Tab Capture: Backing store readbacks to YV12 VideoFrames. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix a verb tense parallelism problem in a comment. Created 7 years, 10 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 | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 // 4 //
5 // Implementation notes: This needs to work on a variety of hardware 5 // Implementation notes: This needs to work on a variety of hardware
6 // configurations where the speed of the CPU and GPU greatly affect overall 6 // configurations where the speed of the CPU and GPU greatly affect overall
7 // performance. Therefore, the process of capturing has been split up into a 7 // performance. Therefore, the process of capturing has been split up into a
8 // pipeline of three stages. Each stage executes on its own thread: 8 // pipeline of three stages. Each stage executes on its own thread:
9 // 9 //
10 // 1. Capture: A bitmap is snapshotted/copied from the RenderView's backing 10 // 1. Capture: A bitmap is snapshotted/copied from the RenderView's backing
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
57 #include "base/time.h" 57 #include "base/time.h"
58 #include "content/browser/renderer_host/media/web_contents_capture_util.h" 58 #include "content/browser/renderer_host/media/web_contents_capture_util.h"
59 #include "content/browser/web_contents/web_contents_impl.h" 59 #include "content/browser/web_contents/web_contents_impl.h"
60 #include "content/public/browser/browser_thread.h" 60 #include "content/public/browser/browser_thread.h"
61 #include "content/public/browser/render_process_host.h" 61 #include "content/public/browser/render_process_host.h"
62 #include "content/public/browser/render_view_host.h" 62 #include "content/public/browser/render_view_host.h"
63 #include "content/public/browser/render_widget_host_view.h" 63 #include "content/public/browser/render_widget_host_view.h"
64 #include "content/public/browser/web_contents.h" 64 #include "content/public/browser/web_contents.h"
65 #include "content/public/browser/web_contents_observer.h" 65 #include "content/public/browser/web_contents_observer.h"
66 #include "media/base/bind_to_loop.h" 66 #include "media/base/bind_to_loop.h"
67 #include "media/base/video_frame.h"
67 #include "media/video/capture/video_capture_types.h" 68 #include "media/video/capture/video_capture_types.h"
68 #include "skia/ext/image_operations.h" 69 #include "skia/ext/image_operations.h"
69 #include "third_party/skia/include/core/SkBitmap.h" 70 #include "third_party/skia/include/core/SkBitmap.h"
70 #include "third_party/skia/include/core/SkColor.h" 71 #include "third_party/skia/include/core/SkColor.h"
71 #include "ui/gfx/rect.h" 72 #include "ui/gfx/rect.h"
73 #include "ui/gfx/skia_util.h"
72 74
73 // Used to self-trampoline invocation of methods to the approprate thread. This 75 // Used to self-trampoline invocation of methods to the approprate thread. This
74 // should be used sparingly, only when it's not clear which thread is invoking a 76 // should be used sparingly, only when it's not clear which thread is invoking a
75 // method. 77 // method.
76 #define ENSURE_INVOKED_ON_THREAD(thread, ...) { \ 78 #define ENSURE_INVOKED_ON_THREAD(thread, ...) { \
77 DCHECK(thread.IsRunning()); \ 79 DCHECK(thread.IsRunning()); \
78 if (MessageLoop::current() != thread.message_loop()) { \ 80 if (MessageLoop::current() != thread.message_loop()) { \
79 thread.message_loop()->PostTask(FROM_HERE, base::Bind(__VA_ARGS__)); \ 81 thread.message_loop()->PostTask(FROM_HERE, base::Bind(__VA_ARGS__)); \
80 return; \ 82 return; \
81 } \ 83 } \
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
132 fitted_width = std::max(kMinFrameWidth, MakeEven(fitted_width)); 134 fitted_width = std::max(kMinFrameWidth, MakeEven(fitted_width));
133 fitted_height = std::max(kMinFrameHeight, MakeEven(fitted_height)); 135 fitted_height = std::max(kMinFrameHeight, MakeEven(fitted_height));
134 136
135 *fitted_size = gfx::Size(fitted_width, fitted_height); 137 *fitted_size = gfx::Size(fitted_width, fitted_height);
136 } 138 }
137 139
138 // Keeps track of the RenderView to be sourced, and executes copying of the 140 // Keeps track of the RenderView to be sourced, and executes copying of the
139 // backing store on the UI BrowserThread. 141 // backing store on the UI BrowserThread.
140 class BackingStoreCopier : public WebContentsObserver { 142 class BackingStoreCopier : public WebContentsObserver {
141 public: 143 public:
142 // Result status and done callback used with StartCopy().
143 enum Result {
144 OK,
145 TRANSIENT_ERROR,
146 NO_SOURCE,
147 };
148 typedef base::Callback<void(Result result,
149 const SkBitmap& capture,
150 const base::Time& capture_time)> DoneCB;
151
152 BackingStoreCopier(int render_process_id, int render_view_id); 144 BackingStoreCopier(int render_process_id, int render_view_id);
153 145
154 // If non-NULL, use the given |override| to access the backing store. 146 // If non-NULL, use the given |override| to access the backing store.
155 // This is used for unit testing. 147 // This is used for unit testing.
156 void SetRenderWidgetHostForTesting(RenderWidgetHost* override); 148 void SetRenderWidgetHostForTesting(RenderWidgetHost* override);
157 149
158 // Starts the copy from the backing store. Must be run on the UI 150 // Starts the copy from the backing store. Must be run on the UI
159 // BrowserThread. |done_cb| is invoked with result status. When successful 151 // BrowserThread. Resulting frame is conveyed back to |consumer|.
160 // (OK), the bitmap of the capture is transferred to the callback along with 152 void StartCopy(const scoped_refptr<CaptureMachine>& consumer,
161 // the timestamp at which the capture was completed. 153 int frame_number,
162 void StartCopy(int frame_number, int desired_width, int desired_height, 154 int desired_width,
163 const DoneCB& done_cb); 155 int desired_height);
164 156
157 // content::WebContentsObserver implementation.
165 virtual void DidShowFullscreenWidget(int routing_id) OVERRIDE { 158 virtual void DidShowFullscreenWidget(int routing_id) OVERRIDE {
166 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 159 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
167 fullscreen_widget_id_ = routing_id; 160 fullscreen_widget_id_ = routing_id;
168 } 161 }
169 162
170 virtual void DidDestroyFullscreenWidget(int routing_id) OVERRIDE { 163 virtual void DidDestroyFullscreenWidget(int routing_id) OVERRIDE {
171 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 164 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
172 DCHECK_EQ(fullscreen_widget_id_, routing_id); 165 DCHECK_EQ(fullscreen_widget_id_, routing_id);
173 fullscreen_widget_id_ = MSG_ROUTING_NONE; 166 fullscreen_widget_id_ = MSG_ROUTING_NONE;
174 } 167 }
175 168
176 private: 169 private:
177 void LookUpAndObserveWebContents(); 170 void LookUpAndObserveWebContents();
178 171
179 void CopyFromBackingStoreComplete(int frame_number, 172 // Response callback for RenderWidgetHost::CopyFromBackingStore.
180 const DoneCB& done_cb, 173 void DidCopyFromBackingStore(const scoped_refptr<CaptureMachine>& consumer,
181 bool success, 174 int frame_number,
182 const SkBitmap& result); 175 const base::Time& start_time,
176 bool success,
177 const SkBitmap& frame);
178
179 // Response callback for RenderWidgetHost::CopyFromBackingStoreToVideoFrame.
180 void DidCopyFromBackingStoreToVideoFrame(
181 const scoped_refptr<CaptureMachine>& consumer,
182 int frame_number,
183 const base::Time& start_time,
184 const scoped_refptr<media::VideoFrame>& frame,
185 bool success);
183 186
184 // The "starting point" to find the capture source. 187 // The "starting point" to find the capture source.
185 const int render_process_id_; 188 const int render_process_id_;
186 const int render_view_id_; 189 const int render_view_id_;
187 190
188 // Routing ID of any active fullscreen render widget or MSG_ROUTING_NONE 191 // Routing ID of any active fullscreen render widget or MSG_ROUTING_NONE
189 // otherwise. 192 // otherwise.
190 int fullscreen_widget_id_; 193 int fullscreen_widget_id_;
191 194
192 // Last known RenderView size. 195 // Last known RenderView size.
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
242 class SynchronizedConsumer { 245 class SynchronizedConsumer {
243 public: 246 public:
244 SynchronizedConsumer(); 247 SynchronizedConsumer();
245 248
246 void SetConsumer(media::VideoCaptureDevice::EventHandler* consumer); 249 void SetConsumer(media::VideoCaptureDevice::EventHandler* consumer);
247 250
248 void OnFrameInfo(const media::VideoCaptureCapability& info); 251 void OnFrameInfo(const media::VideoCaptureCapability& info);
249 void OnError(); 252 void OnError();
250 void OnIncomingCapturedFrame(const uint8* pixels, int size, 253 void OnIncomingCapturedFrame(const uint8* pixels, int size,
251 const base::Time& timestamp); 254 const base::Time& timestamp);
255 void OnIncomingCapturedVideoFrame(
256 const scoped_refptr<media::VideoFrame>& video_frame,
257 const base::Time& timestamp);
252 258
253 private: 259 private:
254 base::Lock consumer_lock_; 260 base::Lock consumer_lock_;
255 media::VideoCaptureDevice::EventHandler* wrapped_consumer_; 261 media::VideoCaptureDevice::EventHandler* wrapped_consumer_;
256 262
257 DISALLOW_COPY_AND_ASSIGN(SynchronizedConsumer); 263 DISALLOW_COPY_AND_ASSIGN(SynchronizedConsumer);
258 }; 264 };
259 265
260 // Delivers rendered video frames to a consumer on a separate thread. Also 266 // Delivers rendered video frames to a consumer on a separate thread. Also
261 // responsible for logging the effective frame rate. 267 // responsible for logging the effective frame rate.
262 class VideoFrameDeliverer { 268 class VideoFrameDeliverer {
263 public: 269 public:
264 explicit VideoFrameDeliverer(SynchronizedConsumer* consumer); 270 explicit VideoFrameDeliverer(SynchronizedConsumer* consumer);
265 271
272 // Deliver a fully rendered ARGB frame, using SkBitmap as a container.
273 // |done_cb| will be invoked after delivery is complete.
266 void Deliver(int frame_number, 274 void Deliver(int frame_number,
267 const SkBitmap& frame_buffer, const base::Time& frame_timestamp, 275 const SkBitmap& frame_buffer,
276 const base::Time& frame_timestamp,
268 const base::Closure& done_cb); 277 const base::Closure& done_cb);
278 // Deliver a fully rendered frame YV12 frame, using VideoFrame as a container.
279 // A refcount is taken on |frame| until delivery is complete.
280 void Deliver(int frame_number,
281 const scoped_refptr<media::VideoFrame>& frame,
282 const base::Time& frame_timestamp);
269 283
270 private: 284 private:
271 void DeliverOnDeliverThread(int frame_number, 285 void DeliverOnDeliverThread(int frame_number,
272 const SkBitmap& frame_buffer, 286 const SkBitmap& frame,
273 const base::Time& frame_timestamp, 287 const base::Time& frame_timestamp,
274 const base::Closure& done_cb); 288 const base::Closure& done_cb);
289 void DeliverVideoFrameOnDeliverThread(
290 int frame_number,
291 const scoped_refptr<media::VideoFrame>& frame,
292 const base::Time& frame_timestamp);
293
294 // Treat |frame_number| as having been delivered, and update the
295 // frame rate statistics accordingly.
296 void ChronicleFrameDelivery(int frame_number);
275 297
276 base::Thread deliver_thread_; 298 base::Thread deliver_thread_;
277 SynchronizedConsumer* const consumer_; 299 SynchronizedConsumer* const consumer_;
278 300
279 // The following keep track of and log the effective frame rate (from the 301 // The following keep track of and log the effective frame rate (from the
280 // deliver stage) whenever verbose logging is turned on. 302 // deliver stage) whenever verbose logging is turned on.
281 base::Time last_frame_rate_log_time_; 303 base::Time last_frame_rate_log_time_;
282 int count_frames_rendered_; 304 int count_frames_rendered_;
283 int last_frame_number_; 305 int last_frame_number_;
284 306
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
316 fullscreen_widget_id_ = static_cast<WebContentsImpl*>(web_contents())-> 338 fullscreen_widget_id_ = static_cast<WebContentsImpl*>(web_contents())->
317 GetFullscreenWidgetRoutingID(); 339 GetFullscreenWidgetRoutingID();
318 } 340 }
319 } 341 }
320 342
321 void BackingStoreCopier::SetRenderWidgetHostForTesting( 343 void BackingStoreCopier::SetRenderWidgetHostForTesting(
322 RenderWidgetHost* override) { 344 RenderWidgetHost* override) {
323 rwh_for_testing_ = override; 345 rwh_for_testing_ = override;
324 } 346 }
325 347
326 void BackingStoreCopier::StartCopy(int frame_number,
327 int desired_width, int desired_height,
328 const DoneCB& done_cb) {
329 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
330
331 TRACE_EVENT_ASYNC_BEGIN1("mirroring", "Capture", this,
332 "frame_number", frame_number);
333
334 RenderWidgetHost* rwh;
335 if (rwh_for_testing_) {
336 rwh = rwh_for_testing_;
337 } else {
338 if (!web_contents()) { // No source yet.
339 LookUpAndObserveWebContents();
340 if (!web_contents()) { // No source ever.
341 done_cb.Run(NO_SOURCE, SkBitmap(), base::Time());
342 return;
343 }
344 }
345
346 if (fullscreen_widget_id_ != MSG_ROUTING_NONE) {
347 RenderProcessHost* process = web_contents()->GetRenderProcessHost();
348 rwh = process ? process->GetRenderWidgetHostByID(fullscreen_widget_id_)
349 : NULL;
350 } else {
351 rwh = web_contents()->GetRenderViewHost();
352 }
353
354 if (!rwh) {
355 // Transient failure state (e.g., a RenderView is being replaced).
356 done_cb.Run(TRANSIENT_ERROR, SkBitmap(), base::Time());
357 return;
358 }
359 }
360
361 gfx::Size fitted_size;
362 if (RenderWidgetHostView* const view = rwh->GetView()) {
363 const gfx::Size& view_size = view->GetViewBounds().size();
364 if (!view_size.IsEmpty()) {
365 CalculateFittedSize(view_size.width(), view_size.height(),
366 desired_width, desired_height,
367 &fitted_size);
368 }
369 if (view_size != last_view_size_) {
370 last_view_size_ = view_size;
371
372 // Measure the number of kilopixels.
373 UMA_HISTOGRAM_COUNTS_10000(
374 "TabCapture.ViewChangeKiloPixels",
375 view_size.width() * view_size.height() / 1024);
376 }
377 }
378
379 rwh->CopyFromBackingStore(
380 gfx::Rect(),
381 fitted_size,
382 base::Bind(&BackingStoreCopier::CopyFromBackingStoreComplete,
383 base::Unretained(this),
384 frame_number, done_cb));
385
386 // TODO(miu): When a tab is not visible to the user, rendering stops. For
387 // mirroring, however, it's important that rendering continues to happen.
388 }
389
390 void BackingStoreCopier::CopyFromBackingStoreComplete(
391 int frame_number,
392 const DoneCB& done_cb,
393 bool success,
394 const SkBitmap& frame) {
395 // Note: No restriction on which thread invokes this method but, currently,
396 // it's always the UI BrowserThread.
397 TRACE_EVENT_ASYNC_END1("mirroring", "Capture", this,
398 "frame_number", frame_number);
399 if (success) {
400 done_cb.Run(OK, frame, base::Time::Now());
401 } else {
402 // Capture can fail due to transient issues, so just skip this frame.
403 DVLOG(1) << "CopyFromBackingStore was not successful; skipping frame.";
404 done_cb.Run(TRANSIENT_ERROR, SkBitmap(), base::Time());
405 }
406 }
407
408 VideoFrameRenderer::VideoFrameRenderer() 348 VideoFrameRenderer::VideoFrameRenderer()
409 : render_thread_("WebContentsVideo_RenderThread") { 349 : render_thread_("WebContentsVideo_RenderThread") {
410 output_[0].in_use = false; 350 output_[0].in_use = false;
411 output_[1].in_use = false; 351 output_[1].in_use = false;
412 render_thread_.Start(); 352 render_thread_.Start();
413 } 353 }
414 354
415 void VideoFrameRenderer::Render(int frame_number, 355 void VideoFrameRenderer::Render(int frame_number,
416 const SkBitmap& capture, 356 const SkBitmap& capture,
417 int frame_width, int frame_height, 357 int frame_width, int frame_height,
(...skipping 149 matching lines...) Expand 10 before | Expand all | Expand 10 after
567 } 507 }
568 508
569 void SynchronizedConsumer::OnIncomingCapturedFrame( 509 void SynchronizedConsumer::OnIncomingCapturedFrame(
570 const uint8* pixels, int size, const base::Time& timestamp) { 510 const uint8* pixels, int size, const base::Time& timestamp) {
571 base::AutoLock guard(consumer_lock_); 511 base::AutoLock guard(consumer_lock_);
572 if (wrapped_consumer_) { 512 if (wrapped_consumer_) {
573 wrapped_consumer_->OnIncomingCapturedFrame(pixels, size, timestamp); 513 wrapped_consumer_->OnIncomingCapturedFrame(pixels, size, timestamp);
574 } 514 }
575 } 515 }
576 516
517 void SynchronizedConsumer::OnIncomingCapturedVideoFrame(
518 const scoped_refptr<media::VideoFrame>& video_frame,
519 const base::Time& timestamp) {
520 base::AutoLock guard(consumer_lock_);
521 if (wrapped_consumer_) {
522 wrapped_consumer_->OnIncomingCapturedVideoFrame(video_frame, timestamp);
523 }
524 }
525
577 VideoFrameDeliverer::VideoFrameDeliverer(SynchronizedConsumer* consumer) 526 VideoFrameDeliverer::VideoFrameDeliverer(SynchronizedConsumer* consumer)
578 : deliver_thread_("WebContentsVideo_DeliverThread"), 527 : deliver_thread_("WebContentsVideo_DeliverThread"),
579 consumer_(consumer), 528 consumer_(consumer),
580 last_frame_number_(0) { 529 last_frame_number_(0) {
581 DCHECK(consumer_); 530 DCHECK(consumer_);
582 deliver_thread_.Start(); 531 deliver_thread_.Start();
583 } 532 }
584 533
585 void VideoFrameDeliverer::Deliver( 534 void VideoFrameDeliverer::Deliver(
586 int frame_number, 535 int frame_number,
587 const SkBitmap& frame_buffer, const base::Time& frame_timestamp, 536 const SkBitmap& frame_buffer, const base::Time& frame_timestamp,
588 const base::Closure& done_cb) { 537 const base::Closure& done_cb) {
589 deliver_thread_.message_loop()->PostTask( 538 deliver_thread_.message_loop()->PostTask(
590 FROM_HERE, 539 FROM_HERE,
591 base::Bind(&VideoFrameDeliverer::DeliverOnDeliverThread, 540 base::Bind(&VideoFrameDeliverer::DeliverOnDeliverThread,
592 base::Unretained(this), 541 base::Unretained(this),
593 frame_number, base::ConstRef(frame_buffer), frame_timestamp, 542 frame_number, base::ConstRef(frame_buffer), frame_timestamp,
594 done_cb)); 543 done_cb));
595 } 544 }
596 545
546 void VideoFrameDeliverer::Deliver(
547 int frame_number,
548 const scoped_refptr<media::VideoFrame>& frame,
549 const base::Time& frame_timestamp) {
550 deliver_thread_.message_loop()->PostTask(
551 FROM_HERE,
552 base::Bind(&VideoFrameDeliverer::DeliverVideoFrameOnDeliverThread,
553 base::Unretained(this), frame_number, frame, frame_timestamp));
554 }
555
597 void VideoFrameDeliverer::DeliverOnDeliverThread( 556 void VideoFrameDeliverer::DeliverOnDeliverThread(
598 int frame_number, 557 int frame_number,
599 const SkBitmap& frame_buffer, const base::Time& frame_timestamp, 558 const SkBitmap& frame_buffer,
559 const base::Time& frame_timestamp,
600 const base::Closure& done_cb) { 560 const base::Closure& done_cb) {
601 DCHECK_EQ(deliver_thread_.message_loop(), MessageLoop::current()); 561 DCHECK_EQ(deliver_thread_.message_loop(), MessageLoop::current());
602 562
603 TRACE_EVENT1("mirroring", "DeliverFrame", "frame_number", frame_number); 563 TRACE_EVENT1("mirroring", "DeliverFrame", "frame_number", frame_number);
604 564
605 // Send the frame to the consumer. 565 // Send the frame to the consumer.
606 // Note: The consumer will do an ARGB-->YUV conversion in this callback, 566 // Note: The consumer will do an ARGB-->YUV conversion in this callback,
607 // blocking the current thread for a bit. 567 // blocking the current thread for a bit.
608 SkAutoLockPixels frame_buffer_locker(frame_buffer); 568 SkAutoLockPixels frame_buffer_locker(frame_buffer);
609 consumer_->OnIncomingCapturedFrame( 569 consumer_->OnIncomingCapturedFrame(
610 static_cast<const uint8*>(frame_buffer.getPixels()), 570 static_cast<const uint8*>(frame_buffer.getPixels()),
611 frame_buffer.getSize(), 571 frame_buffer.getSize(),
612 frame_timestamp); 572 frame_timestamp);
613 573
574 ChronicleFrameDelivery(frame_number);
575
576 // All done.
577 done_cb.Run();
578 }
579
580 void VideoFrameDeliverer::DeliverVideoFrameOnDeliverThread(
581 int frame_number,
582 const scoped_refptr<media::VideoFrame>& frame,
583 const base::Time& frame_timestamp) {
584 DCHECK_EQ(deliver_thread_.message_loop(), MessageLoop::current());
585
586 TRACE_EVENT1("mirroring", "DeliverFrame", "frame_number", frame_number);
587
588 // Send the frame to the consumer.
589 consumer_->OnIncomingCapturedVideoFrame(frame, frame_timestamp);
590
591 ChronicleFrameDelivery(frame_number);
592 }
593
594 void VideoFrameDeliverer::ChronicleFrameDelivery(int frame_number) {
614 // Log frame rate, if verbose logging is turned on. 595 // Log frame rate, if verbose logging is turned on.
615 static const base::TimeDelta kFrameRateLogInterval = 596 static const base::TimeDelta kFrameRateLogInterval =
616 base::TimeDelta::FromSeconds(10); 597 base::TimeDelta::FromSeconds(10);
617 const base::Time& now = base::Time::Now(); 598 const base::Time& now = base::Time::Now();
618 if (last_frame_rate_log_time_.is_null()) { 599 if (last_frame_rate_log_time_.is_null()) {
619 last_frame_rate_log_time_ = now; 600 last_frame_rate_log_time_ = now;
620 count_frames_rendered_ = 0; 601 count_frames_rendered_ = 0;
621 last_frame_number_ = frame_number; 602 last_frame_number_ = frame_number;
622 } else { 603 } else {
623 ++count_frames_rendered_; 604 ++count_frames_rendered_;
(...skipping 10 matching lines...) Expand all
634 UMA_HISTOGRAM_COUNTS( 615 UMA_HISTOGRAM_COUNTS(
635 "TabCapture.FrameRate", 616 "TabCapture.FrameRate",
636 static_cast<int>(measured_fps)); 617 static_cast<int>(measured_fps));
637 VLOG(1) << "Current measured frame rate for CaptureMachine@" << this 618 VLOG(1) << "Current measured frame rate for CaptureMachine@" << this
638 << " is " << measured_fps << " FPS."; 619 << " is " << measured_fps << " FPS.";
639 last_frame_rate_log_time_ = now; 620 last_frame_rate_log_time_ = now;
640 count_frames_rendered_ = 0; 621 count_frames_rendered_ = 0;
641 last_frame_number_ = frame_number; 622 last_frame_number_ = frame_number;
642 } 623 }
643 } 624 }
644
645 // All done.
646 done_cb.Run();
647 } 625 }
648 626
649 } // namespace 627 } // namespace
650 628
651 // The "meat" of the video capture implementation, which is a ref-counted class. 629 // The "meat" of the video capture implementation, which is a ref-counted class.
652 // Separating this from the "shell class" WebContentsVideoCaptureDevice allows 630 // Separating this from the "shell class" WebContentsVideoCaptureDevice allows
653 // safe destruction without needing to block any threads (e.g., the IO 631 // safe destruction without needing to block any threads (e.g., the IO
654 // BrowserThread). 632 // BrowserThread).
655 // 633 //
656 // CaptureMachine manages a simple state machine and the pipeline (see notes at 634 // CaptureMachine manages a simple state machine and the pipeline (see notes at
657 // top of this file). It times the start of successive captures and 635 // top of this file). It times the start of successive captures and
658 // facilitates the processing of each through the stages of the pipeline. 636 // facilitates the processing of each through the stages of the pipeline.
659 class CaptureMachine 637 class CaptureMachine
660 : public base::RefCountedThreadSafe<CaptureMachine, CaptureMachine> { 638 : public base::RefCountedThreadSafe<CaptureMachine, CaptureMachine> {
661 public: 639 public:
640 enum SnapshotError {
641 NO_SOURCE,
642 TRANSIENT_ERROR
643 };
644
662 CaptureMachine(int render_process_id, int render_view_id); 645 CaptureMachine(int render_process_id, int render_view_id);
663 646
664 // Sets the capture source to the given |override| for unit testing. 647 // Sets the capture source to the given |override| for unit testing.
665 // Also, |destroy_cb| will be invoked after CaptureMachine is fully destroyed 648 // Also, |destroy_cb| will be invoked after CaptureMachine is fully destroyed
666 // (to synchronize tear-down). 649 // (to synchronize tear-down).
667 void InitializeForTesting(RenderWidgetHost* override, 650 void InitializeForTesting(RenderWidgetHost* override,
668 const base::Closure& destroy_cb); 651 const base::Closure& destroy_cb);
669 652
670 // Synchronously sets/unsets the consumer. Pass |consumer| as NULL to remove 653 // Synchronously sets/unsets the consumer. Pass |consumer| as NULL to remove
671 // the reference to the consumer; then, once this method returns, 654 // the reference to the consumer; then, once this method returns,
672 // CaptureMachine will no longer invoke callbacks on the old consumer from any 655 // CaptureMachine will no longer invoke callbacks on the old consumer from any
673 // thread. 656 // thread.
674 void SetConsumer(media::VideoCaptureDevice::EventHandler* consumer); 657 void SetConsumer(media::VideoCaptureDevice::EventHandler* consumer);
675 658
676 // Asynchronous requests to change CaptureMachine state. 659 // Asynchronous requests to change CaptureMachine state.
677 void Allocate(int width, int height, int frame_rate); 660 void Allocate(int width, int height, int frame_rate);
678 void Start(); 661 void Start();
679 void Stop(); 662 void Stop();
680 void DeAllocate(); 663 void DeAllocate();
681 664
665 // Snapshot result events.
666 void OnSnapshotComplete(int frame_number,
667 const base::Time& start_time,
668 const base::TimeDelta& duration,
669 const SkBitmap& frame);
670 void OnSnapshotComplete(int frame_number,
671 const base::Time& start_time,
672 const base::TimeDelta& duration,
673 const scoped_refptr<media::VideoFrame>& frame);
674 void OnSnapshotFailed(SnapshotError error,
675 int frame_number);
676
682 private: 677 private:
683 friend class base::RefCountedThreadSafe<CaptureMachine, CaptureMachine>; 678 friend class base::RefCountedThreadSafe<CaptureMachine, CaptureMachine>;
684 679
685 // Flag indicating current state. 680 // Flag indicating current state.
686 enum State { 681 enum State {
687 kIdle, 682 kIdle,
688 kAllocated, 683 kAllocated,
689 kCapturing, 684 kCapturing,
690 kError, 685 kError,
691 kDestroyed 686 kDestroyed
692 }; 687 };
693 688
694 virtual ~CaptureMachine(); 689 virtual ~CaptureMachine();
695 690
696 void TransitionStateTo(State next_state); 691 void TransitionStateTo(State next_state);
697 692
698 // Stops capturing and notifies consumer_ of an error state. 693 // Stops capturing and notifies consumer_ of an error state.
699 void Error(); 694 void Error();
700 695
701 // Schedules the next frame capture off of the system clock, skipping frames 696 // Schedules the next frame capture off of the system clock, skipping frames
702 // to catch-up if necessary. 697 // to catch-up if necessary.
703 void ScheduleNextFrameCapture(); 698 void ScheduleNextFrameCapture();
704 699
705 // The glue between the pipeline stages. 700 // The glue between the pipeline stages.
706 void StartSnapshot(); 701 void StartSnapshot();
707 void SnapshotComplete(int frame_number, 702 bool FinishSnapshot();
708 const base::Time& start_time, 703 void SnapshotCompleteBitmap(int frame_number,
709 BackingStoreCopier::Result result, 704 const base::Time& start_time,
710 const SkBitmap& capture, 705 const base::TimeDelta& duration,
711 const base::Time& capture_time); 706 const SkBitmap& frame);
707 void SnapshotCompleteVideoFrame(
708 int frame_number,
709 const base::Time& start_time,
710 const base::TimeDelta& duration,
711 const scoped_refptr<media::VideoFrame>& frame);
712 void SnapshotFailed(SnapshotError error, int frame_number);
713
712 void RenderComplete(int frame_number, 714 void RenderComplete(int frame_number,
713 const base::Time& capture_time, 715 const base::Time& capture_time,
714 const SkBitmap* frame_buffer); 716 const SkBitmap* frame_buffer);
715 void DeliverComplete(const SkBitmap* frame_buffer); 717 void DeliverComplete(const SkBitmap* frame_buffer);
716 718
717 // Specialized RefCounted traits for CaptureMachine, so that operator delete 719 // Specialized RefCounted traits for CaptureMachine, so that operator delete
718 // is called from an "outside" thread. See comments for "traits" in 720 // is called from an "outside" thread. See comments for "traits" in
719 // base/memory/ref_counted.h. 721 // base/memory/ref_counted.h.
720 static void Destruct(const CaptureMachine* x); 722 static void Destruct(const CaptureMachine* x);
721 static void DeleteFromOutsideThread(const CaptureMachine* x); 723 static void DeleteFromOutsideThread(const CaptureMachine* x);
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
789 if (width < kMinFrameWidth || height < kMinFrameHeight) { 791 if (width < kMinFrameWidth || height < kMinFrameHeight) {
790 DVLOG(1) << "invalid width (" << width << ") and/or height (" 792 DVLOG(1) << "invalid width (" << width << ") and/or height ("
791 << height << ")"; 793 << height << ")";
792 Error(); 794 Error();
793 return; 795 return;
794 } 796 }
795 797
796 settings_.width = width; 798 settings_.width = width;
797 settings_.height = height; 799 settings_.height = height;
798 settings_.frame_rate = frame_rate; 800 settings_.frame_rate = frame_rate;
801 // Sets the color format used by OnIncomingCapturedFrame().
802 // Does not apply to OnIncomingCapturedVideoFrame().
799 settings_.color = media::VideoCaptureCapability::kARGB; 803 settings_.color = media::VideoCaptureCapability::kARGB;
800 settings_.expected_capture_delay = 0; 804 settings_.expected_capture_delay = 0;
801 settings_.interlaced = false; 805 settings_.interlaced = false;
802 806
803 capture_period_ = base::TimeDelta::FromMicroseconds( 807 capture_period_ = base::TimeDelta::FromMicroseconds(
804 1000000.0 / settings_.frame_rate + 0.5); 808 1000000.0 / settings_.frame_rate + 0.5);
805 809
806 consumer_.OnFrameInfo(settings_); 810 consumer_.OnFrameInfo(settings_);
807 811
808 TransitionStateTo(kAllocated); 812 TransitionStateTo(kAllocated);
(...skipping 124 matching lines...) Expand 10 before | Expand all | Expand 10 after
933 void CaptureMachine::StartSnapshot() { 937 void CaptureMachine::StartSnapshot() {
934 DCHECK_EQ(manager_thread_.message_loop(), MessageLoop::current()); 938 DCHECK_EQ(manager_thread_.message_loop(), MessageLoop::current());
935 939
936 if (state_ != kCapturing) { 940 if (state_ != kCapturing) {
937 return; 941 return;
938 } 942 }
939 943
940 if (!is_snapshotting_) { 944 if (!is_snapshotting_) {
941 is_snapshotting_ = true; 945 is_snapshotting_ = true;
942 946
943 const BackingStoreCopier::DoneCB& done_cb = 947 BrowserThread::PostTask(
944 media::BindToLoop(manager_thread_.message_loop_proxy(), 948 BrowserThread::UI, FROM_HERE,
945 base::Bind(&CaptureMachine::SnapshotComplete, this, 949 base::Bind(&BackingStoreCopier::StartCopy, base::Unretained(&copier_),
946 frame_number_, base::Time::Now())); 950 make_scoped_refptr(this), frame_number_, settings_.width,
947 const base::Closure& start_cb = 951 settings_.height));
948 base::Bind(&BackingStoreCopier::StartCopy,
949 base::Unretained(&copier_),
950 frame_number_, settings_.width, settings_.height, done_cb);
951 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, start_cb);
952 } 952 }
953 953
954 ScheduleNextFrameCapture(); 954 ScheduleNextFrameCapture();
955 } 955 }
956 956
957 void CaptureMachine::SnapshotComplete(int frame_number, 957 bool CaptureMachine::FinishSnapshot() {
958 const base::Time& start_time,
959 BackingStoreCopier::Result result,
960 const SkBitmap& capture,
961 const base::Time& capture_time) {
962 DCHECK_EQ(manager_thread_.message_loop(), MessageLoop::current()); 958 DCHECK_EQ(manager_thread_.message_loop(), MessageLoop::current());
963 959
964 DCHECK(is_snapshotting_); 960 DCHECK(is_snapshotting_);
965 is_snapshotting_ = false; 961 is_snapshotting_ = false;
966 962
967 if (state_ != kCapturing) { 963 return state_ == kCapturing;
964 }
965
966 void CaptureMachine::OnSnapshotComplete(int frame_number,
967 const base::Time& start_time,
968 const base::TimeDelta& duration,
969 const SkBitmap& frame) {
970 manager_thread_.message_loop()->PostTask(
971 FROM_HERE,
972 base::Bind(&CaptureMachine::SnapshotCompleteBitmap, this,
973 frame_number, start_time, duration, frame));
974 }
975
976 void CaptureMachine::SnapshotCompleteBitmap(int frame_number,
977 const base::Time& start_time,
978 const base::TimeDelta& duration,
979 const SkBitmap& capture) {
980 if (!FinishSnapshot())
968 return; 981 return;
969 }
970 982
971 switch (result) { 983 UMA_HISTOGRAM_TIMES("TabCapture.SnapshotTime", duration);
972 case BackingStoreCopier::OK: 984 if (num_renders_pending_ <= 1) {
973 UMA_HISTOGRAM_TIMES("TabCapture.SnapshotTime", 985 ++num_renders_pending_;
974 base::Time::Now() - start_time); 986 renderer_.Render(
975 if (num_renders_pending_ <= 1) { 987 frame_number,
976 ++num_renders_pending_; 988 capture,
977 DCHECK(!capture_time.is_null()); 989 settings_.width, settings_.height,
978 renderer_.Render( 990 media::BindToLoop(manager_thread_.message_loop_proxy(),
979 frame_number, 991 base::Bind(&CaptureMachine::RenderComplete, this,
980 capture, 992 frame_number, start_time + duration)));
981 settings_.width, settings_.height,
982 media::BindToLoop(manager_thread_.message_loop_proxy(),
983 base::Bind(&CaptureMachine::RenderComplete, this,
984 frame_number, capture_time)));
985 }
986 break;
987
988 case BackingStoreCopier::TRANSIENT_ERROR:
989 // Skip this frame.
990 break;
991
992 case BackingStoreCopier::NO_SOURCE:
993 DVLOG(1) << "no capture source";
994 Error();
995 break;
996 } 993 }
997 } 994 }
998 995
996 void CaptureMachine::OnSnapshotComplete(
997 int frame_number,
998 const base::Time& start_time,
999 const base::TimeDelta& duration,
1000 const scoped_refptr<media::VideoFrame>& frame) {
1001 manager_thread_.message_loop()->PostTask(
1002 FROM_HERE,
1003 base::Bind(&CaptureMachine::SnapshotCompleteVideoFrame, this,
1004 frame_number, start_time, duration, frame));
1005 }
1006
1007 void CaptureMachine::SnapshotCompleteVideoFrame(
1008 int frame_number,
1009 const base::Time& start_time,
1010 const base::TimeDelta& duration,
1011 const scoped_refptr<media::VideoFrame>& frame) {
1012 if (!FinishSnapshot())
1013 return;
1014
1015 UMA_HISTOGRAM_TIMES("TabCapture.SnapshotTime", duration);
1016
1017 deliverer_.Deliver(frame_number, frame, start_time + duration);
1018 }
1019
1020 void CaptureMachine::OnSnapshotFailed(CaptureMachine::SnapshotError error,
1021 int frame_number) {
1022 manager_thread_.message_loop()->PostTask(FROM_HERE,
1023 base::Bind(&CaptureMachine::SnapshotFailed, this, error, frame_number));
1024 }
1025
1026 void CaptureMachine::SnapshotFailed(CaptureMachine::SnapshotError error,
1027 int frame_number) {
1028 if (!FinishSnapshot())
1029 return;
1030
1031 if (error == NO_SOURCE)
1032 Error();
1033 }
1034
999 void CaptureMachine::RenderComplete(int frame_number, 1035 void CaptureMachine::RenderComplete(int frame_number,
1000 const base::Time& capture_time, 1036 const base::Time& capture_time,
1001 const SkBitmap* frame_buffer) { 1037 const SkBitmap* frame_buffer) {
1002 DCHECK_EQ(manager_thread_.message_loop(), MessageLoop::current()); 1038 DCHECK_EQ(manager_thread_.message_loop(), MessageLoop::current());
1003 1039
1004 --num_renders_pending_; 1040 --num_renders_pending_;
1005 DCHECK_LE(0, num_renders_pending_); 1041 DCHECK_LE(0, num_renders_pending_);
1006 1042
1007 if (state_ != kCapturing || !frame_buffer) { 1043 if (state_ != kCapturing || !frame_buffer) {
1008 return; 1044 return;
1009 } 1045 }
1010 1046
1011 DCHECK(!capture_time.is_null()); 1047 DCHECK(!capture_time.is_null());
1012 DCHECK(frame_buffer); 1048 DCHECK(frame_buffer);
1013 deliverer_.Deliver( 1049 deliverer_.Deliver(
1014 frame_number, *frame_buffer, capture_time, 1050 frame_number, *frame_buffer, capture_time,
1015 base::Bind(&CaptureMachine::DeliverComplete, this, frame_buffer)); 1051 base::Bind(&CaptureMachine::DeliverComplete, this, frame_buffer));
1016 } 1052 }
1017 1053
1018 void CaptureMachine::DeliverComplete(const SkBitmap* frame_buffer) { 1054 void CaptureMachine::DeliverComplete(const SkBitmap* frame_buffer) {
1019 renderer_.Release(frame_buffer); 1055 renderer_.Release(frame_buffer);
1020 } 1056 }
1021 1057
1058 void BackingStoreCopier::StartCopy(
1059 const scoped_refptr<CaptureMachine>& consumer,
1060 int frame_number,
1061 int desired_width,
1062 int desired_height) {
1063 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1064
1065 RenderWidgetHost* rwh;
1066 if (rwh_for_testing_) {
1067 rwh = rwh_for_testing_;
1068 } else {
1069 if (!web_contents()) { // No source yet.
1070 LookUpAndObserveWebContents();
1071 if (!web_contents()) { // No source ever.
1072 consumer->OnSnapshotFailed(CaptureMachine::NO_SOURCE, frame_number);
1073 return;
1074 }
1075 }
1076
1077 if (fullscreen_widget_id_ != MSG_ROUTING_NONE) {
1078 RenderProcessHost* process = web_contents()->GetRenderProcessHost();
1079 rwh = process ? process->GetRenderWidgetHostByID(fullscreen_widget_id_)
1080 : NULL;
1081 } else {
1082 rwh = web_contents()->GetRenderViewHost();
1083 }
1084
1085 if (!rwh) {
1086 // Transient failure state (e.g., a RenderView is being replaced).
1087 consumer->OnSnapshotFailed(CaptureMachine::TRANSIENT_ERROR, frame_number);
1088 return;
1089 }
1090 }
1091
1092 gfx::Size fitted_size;
1093 if (RenderWidgetHostView* const view = rwh->GetView()) {
1094 const gfx::Size& view_size = view->GetViewBounds().size();
1095 if (!view_size.IsEmpty()) {
1096 CalculateFittedSize(view_size.width(), view_size.height(),
1097 desired_width, desired_height,
1098 &fitted_size);
1099 }
1100 if (view_size != last_view_size_) {
1101 last_view_size_ = view_size;
1102
1103 // Measure the number of kilopixels.
1104 UMA_HISTOGRAM_COUNTS_10000(
1105 "TabCapture.ViewChangeKiloPixels",
1106 view_size.width() * view_size.height() / 1024);
1107 }
1108 }
1109
1110 TRACE_EVENT_ASYNC_BEGIN1("mirroring", "Capture", this,
1111 "frame_number", frame_number);
1112 if (rwh->CanCopyToVideoFrame()) {
1113 gfx::Size dst_size(desired_width, desired_height);
1114 scoped_refptr<media::VideoFrame> video_frame(
1115 media::VideoFrame::CreateFrame(
1116 media::VideoFrame::YV12,
1117 dst_size,
1118 gfx::Rect(dst_size),
1119 dst_size,
1120 base::TimeDelta()));
1121
1122 rwh->CopyFromBackingStoreToVideoFrame(
1123 gfx::Rect(),
1124 video_frame,
1125 base::Bind(&BackingStoreCopier::DidCopyFromBackingStoreToVideoFrame,
1126 base::Unretained(this), consumer, frame_number,
1127 base::Time::Now(), video_frame));
1128 } else {
1129 rwh->CopyFromBackingStore(
1130 gfx::Rect(),
1131 fitted_size,
1132 base::Bind(&BackingStoreCopier::DidCopyFromBackingStore,
1133 base::Unretained(this), consumer, frame_number,
1134 base::Time::Now()));
1135 }
1136 // TODO(miu): When a tab is not visible to the user, rendering stops. For
1137 // mirroring, however, it's important that rendering continues to happen.
1138 }
1139
1140 void BackingStoreCopier::DidCopyFromBackingStore(
1141 const scoped_refptr<CaptureMachine>& consumer,
1142 int frame_number,
1143 const base::Time& start_time,
1144 bool success,
1145 const SkBitmap& frame) {
1146 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1147 // Note: No restriction on which thread invokes this method but, currently,
1148 // it's always the UI BrowserThread.
1149 TRACE_EVENT_ASYNC_END1("mirroring", "Capture", this,
1150 "frame_number", frame_number);
1151
1152 if (success) {
1153 consumer->OnSnapshotComplete(
1154 frame_number, start_time, base::Time::Now() - start_time, frame);
1155 } else {
1156 // Capture can fail due to transient issues, so just skip this frame.
1157 DVLOG(1) << "CopyFromBackingStore was not successful; skipping frame.";
1158 consumer->OnSnapshotFailed(CaptureMachine::TRANSIENT_ERROR, frame_number);
1159 }
1160 }
1161
1162 void BackingStoreCopier::DidCopyFromBackingStoreToVideoFrame(
1163 const scoped_refptr<CaptureMachine>& consumer,
1164 int frame_number,
1165 const base::Time& start_time,
1166 const scoped_refptr<media::VideoFrame>& frame,
1167 bool success) {
1168 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1169 // Note: No restriction on which thread invokes this method but, currently,
1170 // it's always the UI BrowserThread.
1171 TRACE_EVENT_ASYNC_END1("mirroring", "Capture", this,
1172 "frame_number", frame_number);
1173
1174 if (frame && frame->format() != media::VideoFrame::INVALID &&
1175 frame->format() != media::VideoFrame::EMPTY) {
1176 consumer->OnSnapshotComplete(
1177 frame_number, start_time, base::Time::Now() - start_time, frame);
1178 } else {
1179 // Capture can fail due to transient issues, so just skip this frame.
1180 DVLOG(1) << "CopyFromBackingStoreToVideoFrame failure; skipping frame.";
1181 consumer->OnSnapshotFailed(
1182 CaptureMachine::TRANSIENT_ERROR, frame_number);
1183 }
1184 }
1185
1022 WebContentsVideoCaptureDevice::WebContentsVideoCaptureDevice( 1186 WebContentsVideoCaptureDevice::WebContentsVideoCaptureDevice(
1023 const media::VideoCaptureDevice::Name& name, 1187 const media::VideoCaptureDevice::Name& name,
1024 int render_process_id, int render_view_id) 1188 int render_process_id, int render_view_id)
1025 : device_name_(name), 1189 : device_name_(name),
1026 capturer_(new CaptureMachine(render_process_id, render_view_id)) {} 1190 capturer_(new CaptureMachine(render_process_id, render_view_id)) {}
1027 1191
1028 WebContentsVideoCaptureDevice::WebContentsVideoCaptureDevice( 1192 WebContentsVideoCaptureDevice::WebContentsVideoCaptureDevice(
1029 RenderWidgetHost* test_source, const base::Closure& destroy_cb) 1193 RenderWidgetHost* test_source, const base::Closure& destroy_cb)
1030 : capturer_(new CaptureMachine(-1, -1)) { 1194 : capturer_(new CaptureMachine(-1, -1)) {
1031 device_name_.device_name = "WebContentsForTesting"; 1195 device_name_.device_name = "WebContentsForTesting";
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
1087 capturer_->SetConsumer(NULL); 1251 capturer_->SetConsumer(NULL);
1088 capturer_->DeAllocate(); 1252 capturer_->DeAllocate();
1089 } 1253 }
1090 1254
1091 const media::VideoCaptureDevice::Name& 1255 const media::VideoCaptureDevice::Name&
1092 WebContentsVideoCaptureDevice::device_name() { 1256 WebContentsVideoCaptureDevice::device_name() {
1093 return device_name_; 1257 return device_name_;
1094 } 1258 }
1095 1259
1096 } // namespace content 1260 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698