Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / compositor / delegated_frame_host.cc
blobb8a8ad45153eabff883f7f53ab830ff7821c69b9
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/compositor/delegated_frame_host.h"
7 #include "base/callback_helpers.h"
8 #include "base/command_line.h"
9 #include "base/time/default_tick_clock.h"
10 #include "cc/output/compositor_frame.h"
11 #include "cc/output/compositor_frame_ack.h"
12 #include "cc/output/copy_output_request.h"
13 #include "cc/resources/single_release_callback.h"
14 #include "cc/resources/texture_mailbox.h"
15 #include "cc/surfaces/surface.h"
16 #include "cc/surfaces/surface_factory.h"
17 #include "cc/surfaces/surface_hittest.h"
18 #include "cc/surfaces/surface_manager.h"
19 #include "content/browser/compositor/resize_lock.h"
20 #include "content/browser/compositor/surface_utils.h"
21 #include "content/browser/gpu/compositor_util.h"
22 #include "content/common/gpu/client/gl_helper.h"
23 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
24 #include "content/public/common/content_switches.h"
25 #include "media/base/video_frame.h"
26 #include "media/base/video_util.h"
27 #include "skia/ext/image_operations.h"
28 #include "third_party/skia/include/core/SkCanvas.h"
29 #include "third_party/skia/include/core/SkPaint.h"
30 #include "third_party/skia/include/effects/SkLumaColorFilter.h"
31 #include "ui/gfx/geometry/dip_util.h"
33 namespace content {
35 namespace {
37 void SatisfyCallback(cc::SurfaceManager* manager,
38 cc::SurfaceSequence sequence) {
39 std::vector<uint32_t> sequences;
40 sequences.push_back(sequence.sequence);
41 manager->DidSatisfySequences(sequence.id_namespace, &sequences);
44 void RequireCallback(cc::SurfaceManager* manager,
45 cc::SurfaceId id,
46 cc::SurfaceSequence sequence) {
47 cc::Surface* surface = manager->GetSurfaceForId(id);
48 if (!surface) {
49 LOG(ERROR) << "Attempting to require callback on nonexistent surface";
50 return;
52 surface->AddDestructionDependency(sequence);
55 } // namespace
57 ////////////////////////////////////////////////////////////////////////////////
58 // DelegatedFrameHost
60 DelegatedFrameHost::DelegatedFrameHost(DelegatedFrameHostClient* client)
61 : client_(client),
62 compositor_(nullptr),
63 use_surfaces_(UseSurfacesEnabled()),
64 tick_clock_(new base::DefaultTickClock()),
65 last_output_surface_id_(0),
66 pending_delegated_ack_count_(0),
67 skipped_frames_(false),
68 current_scale_factor_(1.f),
69 can_lock_compositor_(YES_CAN_LOCK),
70 delegated_frame_evictor_(new DelegatedFrameEvictor(this)) {
71 ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
72 factory->AddObserver(this);
73 id_allocator_ = factory->GetContextFactory()->CreateSurfaceIdAllocator();
76 void DelegatedFrameHost::WasShown(const ui::LatencyInfo& latency_info) {
77 delegated_frame_evictor_->SetVisible(true);
79 if (surface_id_.is_null() && !frame_provider_.get() &&
80 !released_front_lock_.get()) {
81 if (compositor_)
82 released_front_lock_ = compositor_->GetCompositorLock();
85 if (compositor_) {
86 compositor_->SetLatencyInfo(latency_info);
90 bool DelegatedFrameHost::HasSavedFrame() {
91 return delegated_frame_evictor_->HasFrame();
94 void DelegatedFrameHost::WasHidden() {
95 delegated_frame_evictor_->SetVisible(false);
96 released_front_lock_ = NULL;
99 void DelegatedFrameHost::MaybeCreateResizeLock() {
100 if (!ShouldCreateResizeLock())
101 return;
102 DCHECK(compositor_);
104 bool defer_compositor_lock =
105 can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
106 can_lock_compositor_ == NO_PENDING_COMMIT;
108 if (can_lock_compositor_ == YES_CAN_LOCK)
109 can_lock_compositor_ = YES_DID_LOCK;
111 resize_lock_ =
112 client_->DelegatedFrameHostCreateResizeLock(defer_compositor_lock);
115 bool DelegatedFrameHost::ShouldCreateResizeLock() {
116 if (!client_->DelegatedFrameCanCreateResizeLock())
117 return false;
119 if (resize_lock_)
120 return false;
122 gfx::Size desired_size = client_->DelegatedFrameHostDesiredSizeInDIP();
123 if (desired_size == current_frame_size_in_dip_ || desired_size.IsEmpty())
124 return false;
126 if (!compositor_)
127 return false;
129 return true;
132 void DelegatedFrameHost::CopyFromCompositingSurface(
133 const gfx::Rect& src_subrect,
134 const gfx::Size& output_size,
135 ReadbackRequestCallback& callback,
136 const SkColorType preferred_color_type) {
137 // Only ARGB888 and RGB565 supported as of now.
138 bool format_support = ((preferred_color_type == kAlpha_8_SkColorType) ||
139 (preferred_color_type == kRGB_565_SkColorType) ||
140 (preferred_color_type == kN32_SkColorType));
141 DCHECK(format_support);
142 if (!CanCopyToBitmap()) {
143 callback.Run(SkBitmap(), content::READBACK_SURFACE_UNAVAILABLE);
144 return;
147 scoped_ptr<cc::CopyOutputRequest> request =
148 cc::CopyOutputRequest::CreateRequest(
149 base::Bind(&DelegatedFrameHost::CopyFromCompositingSurfaceHasResult,
150 output_size, preferred_color_type, callback));
151 if (!src_subrect.IsEmpty())
152 request->set_area(src_subrect);
153 RequestCopyOfOutput(request.Pass());
156 void DelegatedFrameHost::CopyFromCompositingSurfaceToVideoFrame(
157 const gfx::Rect& src_subrect,
158 const scoped_refptr<media::VideoFrame>& target,
159 const base::Callback<void(bool)>& callback) {
160 if (!CanCopyToVideoFrame()) {
161 callback.Run(false);
162 return;
165 scoped_ptr<cc::CopyOutputRequest> request =
166 cc::CopyOutputRequest::CreateRequest(base::Bind(
167 &DelegatedFrameHost::
168 CopyFromCompositingSurfaceHasResultForVideo,
169 AsWeakPtr(), // For caching the ReadbackYUVInterface on this class.
170 nullptr,
171 target,
172 callback));
173 request->set_area(src_subrect);
174 RequestCopyOfOutput(request.Pass());
177 bool DelegatedFrameHost::CanCopyToBitmap() const {
178 return compositor_ &&
179 client_->DelegatedFrameHostGetLayer()->has_external_content();
182 bool DelegatedFrameHost::CanCopyToVideoFrame() const {
183 return compositor_ &&
184 client_->DelegatedFrameHostGetLayer()->has_external_content();
187 bool DelegatedFrameHost::CanSubscribeFrame() const {
188 return true;
191 void DelegatedFrameHost::BeginFrameSubscription(
192 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
193 frame_subscriber_ = subscriber.Pass();
196 void DelegatedFrameHost::EndFrameSubscription() {
197 idle_frame_subscriber_textures_.clear();
198 frame_subscriber_.reset();
201 uint32_t DelegatedFrameHost::GetSurfaceIdNamespace() {
202 if (!use_surfaces_)
203 return 0;
205 return id_allocator_->id_namespace();
208 cc::SurfaceId DelegatedFrameHost::SurfaceIdAtPoint(
209 const gfx::Point& point,
210 gfx::Point* transformed_point) {
211 cc::SurfaceHittest hittest(GetSurfaceManager());
212 return hittest.Hittest(surface_id_, point, transformed_point);
215 bool DelegatedFrameHost::ShouldSkipFrame(gfx::Size size_in_dip) const {
216 // Should skip a frame only when another frame from the renderer is guaranteed
217 // to replace it. Otherwise may cause hangs when the renderer is waiting for
218 // the completion of latency infos (such as when taking a Snapshot.)
219 if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
220 can_lock_compositor_ == NO_PENDING_COMMIT ||
221 !resize_lock_.get())
222 return false;
224 return size_in_dip != resize_lock_->expected_size();
227 void DelegatedFrameHost::WasResized() {
228 if (client_->DelegatedFrameHostDesiredSizeInDIP() !=
229 current_frame_size_in_dip_ &&
230 !client_->DelegatedFrameHostIsVisible())
231 EvictDelegatedFrame();
232 MaybeCreateResizeLock();
235 gfx::Size DelegatedFrameHost::GetRequestedRendererSize() const {
236 if (resize_lock_)
237 return resize_lock_->expected_size();
238 else
239 return client_->DelegatedFrameHostDesiredSizeInDIP();
242 void DelegatedFrameHost::CheckResizeLock() {
243 if (!resize_lock_ ||
244 resize_lock_->expected_size() != current_frame_size_in_dip_)
245 return;
247 // Since we got the size we were looking for, unlock the compositor. But delay
248 // the release of the lock until we've kicked a frame with the new texture, to
249 // avoid resizing the UI before we have a chance to draw a "good" frame.
250 resize_lock_->UnlockCompositor();
253 void DelegatedFrameHost::DidReceiveFrameFromRenderer(
254 const gfx::Rect& damage_rect) {
255 if (!frame_subscriber() || !CanCopyToVideoFrame())
256 return;
258 const base::TimeTicks now = tick_clock_->NowTicks();
259 base::TimeTicks present_time;
260 if (vsync_interval_ <= base::TimeDelta()) {
261 present_time = now;
262 } else {
263 const int64 intervals_elapsed = (now - vsync_timebase_) / vsync_interval_;
264 present_time = vsync_timebase_ + (intervals_elapsed + 1) * vsync_interval_;
267 scoped_refptr<media::VideoFrame> frame;
268 RenderWidgetHostViewFrameSubscriber::DeliverFrameCallback callback;
269 if (!frame_subscriber()->ShouldCaptureFrame(damage_rect, present_time,
270 &frame, &callback))
271 return;
273 // Get a texture to re-use; else, create a new one.
274 scoped_refptr<OwnedMailbox> subscriber_texture;
275 if (!idle_frame_subscriber_textures_.empty()) {
276 subscriber_texture = idle_frame_subscriber_textures_.back();
277 idle_frame_subscriber_textures_.pop_back();
278 } else if (GLHelper* helper =
279 ImageTransportFactory::GetInstance()->GetGLHelper()) {
280 subscriber_texture = new OwnedMailbox(helper);
283 scoped_ptr<cc::CopyOutputRequest> request =
284 cc::CopyOutputRequest::CreateRequest(base::Bind(
285 &DelegatedFrameHost::CopyFromCompositingSurfaceHasResultForVideo,
286 AsWeakPtr(),
287 subscriber_texture,
288 frame,
289 base::Bind(callback, present_time)));
290 // Setting the source in this copy request asks that the layer abort any prior
291 // uncommitted copy requests made on behalf of the same frame subscriber.
292 // This will not affect any of the copy requests spawned elsewhere from
293 // DelegatedFrameHost (e.g., a call to CopyFromCompositingSurface() for
294 // screenshots) since those copy requests do not specify |frame_subscriber()|
295 // as a source.
296 request->set_source(frame_subscriber());
297 request->set_area(gfx::Rect(current_frame_size_in_dip_));
298 if (subscriber_texture.get()) {
299 request->SetTextureMailbox(
300 cc::TextureMailbox(subscriber_texture->mailbox(),
301 subscriber_texture->target(),
302 subscriber_texture->sync_point()));
304 RequestCopyOfOutput(request.Pass());
307 void DelegatedFrameHost::SwapDelegatedFrame(
308 uint32 output_surface_id,
309 scoped_ptr<cc::DelegatedFrameData> frame_data,
310 float frame_device_scale_factor,
311 const std::vector<ui::LatencyInfo>& latency_info,
312 std::vector<uint32_t>* satisfies_sequences) {
313 DCHECK(!frame_data->render_pass_list.empty());
315 cc::RenderPass* root_pass = frame_data->render_pass_list.back();
317 gfx::Size frame_size = root_pass->output_rect.size();
318 gfx::Size frame_size_in_dip =
319 gfx::ConvertSizeToDIP(frame_device_scale_factor, frame_size);
321 gfx::Rect damage_rect = gfx::ToEnclosingRect(root_pass->damage_rect);
322 damage_rect.Intersect(gfx::Rect(frame_size));
323 gfx::Rect damage_rect_in_dip =
324 gfx::ConvertRectToDIP(frame_device_scale_factor, damage_rect);
326 if (ShouldSkipFrame(frame_size_in_dip)) {
327 cc::CompositorFrameAck ack;
328 cc::TransferableResource::ReturnResources(frame_data->resource_list,
329 &ack.resources);
331 skipped_latency_info_list_.insert(skipped_latency_info_list_.end(),
332 latency_info.begin(), latency_info.end());
334 client_->DelegatedFrameHostSendCompositorSwapAck(output_surface_id, ack);
335 skipped_frames_ = true;
336 return;
339 if (skipped_frames_) {
340 skipped_frames_ = false;
341 damage_rect = gfx::Rect(frame_size);
342 damage_rect_in_dip = gfx::Rect(frame_size_in_dip);
344 // Give the same damage rect to the compositor.
345 cc::RenderPass* root_pass = frame_data->render_pass_list.back();
346 root_pass->damage_rect = damage_rect;
349 if (output_surface_id != last_output_surface_id_) {
350 // Resource ids are scoped by the output surface.
351 // If the originating output surface doesn't match the last one, it
352 // indicates the renderer's output surface may have been recreated, in which
353 // case we should recreate the DelegatedRendererLayer, to avoid matching
354 // resources from the old one with resources from the new one which would
355 // have the same id. Changing the layer to showing painted content destroys
356 // the DelegatedRendererLayer.
357 EvictDelegatedFrame();
359 surface_factory_.reset();
360 if (!surface_returned_resources_.empty())
361 SendReturnedDelegatedResources(last_output_surface_id_);
363 // Drop the cc::DelegatedFrameResourceCollection so that we will not return
364 // any resources from the old output surface with the new output surface id.
365 if (resource_collection_.get()) {
366 resource_collection_->SetClient(NULL);
368 if (resource_collection_->LoseAllResources())
369 SendReturnedDelegatedResources(last_output_surface_id_);
371 resource_collection_ = NULL;
373 last_output_surface_id_ = output_surface_id;
375 bool immediate_ack = !compositor_;
376 pending_delegated_ack_count_++;
378 if (frame_size.IsEmpty()) {
379 DCHECK(frame_data->resource_list.empty());
380 EvictDelegatedFrame();
381 } else {
382 if (use_surfaces_) {
383 ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
384 cc::SurfaceManager* manager = factory->GetSurfaceManager();
385 if (!surface_factory_) {
386 surface_factory_ =
387 make_scoped_ptr(new cc::SurfaceFactory(manager, this));
389 if (surface_id_.is_null() || frame_size != current_surface_size_ ||
390 frame_size_in_dip != current_frame_size_in_dip_) {
391 if (!surface_id_.is_null())
392 surface_factory_->Destroy(surface_id_);
393 surface_id_ = id_allocator_->GenerateId();
394 surface_factory_->Create(surface_id_);
395 // manager must outlive compositors using it.
396 client_->DelegatedFrameHostGetLayer()->SetShowSurface(
397 surface_id_,
398 base::Bind(&SatisfyCallback, base::Unretained(manager)),
399 base::Bind(&RequireCallback, base::Unretained(manager)), frame_size,
400 frame_device_scale_factor, frame_size_in_dip);
401 current_surface_size_ = frame_size;
402 current_scale_factor_ = frame_device_scale_factor;
404 scoped_ptr<cc::CompositorFrame> compositor_frame =
405 make_scoped_ptr(new cc::CompositorFrame());
406 compositor_frame->delegated_frame_data = frame_data.Pass();
408 compositor_frame->metadata.latency_info.swap(skipped_latency_info_list_);
409 compositor_frame->metadata.latency_info.insert(
410 compositor_frame->metadata.latency_info.end(),
411 latency_info.begin(),
412 latency_info.end());
413 compositor_frame->metadata.satisfies_sequences.swap(*satisfies_sequences);
415 gfx::Size desired_size = client_->DelegatedFrameHostDesiredSizeInDIP();
416 if (desired_size != frame_size_in_dip && !desired_size.IsEmpty())
417 immediate_ack = true;
419 cc::SurfaceFactory::DrawCallback ack_callback;
420 if (compositor_ && !immediate_ack) {
421 ack_callback = base::Bind(&DelegatedFrameHost::SurfaceDrawn,
422 AsWeakPtr(), output_surface_id);
424 surface_factory_->SubmitFrame(
425 surface_id_, compositor_frame.Pass(), ack_callback);
426 } else {
427 if (!resource_collection_.get()) {
428 resource_collection_ = new cc::DelegatedFrameResourceCollection;
429 resource_collection_->SetClient(this);
431 // If the physical frame size changes, we need a new |frame_provider_|. If
432 // the physical frame size is the same, but the size in DIP changed, we
433 // need to adjust the scale at which the frames will be drawn, and we do
434 // this by making a new |frame_provider_| also to ensure the scale change
435 // is presented in sync with the new frame content.
436 if (!frame_provider_.get() ||
437 frame_size != frame_provider_->frame_size() ||
438 frame_size_in_dip != current_frame_size_in_dip_) {
439 frame_provider_ = new cc::DelegatedFrameProvider(
440 resource_collection_.get(), frame_data.Pass());
441 client_->DelegatedFrameHostGetLayer()->SetShowDelegatedContent(
442 frame_provider_.get(), frame_size_in_dip);
443 } else {
444 frame_provider_->SetFrameData(frame_data.Pass());
448 released_front_lock_ = NULL;
449 current_frame_size_in_dip_ = frame_size_in_dip;
450 CheckResizeLock();
452 if (!damage_rect_in_dip.IsEmpty())
453 client_->DelegatedFrameHostGetLayer()->OnDelegatedFrameDamage(
454 damage_rect_in_dip);
456 if (immediate_ack) {
457 SendDelegatedFrameAck(output_surface_id);
458 } else if (!use_surfaces_) {
459 std::vector<ui::LatencyInfo>::const_iterator it;
460 for (it = latency_info.begin(); it != latency_info.end(); ++it)
461 compositor_->SetLatencyInfo(*it);
462 // If we've previously skipped any latency infos add them.
463 for (it = skipped_latency_info_list_.begin();
464 it != skipped_latency_info_list_.end();
465 ++it)
466 compositor_->SetLatencyInfo(*it);
467 skipped_latency_info_list_.clear();
468 AddOnCommitCallbackAndDisableLocks(
469 base::Bind(&DelegatedFrameHost::SendDelegatedFrameAck,
470 AsWeakPtr(), output_surface_id));
471 } else {
472 AddOnCommitCallbackAndDisableLocks(base::Closure());
474 DidReceiveFrameFromRenderer(damage_rect);
475 if (frame_provider_.get() || !surface_id_.is_null())
476 delegated_frame_evictor_->SwappedFrame(
477 client_->DelegatedFrameHostIsVisible());
478 // Note: the frame may have been evicted immediately.
481 void DelegatedFrameHost::SendDelegatedFrameAck(uint32 output_surface_id) {
482 cc::CompositorFrameAck ack;
483 if (!surface_returned_resources_.empty())
484 ack.resources.swap(surface_returned_resources_);
485 if (resource_collection_.get())
486 resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
487 client_->DelegatedFrameHostSendCompositorSwapAck(output_surface_id, ack);
488 DCHECK_GT(pending_delegated_ack_count_, 0);
489 pending_delegated_ack_count_--;
492 void DelegatedFrameHost::SurfaceDrawn(uint32 output_surface_id,
493 cc::SurfaceDrawStatus drawn) {
494 SendDelegatedFrameAck(output_surface_id);
497 void DelegatedFrameHost::UnusedResourcesAreAvailable() {
498 if (pending_delegated_ack_count_)
499 return;
501 SendReturnedDelegatedResources(last_output_surface_id_);
504 void DelegatedFrameHost::SendReturnedDelegatedResources(
505 uint32 output_surface_id) {
506 cc::CompositorFrameAck ack;
507 if (!surface_returned_resources_.empty()) {
508 ack.resources.swap(surface_returned_resources_);
509 } else {
510 DCHECK(resource_collection_.get());
511 resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
513 DCHECK(!ack.resources.empty());
515 client_->DelegatedFrameHostSendReclaimCompositorResources(output_surface_id,
516 ack);
519 void DelegatedFrameHost::ReturnResources(
520 const cc::ReturnedResourceArray& resources) {
521 if (resources.empty())
522 return;
523 std::copy(resources.begin(),
524 resources.end(),
525 std::back_inserter(surface_returned_resources_));
526 if (!pending_delegated_ack_count_)
527 SendReturnedDelegatedResources(last_output_surface_id_);
530 void DelegatedFrameHost::EvictDelegatedFrame() {
531 client_->DelegatedFrameHostGetLayer()->SetShowSolidColorContent();
532 frame_provider_ = NULL;
533 if (!surface_id_.is_null()) {
534 surface_factory_->Destroy(surface_id_);
535 surface_id_ = cc::SurfaceId();
537 delegated_frame_evictor_->DiscardedFrame();
540 // static
541 void DelegatedFrameHost::CopyFromCompositingSurfaceHasResult(
542 const gfx::Size& dst_size_in_pixel,
543 const SkColorType color_type,
544 ReadbackRequestCallback& callback,
545 scoped_ptr<cc::CopyOutputResult> result) {
546 if (result->IsEmpty() || result->size().IsEmpty()) {
547 callback.Run(SkBitmap(), content::READBACK_FAILED);
548 return;
551 gfx::Size output_size_in_pixel;
552 if (dst_size_in_pixel.IsEmpty())
553 output_size_in_pixel = result->size();
554 else
555 output_size_in_pixel = dst_size_in_pixel;
557 if (result->HasTexture()) {
558 // GPU-accelerated path
559 PrepareTextureCopyOutputResult(output_size_in_pixel, color_type,
560 callback,
561 result.Pass());
562 return;
565 DCHECK(result->HasBitmap());
566 // Software path
567 PrepareBitmapCopyOutputResult(output_size_in_pixel, color_type, callback,
568 result.Pass());
571 static void CopyFromCompositingSurfaceFinished(
572 ReadbackRequestCallback& callback,
573 scoped_ptr<cc::SingleReleaseCallback> release_callback,
574 scoped_ptr<SkBitmap> bitmap,
575 scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock,
576 bool result) {
577 bitmap_pixels_lock.reset();
579 uint32 sync_point = 0;
580 if (result) {
581 GLHelper* gl_helper = ImageTransportFactory::GetInstance()->GetGLHelper();
582 if (gl_helper)
583 sync_point = gl_helper->InsertSyncPoint();
585 bool lost_resource = sync_point == 0;
586 release_callback->Run(sync_point, lost_resource);
588 callback.Run(*bitmap,
589 result ? content::READBACK_SUCCESS : content::READBACK_FAILED);
592 // static
593 void DelegatedFrameHost::PrepareTextureCopyOutputResult(
594 const gfx::Size& dst_size_in_pixel,
595 const SkColorType color_type,
596 ReadbackRequestCallback& callback,
597 scoped_ptr<cc::CopyOutputResult> result) {
598 DCHECK(result->HasTexture());
599 base::ScopedClosureRunner scoped_callback_runner(
600 base::Bind(callback, SkBitmap(), content::READBACK_FAILED));
602 // TODO(siva.gunturi): We should be able to validate the format here using
603 // GLHelper::IsReadbackConfigSupported before we processs the result.
604 // See crbug.com/415682 and crbug.com/415131.
605 scoped_ptr<SkBitmap> bitmap(new SkBitmap);
606 if (!bitmap->tryAllocPixels(SkImageInfo::Make(
607 dst_size_in_pixel.width(), dst_size_in_pixel.height(), color_type,
608 kOpaque_SkAlphaType))) {
609 scoped_callback_runner.Reset(base::Bind(
610 callback, SkBitmap(), content::READBACK_BITMAP_ALLOCATION_FAILURE));
611 return;
614 ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
615 GLHelper* gl_helper = factory->GetGLHelper();
616 if (!gl_helper)
617 return;
619 scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock(
620 new SkAutoLockPixels(*bitmap));
621 uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
623 cc::TextureMailbox texture_mailbox;
624 scoped_ptr<cc::SingleReleaseCallback> release_callback;
625 result->TakeTexture(&texture_mailbox, &release_callback);
626 DCHECK(texture_mailbox.IsTexture());
628 ignore_result(scoped_callback_runner.Release());
630 gl_helper->CropScaleReadbackAndCleanMailbox(
631 texture_mailbox.mailbox(),
632 texture_mailbox.sync_point(),
633 result->size(),
634 gfx::Rect(result->size()),
635 dst_size_in_pixel,
636 pixels,
637 color_type,
638 base::Bind(&CopyFromCompositingSurfaceFinished,
639 callback,
640 base::Passed(&release_callback),
641 base::Passed(&bitmap),
642 base::Passed(&bitmap_pixels_lock)),
643 GLHelper::SCALER_QUALITY_GOOD);
646 // static
647 void DelegatedFrameHost::PrepareBitmapCopyOutputResult(
648 const gfx::Size& dst_size_in_pixel,
649 const SkColorType preferred_color_type,
650 ReadbackRequestCallback& callback,
651 scoped_ptr<cc::CopyOutputResult> result) {
652 SkColorType color_type = preferred_color_type;
653 if (color_type != kN32_SkColorType && color_type != kAlpha_8_SkColorType) {
654 // Switch back to default colortype if format not supported.
655 color_type = kN32_SkColorType;
657 DCHECK(result->HasBitmap());
658 scoped_ptr<SkBitmap> source = result->TakeBitmap();
659 DCHECK(source);
660 SkBitmap scaled_bitmap;
661 if (source->width() != dst_size_in_pixel.width() ||
662 source->height() != dst_size_in_pixel.height()) {
663 scaled_bitmap =
664 skia::ImageOperations::Resize(*source,
665 skia::ImageOperations::RESIZE_BEST,
666 dst_size_in_pixel.width(),
667 dst_size_in_pixel.height());
668 } else {
669 scaled_bitmap = *source;
671 if (color_type == kN32_SkColorType) {
672 DCHECK_EQ(scaled_bitmap.colorType(), kN32_SkColorType);
673 callback.Run(scaled_bitmap, READBACK_SUCCESS);
674 return;
676 DCHECK_EQ(color_type, kAlpha_8_SkColorType);
677 // The software path currently always returns N32 bitmap regardless of the
678 // |color_type| we ask for.
679 DCHECK_EQ(scaled_bitmap.colorType(), kN32_SkColorType);
680 // Paint |scaledBitmap| to alpha-only |grayscale_bitmap|.
681 SkBitmap grayscale_bitmap;
682 bool success = grayscale_bitmap.tryAllocPixels(
683 SkImageInfo::MakeA8(scaled_bitmap.width(), scaled_bitmap.height()));
684 if (!success) {
685 callback.Run(SkBitmap(), content::READBACK_BITMAP_ALLOCATION_FAILURE);
686 return;
688 SkCanvas canvas(grayscale_bitmap);
689 SkPaint paint;
690 skia::RefPtr<SkColorFilter> filter =
691 skia::AdoptRef(SkLumaColorFilter::Create());
692 paint.setColorFilter(filter.get());
693 canvas.drawBitmap(scaled_bitmap, SkIntToScalar(0), SkIntToScalar(0), &paint);
694 callback.Run(grayscale_bitmap, READBACK_SUCCESS);
697 // static
698 void DelegatedFrameHost::ReturnSubscriberTexture(
699 base::WeakPtr<DelegatedFrameHost> dfh,
700 scoped_refptr<OwnedMailbox> subscriber_texture,
701 uint32 sync_point) {
702 if (!subscriber_texture.get())
703 return;
704 if (!dfh)
705 return;
707 subscriber_texture->UpdateSyncPoint(sync_point);
709 if (dfh->frame_subscriber_ && subscriber_texture->texture_id())
710 dfh->idle_frame_subscriber_textures_.push_back(subscriber_texture);
713 // static
714 void DelegatedFrameHost::CopyFromCompositingSurfaceFinishedForVideo(
715 base::WeakPtr<DelegatedFrameHost> dfh,
716 const base::Callback<void(bool)>& callback,
717 scoped_refptr<OwnedMailbox> subscriber_texture,
718 scoped_ptr<cc::SingleReleaseCallback> release_callback,
719 bool result) {
720 callback.Run(result);
722 uint32 sync_point = 0;
723 if (result) {
724 GLHelper* gl_helper = ImageTransportFactory::GetInstance()->GetGLHelper();
725 sync_point = gl_helper->InsertSyncPoint();
727 if (release_callback) {
728 // A release callback means the texture came from the compositor, so there
729 // should be no |subscriber_texture|.
730 DCHECK(!subscriber_texture.get());
731 bool lost_resource = sync_point == 0;
732 release_callback->Run(sync_point, lost_resource);
734 ReturnSubscriberTexture(dfh, subscriber_texture, sync_point);
737 // static
738 void DelegatedFrameHost::CopyFromCompositingSurfaceHasResultForVideo(
739 base::WeakPtr<DelegatedFrameHost> dfh,
740 scoped_refptr<OwnedMailbox> subscriber_texture,
741 scoped_refptr<media::VideoFrame> video_frame,
742 const base::Callback<void(bool)>& callback,
743 scoped_ptr<cc::CopyOutputResult> result) {
744 base::ScopedClosureRunner scoped_callback_runner(base::Bind(callback, false));
745 base::ScopedClosureRunner scoped_return_subscriber_texture(
746 base::Bind(&ReturnSubscriberTexture, dfh, subscriber_texture, 0));
748 if (!dfh)
749 return;
750 if (result->IsEmpty())
751 return;
752 if (result->size().IsEmpty())
753 return;
755 // Compute the dest size we want after the letterboxing resize. Make the
756 // coordinates and sizes even because we letterbox in YUV space
757 // (see CopyRGBToVideoFrame). They need to be even for the UV samples to
758 // line up correctly.
759 // The video frame's visible_rect() and the result's size() are both physical
760 // pixels.
761 gfx::Rect region_in_frame = media::ComputeLetterboxRegion(
762 video_frame->visible_rect(), result->size());
763 region_in_frame = gfx::Rect(region_in_frame.x() & ~1,
764 region_in_frame.y() & ~1,
765 region_in_frame.width() & ~1,
766 region_in_frame.height() & ~1);
767 if (region_in_frame.IsEmpty())
768 return;
770 if (!result->HasTexture()) {
771 DCHECK(result->HasBitmap());
772 scoped_ptr<SkBitmap> bitmap = result->TakeBitmap();
773 // Scale the bitmap to the required size, if necessary.
774 SkBitmap scaled_bitmap;
775 if (result->size() != region_in_frame.size()) {
776 skia::ImageOperations::ResizeMethod method =
777 skia::ImageOperations::RESIZE_GOOD;
778 scaled_bitmap = skia::ImageOperations::Resize(*bitmap.get(), method,
779 region_in_frame.width(),
780 region_in_frame.height());
781 } else {
782 scaled_bitmap = *bitmap.get();
786 SkAutoLockPixels scaled_bitmap_locker(scaled_bitmap);
788 media::CopyRGBToVideoFrame(
789 reinterpret_cast<uint8*>(scaled_bitmap.getPixels()),
790 scaled_bitmap.rowBytes(),
791 region_in_frame,
792 video_frame.get());
794 ignore_result(scoped_callback_runner.Release());
795 callback.Run(true);
796 return;
799 ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
800 GLHelper* gl_helper = factory->GetGLHelper();
801 if (!gl_helper)
802 return;
803 if (subscriber_texture.get() && !subscriber_texture->texture_id())
804 return;
806 cc::TextureMailbox texture_mailbox;
807 scoped_ptr<cc::SingleReleaseCallback> release_callback;
808 result->TakeTexture(&texture_mailbox, &release_callback);
809 DCHECK(texture_mailbox.IsTexture());
811 gfx::Rect result_rect(result->size());
813 content::ReadbackYUVInterface* yuv_readback_pipeline =
814 dfh->yuv_readback_pipeline_.get();
815 if (yuv_readback_pipeline == NULL ||
816 yuv_readback_pipeline->scaler()->SrcSize() != result_rect.size() ||
817 yuv_readback_pipeline->scaler()->SrcSubrect() != result_rect ||
818 yuv_readback_pipeline->scaler()->DstSize() != region_in_frame.size()) {
819 GLHelper::ScalerQuality quality = GLHelper::SCALER_QUALITY_FAST;
820 std::string quality_switch = switches::kTabCaptureDownscaleQuality;
821 // If we're scaling up, we can use the "best" quality.
822 if (result_rect.size().width() < region_in_frame.size().width() &&
823 result_rect.size().height() < region_in_frame.size().height())
824 quality_switch = switches::kTabCaptureUpscaleQuality;
826 std::string switch_value =
827 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
828 quality_switch);
829 if (switch_value == "fast")
830 quality = GLHelper::SCALER_QUALITY_FAST;
831 else if (switch_value == "good")
832 quality = GLHelper::SCALER_QUALITY_GOOD;
833 else if (switch_value == "best")
834 quality = GLHelper::SCALER_QUALITY_BEST;
836 dfh->yuv_readback_pipeline_.reset(
837 gl_helper->CreateReadbackPipelineYUV(quality,
838 result_rect.size(),
839 result_rect,
840 region_in_frame.size(),
841 true,
842 true));
843 yuv_readback_pipeline = dfh->yuv_readback_pipeline_.get();
846 ignore_result(scoped_callback_runner.Release());
847 ignore_result(scoped_return_subscriber_texture.Release());
848 base::Callback<void(bool result)> finished_callback = base::Bind(
849 &DelegatedFrameHost::CopyFromCompositingSurfaceFinishedForVideo,
850 dfh->AsWeakPtr(),
851 callback,
852 subscriber_texture,
853 base::Passed(&release_callback));
854 yuv_readback_pipeline->ReadbackYUV(texture_mailbox.mailbox(),
855 texture_mailbox.sync_point(),
856 video_frame.get(),
857 region_in_frame.origin(),
858 finished_callback);
861 ////////////////////////////////////////////////////////////////////////////////
862 // DelegatedFrameHost, ui::CompositorObserver implementation:
864 void DelegatedFrameHost::OnCompositingDidCommit(
865 ui::Compositor* compositor) {
866 if (can_lock_compositor_ == NO_PENDING_COMMIT) {
867 can_lock_compositor_ = YES_CAN_LOCK;
868 if (resize_lock_.get() && resize_lock_->GrabDeferredLock())
869 can_lock_compositor_ = YES_DID_LOCK;
871 RunOnCommitCallbacks();
872 if (resize_lock_ &&
873 resize_lock_->expected_size() == current_frame_size_in_dip_) {
874 resize_lock_.reset();
875 client_->DelegatedFrameHostResizeLockWasReleased();
876 // We may have had a resize while we had the lock (e.g. if the lock expired,
877 // or if the UI still gave us some resizes), so make sure we grab a new lock
878 // if necessary.
879 MaybeCreateResizeLock();
883 void DelegatedFrameHost::OnCompositingStarted(
884 ui::Compositor* compositor, base::TimeTicks start_time) {
885 last_draw_ended_ = start_time;
888 void DelegatedFrameHost::OnCompositingEnded(
889 ui::Compositor* compositor) {
892 void DelegatedFrameHost::OnCompositingAborted(ui::Compositor* compositor) {
895 void DelegatedFrameHost::OnCompositingLockStateChanged(
896 ui::Compositor* compositor) {
897 // A compositor lock that is part of a resize lock timed out. We
898 // should display a renderer frame.
899 if (!compositor->IsLocked() && can_lock_compositor_ == YES_DID_LOCK) {
900 can_lock_compositor_ = NO_PENDING_RENDERER_FRAME;
904 void DelegatedFrameHost::OnCompositingShuttingDown(ui::Compositor* compositor) {
905 DCHECK_EQ(compositor, compositor_);
906 ResetCompositor();
907 DCHECK(!compositor_);
910 void DelegatedFrameHost::OnUpdateVSyncParameters(
911 base::TimeTicks timebase,
912 base::TimeDelta interval) {
913 SetVSyncParameters(timebase, interval);
914 if (client_->DelegatedFrameHostIsVisible())
915 client_->DelegatedFrameHostUpdateVSyncParameters(timebase, interval);
918 ////////////////////////////////////////////////////////////////////////////////
919 // DelegatedFrameHost, ImageTransportFactoryObserver implementation:
921 void DelegatedFrameHost::OnLostResources() {
922 if (frame_provider_.get() || !surface_id_.is_null())
923 EvictDelegatedFrame();
924 idle_frame_subscriber_textures_.clear();
925 yuv_readback_pipeline_.reset();
927 client_->DelegatedFrameHostOnLostCompositorResources();
930 ////////////////////////////////////////////////////////////////////////////////
931 // DelegatedFrameHost, private:
933 DelegatedFrameHost::~DelegatedFrameHost() {
934 DCHECK(!compositor_);
935 ImageTransportFactory::GetInstance()->RemoveObserver(this);
937 if (!surface_id_.is_null())
938 surface_factory_->Destroy(surface_id_);
939 if (resource_collection_.get())
940 resource_collection_->SetClient(NULL);
942 DCHECK(!vsync_manager_.get());
945 void DelegatedFrameHost::RunOnCommitCallbacks() {
946 for (std::vector<base::Closure>::const_iterator
947 it = on_compositing_did_commit_callbacks_.begin();
948 it != on_compositing_did_commit_callbacks_.end(); ++it) {
949 it->Run();
951 on_compositing_did_commit_callbacks_.clear();
954 void DelegatedFrameHost::AddOnCommitCallbackAndDisableLocks(
955 const base::Closure& callback) {
956 DCHECK(compositor_);
958 can_lock_compositor_ = NO_PENDING_COMMIT;
959 if (!callback.is_null())
960 on_compositing_did_commit_callbacks_.push_back(callback);
963 void DelegatedFrameHost::SetCompositor(ui::Compositor* compositor) {
964 DCHECK(!compositor_);
965 if (!compositor)
966 return;
967 compositor_ = compositor;
968 compositor_->AddObserver(this);
969 DCHECK(!vsync_manager_.get());
970 vsync_manager_ = compositor_->vsync_manager();
971 vsync_manager_->AddObserver(this);
974 void DelegatedFrameHost::ResetCompositor() {
975 if (!compositor_)
976 return;
977 RunOnCommitCallbacks();
978 if (resize_lock_) {
979 resize_lock_.reset();
980 client_->DelegatedFrameHostResizeLockWasReleased();
982 if (compositor_->HasObserver(this))
983 compositor_->RemoveObserver(this);
984 if (vsync_manager_.get()) {
985 vsync_manager_->RemoveObserver(this);
986 vsync_manager_ = NULL;
988 compositor_ = nullptr;
991 void DelegatedFrameHost::SetVSyncParameters(const base::TimeTicks& timebase,
992 const base::TimeDelta& interval) {
993 vsync_timebase_ = timebase;
994 vsync_interval_ = interval;
997 void DelegatedFrameHost::LockResources() {
998 DCHECK(frame_provider_.get() || !surface_id_.is_null());
999 delegated_frame_evictor_->LockFrame();
1002 void DelegatedFrameHost::RequestCopyOfOutput(
1003 scoped_ptr<cc::CopyOutputRequest> request) {
1004 if (!request_copy_of_output_callback_for_testing_.is_null())
1005 request_copy_of_output_callback_for_testing_.Run(request.Pass());
1006 else
1007 client_->DelegatedFrameHostGetLayer()->RequestCopyOfOutput(request.Pass());
1010 void DelegatedFrameHost::UnlockResources() {
1011 DCHECK(frame_provider_.get() || !surface_id_.is_null());
1012 delegated_frame_evictor_->UnlockFrame();
1015 ////////////////////////////////////////////////////////////////////////////////
1016 // DelegatedFrameHost, ui::LayerOwnerDelegate implementation:
1018 void DelegatedFrameHost::OnLayerRecreated(ui::Layer* old_layer,
1019 ui::Layer* new_layer) {
1020 // The new_layer is the one that will be used by our Window, so that's the one
1021 // that should keep our frame. old_layer will be returned to the
1022 // RecreateLayer caller, and should have a copy.
1023 if (frame_provider_.get()) {
1024 new_layer->SetShowDelegatedContent(frame_provider_.get(),
1025 current_frame_size_in_dip_);
1027 if (!surface_id_.is_null()) {
1028 ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
1029 cc::SurfaceManager* manager = factory->GetSurfaceManager();
1030 new_layer->SetShowSurface(
1031 surface_id_, base::Bind(&SatisfyCallback, base::Unretained(manager)),
1032 base::Bind(&RequireCallback, base::Unretained(manager)),
1033 current_surface_size_, current_scale_factor_,
1034 current_frame_size_in_dip_);
1038 } // namespace content