Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / renderer_host / compositor_impl_android.cc
blob2a5b357d57388a93b1a68b2829326e018a3d63e1
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
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/compositor_impl_android.h"
7 #include <android/bitmap.h>
8 #include <android/native_window_jni.h>
10 #include "base/android/jni_android.h"
11 #include "base/android/scoped_java_ref.h"
12 #include "base/bind.h"
13 #include "base/cancelable_callback.h"
14 #include "base/command_line.h"
15 #include "base/containers/hash_tables.h"
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/single_thread_task_runner.h"
20 #include "base/synchronization/lock.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/threading/simple_thread.h"
23 #include "base/threading/thread.h"
24 #include "base/threading/thread_checker.h"
25 #include "cc/base/switches.h"
26 #include "cc/input/input_handler.h"
27 #include "cc/layers/layer.h"
28 #include "cc/output/compositor_frame.h"
29 #include "cc/output/context_provider.h"
30 #include "cc/output/output_surface.h"
31 #include "cc/output/output_surface_client.h"
32 #include "cc/raster/task_graph_runner.h"
33 #include "cc/scheduler/begin_frame_source.h"
34 #include "cc/surfaces/onscreen_display_client.h"
35 #include "cc/surfaces/surface_display_output_surface.h"
36 #include "cc/surfaces/surface_id_allocator.h"
37 #include "cc/surfaces/surface_manager.h"
38 #include "cc/trees/layer_tree_host.h"
39 #include "cc/trees/layer_tree_settings.h"
40 #include "content/browser/android/child_process_launcher_android.h"
41 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
42 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
43 #include "content/browser/gpu/compositor_util.h"
44 #include "content/browser/gpu/gpu_surface_tracker.h"
45 #include "content/browser/renderer_host/render_widget_host_impl.h"
46 #include "content/common/gpu/client/command_buffer_proxy_impl.h"
47 #include "content/common/gpu/client/context_provider_command_buffer.h"
48 #include "content/common/gpu/client/gl_helper.h"
49 #include "content/common/gpu/client/gpu_channel_host.h"
50 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
51 #include "content/common/gpu/gpu_process_launch_causes.h"
52 #include "content/common/host_shared_bitmap_manager.h"
53 #include "content/public/browser/android/compositor.h"
54 #include "content/public/browser/android/compositor_client.h"
55 #include "content/public/common/content_switches.h"
56 #include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h"
57 #include "gpu/command_buffer/client/context_support.h"
58 #include "gpu/command_buffer/client/gles2_interface.h"
59 #include "third_party/khronos/GLES2/gl2.h"
60 #include "third_party/khronos/GLES2/gl2ext.h"
61 #include "third_party/skia/include/core/SkMallocPixelRef.h"
62 #include "ui/android/window_android.h"
63 #include "ui/gfx/android/device_display_info.h"
64 #include "ui/gfx/swap_result.h"
66 namespace content {
68 namespace {
70 const unsigned int kMaxSwapBuffers = 2U;
72 // Used to override capabilities_.adjust_deadline_for_parent to false
73 class OutputSurfaceWithoutParent : public cc::OutputSurface,
74 public CompositorImpl::VSyncObserver {
75 public:
76 OutputSurfaceWithoutParent(
77 CompositorImpl* compositor,
78 const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
79 const base::Callback<void(gpu::Capabilities)>&
80 populate_gpu_capabilities_callback)
81 : cc::OutputSurface(context_provider),
82 compositor_(compositor),
83 populate_gpu_capabilities_callback_(populate_gpu_capabilities_callback),
84 swap_buffers_completion_callback_(
85 base::Bind(&OutputSurfaceWithoutParent::OnSwapBuffersCompleted,
86 base::Unretained(this))) {
87 capabilities_.adjust_deadline_for_parent = false;
88 capabilities_.max_frames_pending = 2;
91 ~OutputSurfaceWithoutParent() override { compositor_->RemoveObserver(this); }
93 void SwapBuffers(cc::CompositorFrame* frame) override {
94 GetCommandBufferProxy()->SetLatencyInfo(frame->metadata.latency_info);
95 DCHECK(frame->gl_frame_data->sub_buffer_rect ==
96 gfx::Rect(frame->gl_frame_data->size));
97 context_provider_->ContextSupport()->Swap();
98 client_->DidSwapBuffers();
101 bool BindToClient(cc::OutputSurfaceClient* client) override {
102 if (!OutputSurface::BindToClient(client))
103 return false;
105 GetCommandBufferProxy()->SetSwapBuffersCompletionCallback(
106 swap_buffers_completion_callback_.callback());
108 populate_gpu_capabilities_callback_.Run(
109 context_provider_->ContextCapabilities().gpu);
110 compositor_->AddObserver(this);
112 return true;
115 private:
116 CommandBufferProxyImpl* GetCommandBufferProxy() {
117 ContextProviderCommandBuffer* provider_command_buffer =
118 static_cast<content::ContextProviderCommandBuffer*>(
119 context_provider_.get());
120 CommandBufferProxyImpl* command_buffer_proxy =
121 provider_command_buffer->GetCommandBufferProxy();
122 DCHECK(command_buffer_proxy);
123 return command_buffer_proxy;
126 void OnSwapBuffersCompleted(const std::vector<ui::LatencyInfo>& latency_info,
127 gfx::SwapResult result) {
128 RenderWidgetHostImpl::CompositorFrameDrawn(latency_info);
129 OutputSurface::OnSwapBuffersComplete();
132 void OnUpdateVSyncParameters(base::TimeTicks timebase,
133 base::TimeDelta interval) override {
134 CommitVSyncParameters(timebase, interval);
137 CompositorImpl* compositor_;
138 base::Callback<void(gpu::Capabilities)> populate_gpu_capabilities_callback_;
139 base::CancelableCallback<void(const std::vector<ui::LatencyInfo>&,
140 gfx::SwapResult)>
141 swap_buffers_completion_callback_;
144 static bool g_initialized = false;
146 bool g_use_surface_manager = false;
147 base::LazyInstance<cc::SurfaceManager> g_surface_manager =
148 LAZY_INSTANCE_INITIALIZER;
151 int g_surface_id_namespace = 0;
153 class SingleThreadTaskGraphRunner
154 : public cc::TaskGraphRunner,
155 public base::DelegateSimpleThread::Delegate {
156 public:
157 SingleThreadTaskGraphRunner()
158 : worker_thread_(
159 this,
160 "CompositorTileWorker1",
161 base::SimpleThread::Options(base::ThreadPriority::BACKGROUND)) {
162 worker_thread_.Start();
165 ~SingleThreadTaskGraphRunner() override {
166 Shutdown();
167 worker_thread_.Join();
170 private:
171 // Overridden from base::DelegateSimpleThread::Delegate:
172 void Run() override { cc::TaskGraphRunner::Run(); }
174 base::DelegateSimpleThread worker_thread_;
177 base::LazyInstance<SingleThreadTaskGraphRunner> g_task_graph_runner =
178 LAZY_INSTANCE_INITIALIZER;
180 base::LazyInstance<cc::LayerSettings> g_layer_settings =
181 LAZY_INSTANCE_INITIALIZER;
183 } // anonymous namespace
185 // static
186 Compositor* Compositor::Create(CompositorClient* client,
187 gfx::NativeWindow root_window) {
188 return client ? new CompositorImpl(client, root_window) : NULL;
191 // static
192 void Compositor::Initialize() {
193 DCHECK(!CompositorImpl::IsInitialized());
194 g_initialized = true;
195 g_use_surface_manager = UseSurfacesEnabled();
198 // static
199 const cc::LayerSettings& Compositor::LayerSettings() {
200 return g_layer_settings.Get();
203 // static
204 void Compositor::SetLayerSettings(const cc::LayerSettings& settings) {
205 g_layer_settings.Get() = settings;
208 // static
209 bool CompositorImpl::IsInitialized() {
210 return g_initialized;
213 // static
214 cc::SurfaceManager* CompositorImpl::GetSurfaceManager() {
215 if (!g_use_surface_manager)
216 return nullptr;
217 return g_surface_manager.Pointer();
220 // static
221 scoped_ptr<cc::SurfaceIdAllocator> CompositorImpl::CreateSurfaceIdAllocator() {
222 scoped_ptr<cc::SurfaceIdAllocator> allocator(
223 new cc::SurfaceIdAllocator(++g_surface_id_namespace));
224 cc::SurfaceManager* manager = GetSurfaceManager();
225 DCHECK(manager);
226 allocator->RegisterSurfaceIdNamespace(manager);
227 return allocator.Pass();
230 CompositorImpl::CompositorImpl(CompositorClient* client,
231 gfx::NativeWindow root_window)
232 : root_layer_(cc::Layer::Create(Compositor::LayerSettings())),
233 resource_manager_(&ui_resource_provider_),
234 surface_id_allocator_(GetSurfaceManager() ? CreateSurfaceIdAllocator()
235 : nullptr),
236 has_transparent_background_(false),
237 device_scale_factor_(1),
238 window_(NULL),
239 surface_id_(0),
240 client_(client),
241 root_window_(root_window),
242 did_post_swapbuffers_(false),
243 ignore_schedule_composite_(false),
244 needs_composite_(false),
245 needs_animate_(false),
246 will_composite_immediately_(false),
247 composite_on_vsync_trigger_(DO_NOT_COMPOSITE),
248 pending_swapbuffers_(0U),
249 num_successive_context_creation_failures_(0),
250 output_surface_request_pending_(false),
251 weak_factory_(this) {
252 DCHECK(client);
253 DCHECK(root_window);
254 root_window->AttachCompositor(this);
257 CompositorImpl::~CompositorImpl() {
258 root_window_->DetachCompositor();
259 // Clean-up any surface references.
260 SetSurface(NULL);
263 void CompositorImpl::PostComposite(CompositingTrigger trigger) {
264 DCHECK(needs_composite_);
265 DCHECK(trigger == COMPOSITE_IMMEDIATELY || trigger == COMPOSITE_EVENTUALLY);
267 if (will_composite_immediately_ ||
268 (trigger == COMPOSITE_EVENTUALLY && WillComposite())) {
269 // We will already composite soon enough.
270 DCHECK(WillComposite());
271 return;
274 if (DidCompositeThisFrame()) {
275 DCHECK(!WillCompositeThisFrame());
276 if (composite_on_vsync_trigger_ != COMPOSITE_IMMEDIATELY) {
277 composite_on_vsync_trigger_ = trigger;
278 root_window_->RequestVSyncUpdate();
280 DCHECK(WillComposite());
281 return;
284 base::TimeDelta delay;
285 if (trigger == COMPOSITE_IMMEDIATELY) {
286 will_composite_immediately_ = true;
287 composite_on_vsync_trigger_ = DO_NOT_COMPOSITE;
288 } else {
289 DCHECK(!WillComposite());
290 const base::TimeDelta estimated_composite_time = vsync_period_ / 4;
291 const base::TimeTicks now = base::TimeTicks::Now();
293 if (!last_vsync_.is_null() && (now - last_vsync_) < vsync_period_) {
294 base::TimeTicks next_composite =
295 last_vsync_ + vsync_period_ - estimated_composite_time;
296 if (next_composite < now) {
297 // It's too late, we will reschedule composite as needed on the next
298 // vsync.
299 composite_on_vsync_trigger_ = COMPOSITE_EVENTUALLY;
300 root_window_->RequestVSyncUpdate();
301 DCHECK(WillComposite());
302 return;
305 delay = next_composite - now;
308 TRACE_EVENT2("cc,benchmark", "CompositorImpl::PostComposite",
309 "trigger", trigger,
310 "delay", delay.InMillisecondsF());
312 DCHECK(composite_on_vsync_trigger_ == DO_NOT_COMPOSITE);
313 if (current_composite_task_)
314 current_composite_task_->Cancel();
316 // Unretained because we cancel the task on shutdown.
317 current_composite_task_.reset(new base::CancelableClosure(
318 base::Bind(&CompositorImpl::Composite, base::Unretained(this), trigger)));
319 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
320 FROM_HERE, current_composite_task_->callback(), delay);
323 void CompositorImpl::Composite(CompositingTrigger trigger) {
324 if (trigger == COMPOSITE_IMMEDIATELY)
325 will_composite_immediately_ = false;
327 DCHECK(host_);
328 DCHECK(trigger == COMPOSITE_IMMEDIATELY || trigger == COMPOSITE_EVENTUALLY);
329 DCHECK(needs_composite_);
330 DCHECK(!DidCompositeThisFrame());
332 DCHECK_LE(pending_swapbuffers_, kMaxSwapBuffers);
333 // Swap Ack accounting is unreliable if the OutputSurface was lost.
334 // In that case still attempt to composite, which will cause creation of a
335 // new OutputSurface and reset pending_swapbuffers_.
336 if (pending_swapbuffers_ == kMaxSwapBuffers &&
337 !host_->output_surface_lost()) {
338 TRACE_EVENT0("compositor", "CompositorImpl_SwapLimit");
339 return;
342 // Reset state before Layout+Composite since that might create more
343 // requests to Composite that we need to respect.
344 needs_composite_ = false;
346 // Only allow compositing once per vsync.
347 current_composite_task_->Cancel();
348 DCHECK(DidCompositeThisFrame() && !WillComposite());
350 // Ignore ScheduleComposite() from layer tree changes during layout and
351 // animation updates that will already be reflected in the current frame
352 // we are about to draw.
353 ignore_schedule_composite_ = true;
355 const base::TimeTicks frame_time = base::TimeTicks::Now();
356 if (needs_animate_) {
357 needs_animate_ = false;
358 root_window_->Animate(frame_time);
360 ignore_schedule_composite_ = false;
362 did_post_swapbuffers_ = false;
363 host_->Composite(frame_time);
364 if (did_post_swapbuffers_)
365 pending_swapbuffers_++;
367 // Need to track vsync to avoid compositing more than once per frame.
368 root_window_->RequestVSyncUpdate();
371 ui::UIResourceProvider& CompositorImpl::GetUIResourceProvider() {
372 return ui_resource_provider_;
375 ui::ResourceManager& CompositorImpl::GetResourceManager() {
376 return resource_manager_;
379 void CompositorImpl::SetRootLayer(scoped_refptr<cc::Layer> root_layer) {
380 if (subroot_layer_.get()) {
381 subroot_layer_->RemoveFromParent();
382 subroot_layer_ = NULL;
384 if (root_layer.get()) {
385 subroot_layer_ = root_layer;
386 root_layer_->AddChild(root_layer);
390 void CompositorImpl::SetWindowSurface(ANativeWindow* window) {
391 GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get();
393 if (window_) {
394 tracker->RemoveSurface(surface_id_);
395 ANativeWindow_release(window_);
396 window_ = NULL;
397 surface_id_ = 0;
398 SetVisible(false);
401 if (window) {
402 window_ = window;
403 ANativeWindow_acquire(window);
404 surface_id_ = tracker->AddSurfaceForNativeWidget(window);
405 tracker->SetSurfaceHandle(
406 surface_id_,
407 gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NATIVE_DIRECT));
408 SetVisible(true);
412 void CompositorImpl::SetSurface(jobject surface) {
413 JNIEnv* env = base::android::AttachCurrentThread();
414 base::android::ScopedJavaLocalRef<jobject> j_surface(env, surface);
416 // First, cleanup any existing surface references.
417 if (surface_id_)
418 UnregisterViewSurface(surface_id_);
419 SetWindowSurface(NULL);
421 // Now, set the new surface if we have one.
422 ANativeWindow* window = NULL;
423 if (surface) {
424 // Note: This ensures that any local references used by
425 // ANativeWindow_fromSurface are released immediately. This is needed as a
426 // workaround for https://code.google.com/p/android/issues/detail?id=68174
427 base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env);
428 window = ANativeWindow_fromSurface(env, surface);
430 if (window) {
431 SetWindowSurface(window);
432 ANativeWindow_release(window);
433 RegisterViewSurface(surface_id_, j_surface.obj());
437 void CompositorImpl::CreateLayerTreeHost() {
438 DCHECK(!host_);
439 DCHECK(!WillCompositeThisFrame());
440 needs_composite_ = false;
441 pending_swapbuffers_ = 0;
442 cc::LayerTreeSettings settings;
443 settings.renderer_settings.refresh_rate = 60.0;
444 settings.renderer_settings.allow_antialiasing = false;
445 settings.renderer_settings.highp_threshold_min = 2048;
446 settings.use_zero_copy = true;
447 settings.use_one_copy = false;
448 settings.use_display_lists = true;
450 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
451 settings.initial_debug_state.SetRecordRenderingStats(
452 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
453 settings.initial_debug_state.show_fps_counter =
454 command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
455 // TODO(enne): Update this this compositor to use the scheduler.
456 settings.single_thread_proxy_scheduler = false;
458 if (command_line->HasSwitch(
459 switches::kEnableAndroidCompositorAnimationTimelines))
460 settings.use_compositor_animation_timelines = true;
462 cc::LayerTreeHost::InitParams params;
463 params.client = this;
464 params.shared_bitmap_manager = HostSharedBitmapManager::current();
465 params.gpu_memory_buffer_manager = BrowserGpuMemoryBufferManager::current();
466 params.task_graph_runner = g_task_graph_runner.Pointer();
467 params.main_task_runner = base::ThreadTaskRunnerHandle::Get();
468 params.settings = &settings;
469 host_ = cc::LayerTreeHost::CreateSingleThreaded(this, &params);
470 host_->SetRootLayer(root_layer_);
472 host_->SetVisible(true);
473 host_->SetLayerTreeHostClientReady();
474 host_->SetViewportSize(size_);
475 host_->set_has_transparent_background(has_transparent_background_);
476 host_->SetDeviceScaleFactor(device_scale_factor_);
478 if (needs_animate_)
479 host_->SetNeedsAnimate();
482 void CompositorImpl::SetVisible(bool visible) {
483 TRACE_EVENT1("cc", "CompositorImpl::SetVisible", "visible", visible);
484 if (!visible) {
485 DCHECK(host_);
486 // Look for any layers that were attached to the root for readback
487 // and are waiting for Composite() to happen.
488 bool readback_pending = false;
489 for (size_t i = 0; i < root_layer_->children().size(); ++i) {
490 if (root_layer_->children()[i]->HasCopyRequest()) {
491 readback_pending = true;
492 break;
495 if (readback_pending) {
496 ignore_schedule_composite_ = true;
497 host_->Composite(base::TimeTicks::Now());
498 ignore_schedule_composite_ = false;
500 if (WillComposite())
501 CancelComposite();
502 ui_resource_provider_.SetLayerTreeHost(NULL);
503 host_.reset();
504 establish_gpu_channel_timeout_.Stop();
505 output_surface_request_pending_ = false;
506 display_client_.reset();
507 if (current_composite_task_) {
508 current_composite_task_->Cancel();
509 current_composite_task_.reset();
511 } else if (!host_) {
512 CreateLayerTreeHost();
513 ui_resource_provider_.SetLayerTreeHost(host_.get());
517 void CompositorImpl::setDeviceScaleFactor(float factor) {
518 device_scale_factor_ = factor;
519 if (host_)
520 host_->SetDeviceScaleFactor(factor);
523 void CompositorImpl::SetWindowBounds(const gfx::Size& size) {
524 if (size_ == size)
525 return;
527 size_ = size;
528 if (host_)
529 host_->SetViewportSize(size);
530 if (display_client_)
531 display_client_->display()->Resize(size);
532 root_layer_->SetBounds(size);
535 void CompositorImpl::SetHasTransparentBackground(bool flag) {
536 has_transparent_background_ = flag;
537 if (host_)
538 host_->set_has_transparent_background(flag);
541 void CompositorImpl::SetNeedsComposite() {
542 if (!host_.get())
543 return;
544 DCHECK(!needs_composite_ || WillComposite());
546 needs_composite_ = true;
547 PostComposite(COMPOSITE_IMMEDIATELY);
550 static scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
551 CreateGpuProcessViewContext(
552 const scoped_refptr<GpuChannelHost>& gpu_channel_host,
553 const blink::WebGraphicsContext3D::Attributes attributes,
554 int surface_id) {
555 GURL url("chrome://gpu/Compositor::createContext3D");
556 static const size_t kBytesPerPixel = 4;
557 gfx::DeviceDisplayInfo display_info;
558 size_t full_screen_texture_size_in_bytes =
559 display_info.GetDisplayHeight() *
560 display_info.GetDisplayWidth() *
561 kBytesPerPixel;
562 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
563 limits.command_buffer_size = 64 * 1024;
564 limits.start_transfer_buffer_size = 64 * 1024;
565 limits.min_transfer_buffer_size = 64 * 1024;
566 limits.max_transfer_buffer_size = std::min(
567 3 * full_screen_texture_size_in_bytes, kDefaultMaxTransferBufferSize);
568 limits.mapped_memory_reclaim_limit = 2 * 1024 * 1024;
569 bool lose_context_when_out_of_memory = true;
570 return make_scoped_ptr(
571 new WebGraphicsContext3DCommandBufferImpl(surface_id,
572 url,
573 gpu_channel_host.get(),
574 attributes,
575 lose_context_when_out_of_memory,
576 limits,
577 NULL));
580 void CompositorImpl::Layout() {
581 ignore_schedule_composite_ = true;
582 client_->Layout();
583 ignore_schedule_composite_ = false;
586 void CompositorImpl::OnGpuChannelEstablished() {
587 establish_gpu_channel_timeout_.Stop();
588 CreateOutputSurface();
591 void CompositorImpl::OnGpuChannelTimeout() {
592 LOG(FATAL) << "Timed out waiting for GPU channel.";
595 void CompositorImpl::RequestNewOutputSurface() {
596 output_surface_request_pending_ = true;
598 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || defined(SYZYASAN)
599 const int64 kGpuChannelTimeoutInSeconds = 30;
600 #else
601 const int64 kGpuChannelTimeoutInSeconds = 10;
602 #endif
604 BrowserGpuChannelHostFactory* factory =
605 BrowserGpuChannelHostFactory::instance();
606 if (!factory->GetGpuChannel() || factory->GetGpuChannel()->IsLost()) {
607 factory->EstablishGpuChannel(
608 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE,
609 base::Bind(&CompositorImpl::OnGpuChannelEstablished,
610 weak_factory_.GetWeakPtr()));
611 establish_gpu_channel_timeout_.Start(
612 FROM_HERE, base::TimeDelta::FromSeconds(kGpuChannelTimeoutInSeconds),
613 this, &CompositorImpl::OnGpuChannelTimeout);
614 return;
617 CreateOutputSurface();
620 void CompositorImpl::DidInitializeOutputSurface() {
621 num_successive_context_creation_failures_ = 0;
622 output_surface_request_pending_ = false;
625 void CompositorImpl::DidFailToInitializeOutputSurface() {
626 LOG(ERROR) << "Failed to init OutputSurface for compositor.";
627 LOG_IF(FATAL, ++num_successive_context_creation_failures_ >= 2)
628 << "Too many context creation failures. Giving up... ";
629 RequestNewOutputSurface();
632 void CompositorImpl::CreateOutputSurface() {
633 // We might have had a request from a LayerTreeHost that was then
634 // deleted.
635 if (!output_surface_request_pending_)
636 return;
638 blink::WebGraphicsContext3D::Attributes attrs;
639 attrs.shareResources = true;
640 attrs.noAutomaticFlushes = true;
641 pending_swapbuffers_ = 0;
643 DCHECK(window_);
644 DCHECK(surface_id_);
646 BrowserGpuChannelHostFactory* factory =
647 BrowserGpuChannelHostFactory::instance();
648 // This channel might be lost (and even if it isn't right now, it might
649 // still get marked as lost from the IO thread, at any point in time really).
650 // But from here on just try and always lead to either
651 // DidInitializeOutputSurface() or DidFailToInitializeOutputSurface().
652 scoped_refptr<GpuChannelHost> gpu_channel_host(factory->GetGpuChannel());
653 scoped_refptr<ContextProviderCommandBuffer> context_provider(
654 ContextProviderCommandBuffer::Create(
655 CreateGpuProcessViewContext(gpu_channel_host, attrs, surface_id_),
656 BROWSER_COMPOSITOR_ONSCREEN_CONTEXT));
657 DCHECK(context_provider.get());
659 scoped_ptr<cc::OutputSurface> real_output_surface(
660 new OutputSurfaceWithoutParent(
661 this, context_provider,
662 base::Bind(&CompositorImpl::PopulateGpuCapabilities,
663 base::Unretained(this))));
665 cc::SurfaceManager* manager = GetSurfaceManager();
666 if (manager) {
667 display_client_.reset(new cc::OnscreenDisplayClient(
668 real_output_surface.Pass(), manager, HostSharedBitmapManager::current(),
669 BrowserGpuMemoryBufferManager::current(),
670 host_->settings().renderer_settings,
671 base::ThreadTaskRunnerHandle::Get()));
672 scoped_ptr<cc::SurfaceDisplayOutputSurface> surface_output_surface(
673 new cc::SurfaceDisplayOutputSurface(
674 manager, surface_id_allocator_.get(), context_provider));
676 display_client_->set_surface_output_surface(surface_output_surface.get());
677 surface_output_surface->set_display_client(display_client_.get());
678 display_client_->display()->Resize(size_);
679 host_->SetOutputSurface(surface_output_surface.Pass());
680 } else {
681 host_->SetOutputSurface(real_output_surface.Pass());
685 void CompositorImpl::PopulateGpuCapabilities(
686 gpu::Capabilities gpu_capabilities) {
687 ui_resource_provider_.SetSupportsETC1NonPowerOfTwo(
688 gpu_capabilities.texture_format_etc1_npot);
691 void CompositorImpl::AddObserver(VSyncObserver* observer) {
692 observer_list_.AddObserver(observer);
695 void CompositorImpl::RemoveObserver(VSyncObserver* observer) {
696 observer_list_.RemoveObserver(observer);
699 void CompositorImpl::ScheduleComposite() {
700 DCHECK(!needs_composite_ || WillComposite());
701 if (ignore_schedule_composite_)
702 return;
704 needs_composite_ = true;
705 // We currently expect layer tree invalidations at most once per frame
706 // during normal operation and therefore try to composite immediately
707 // to minimize latency.
708 PostComposite(COMPOSITE_IMMEDIATELY);
711 void CompositorImpl::ScheduleAnimation() {
712 DCHECK(!needs_composite_ || WillComposite());
713 needs_animate_ = true;
715 if (needs_composite_)
716 return;
718 TRACE_EVENT0("cc", "CompositorImpl::ScheduleAnimation");
719 needs_composite_ = true;
720 PostComposite(COMPOSITE_EVENTUALLY);
723 void CompositorImpl::DidPostSwapBuffers() {
724 TRACE_EVENT0("compositor", "CompositorImpl::DidPostSwapBuffers");
725 did_post_swapbuffers_ = true;
728 void CompositorImpl::DidCompleteSwapBuffers() {
729 TRACE_EVENT0("compositor", "CompositorImpl::DidCompleteSwapBuffers");
730 DCHECK_GT(pending_swapbuffers_, 0U);
731 if (pending_swapbuffers_-- == kMaxSwapBuffers && needs_composite_)
732 PostComposite(COMPOSITE_IMMEDIATELY);
733 client_->OnSwapBuffersCompleted(pending_swapbuffers_);
736 void CompositorImpl::DidAbortSwapBuffers() {
737 TRACE_EVENT0("compositor", "CompositorImpl::DidAbortSwapBuffers");
738 // This really gets called only once from
739 // SingleThreadProxy::DidLoseOutputSurfaceOnImplThread() when the
740 // context was lost.
741 ScheduleComposite();
742 client_->OnSwapBuffersCompleted(0);
745 void CompositorImpl::DidCommit() {
746 root_window_->OnCompositingDidCommit();
749 void CompositorImpl::AttachLayerForReadback(scoped_refptr<cc::Layer> layer) {
750 root_layer_->AddChild(layer);
753 void CompositorImpl::RequestCopyOfOutputOnRootLayer(
754 scoped_ptr<cc::CopyOutputRequest> request) {
755 root_layer_->RequestCopyOfOutput(request.Pass());
758 void CompositorImpl::OnVSync(base::TimeTicks frame_time,
759 base::TimeDelta vsync_period) {
760 vsync_period_ = vsync_period;
761 last_vsync_ = frame_time;
763 if (WillCompositeThisFrame()) {
764 // We somehow missed the last vsync interval, so reschedule for deadline.
765 // We cannot schedule immediately, or will get us out-of-phase with new
766 // renderer frames.
767 CancelComposite();
768 composite_on_vsync_trigger_ = COMPOSITE_EVENTUALLY;
769 } else {
770 current_composite_task_.reset();
773 DCHECK(!DidCompositeThisFrame() && !WillCompositeThisFrame());
774 if (composite_on_vsync_trigger_ != DO_NOT_COMPOSITE) {
775 CompositingTrigger trigger = composite_on_vsync_trigger_;
776 composite_on_vsync_trigger_ = DO_NOT_COMPOSITE;
777 PostComposite(trigger);
780 FOR_EACH_OBSERVER(VSyncObserver, observer_list_,
781 OnUpdateVSyncParameters(frame_time, vsync_period));
784 void CompositorImpl::SetNeedsAnimate() {
785 needs_animate_ = true;
786 if (!host_)
787 return;
789 host_->SetNeedsAnimate();
792 } // namespace content