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 "ui/compositor/compositor.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "base/strings/string_util.h"
15 #include "base/sys_info.h"
16 #include "base/trace_event/trace_event.h"
17 #include "cc/base/switches.h"
18 #include "cc/input/input_handler.h"
19 #include "cc/layers/layer.h"
20 #include "cc/output/begin_frame_args.h"
21 #include "cc/output/context_provider.h"
22 #include "cc/output/latency_info_swap_promise.h"
23 #include "cc/scheduler/begin_frame_source.h"
24 #include "cc/surfaces/surface_id_allocator.h"
25 #include "cc/trees/layer_tree_host.h"
26 #include "third_party/skia/include/core/SkBitmap.h"
27 #include "ui/compositor/compositor_observer.h"
28 #include "ui/compositor/compositor_switches.h"
29 #include "ui/compositor/compositor_vsync_manager.h"
30 #include "ui/compositor/dip_util.h"
31 #include "ui/compositor/layer.h"
32 #include "ui/compositor/layer_animator_collection.h"
33 #include "ui/gl/gl_context.h"
34 #include "ui/gl/gl_switches.h"
38 const double kDefaultRefreshRate
= 60.0;
39 const double kTestRefreshRate
= 200.0;
45 CompositorLock::CompositorLock(Compositor
* compositor
)
46 : compositor_(compositor
) {
47 if (compositor_
->locks_will_time_out_
) {
48 compositor_
->task_runner_
->PostDelayedTask(
50 base::Bind(&CompositorLock::CancelLock
, AsWeakPtr()),
51 base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs
));
55 CompositorLock::~CompositorLock() {
59 void CompositorLock::CancelLock() {
62 compositor_
->UnlockCompositor();
66 Compositor::Compositor(gfx::AcceleratedWidget widget
,
67 ui::ContextFactory
* context_factory
,
68 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
)
69 : context_factory_(context_factory
),
72 surface_id_allocator_(context_factory
->CreateSurfaceIdAllocator()),
73 task_runner_(task_runner
),
74 vsync_manager_(new CompositorVSyncManager()),
75 device_scale_factor_(0.0f
),
76 last_started_frame_(0),
78 locks_will_time_out_(true),
79 compositor_lock_(NULL
),
80 layer_animator_collection_(this),
81 weak_ptr_factory_(this) {
82 root_web_layer_
= cc::Layer::Create(Layer::UILayerSettings());
84 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
86 cc::LayerTreeSettings settings
;
88 // When impl-side painting is enabled, this will ensure PictureLayers always
89 // can have LCD text, to match the previous behaviour with ContentLayers,
90 // where LCD-not-allowed notifications were ignored.
91 settings
.layers_always_allowed_lcd_text
= true;
92 settings
.renderer_settings
.refresh_rate
=
93 context_factory_
->DoesCreateTestContexts() ? kTestRefreshRate
94 : kDefaultRefreshRate
;
95 settings
.main_frame_before_activation_enabled
= false;
96 if (command_line
->HasSwitch(switches::kDisableGpuVsync
)) {
97 std::string display_vsync_string
=
98 command_line
->GetSwitchValueASCII(switches::kDisableGpuVsync
);
99 if (display_vsync_string
== "gpu") {
100 settings
.renderer_settings
.disable_display_vsync
= true;
101 } else if (display_vsync_string
== "beginframe") {
102 settings
.wait_for_beginframe_interval
= false;
104 settings
.renderer_settings
.disable_display_vsync
= true;
105 settings
.wait_for_beginframe_interval
= false;
108 settings
.renderer_settings
.partial_swap_enabled
=
109 !command_line
->HasSwitch(cc::switches::kUIDisablePartialSwap
);
111 settings
.renderer_settings
.finish_rendering_on_resize
= true;
114 // These flags should be mirrored by renderer versions in content/renderer/.
115 settings
.initial_debug_state
.show_debug_borders
=
116 command_line
->HasSwitch(cc::switches::kUIShowCompositedLayerBorders
);
117 settings
.initial_debug_state
.show_fps_counter
=
118 command_line
->HasSwitch(cc::switches::kUIShowFPSCounter
);
119 settings
.initial_debug_state
.show_layer_animation_bounds_rects
=
120 command_line
->HasSwitch(cc::switches::kUIShowLayerAnimationBounds
);
121 settings
.initial_debug_state
.show_paint_rects
=
122 command_line
->HasSwitch(switches::kUIShowPaintRects
);
123 settings
.initial_debug_state
.show_property_changed_rects
=
124 command_line
->HasSwitch(cc::switches::kUIShowPropertyChangedRects
);
125 settings
.initial_debug_state
.show_surface_damage_rects
=
126 command_line
->HasSwitch(cc::switches::kUIShowSurfaceDamageRects
);
127 settings
.initial_debug_state
.show_screen_space_rects
=
128 command_line
->HasSwitch(cc::switches::kUIShowScreenSpaceRects
);
129 settings
.initial_debug_state
.show_replica_screen_space_rects
=
130 command_line
->HasSwitch(cc::switches::kUIShowReplicaScreenSpaceRects
);
132 settings
.initial_debug_state
.SetRecordRenderingStats(
133 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
));
135 settings
.use_display_lists
= true;
137 settings
.use_zero_copy
= IsUIZeroCopyEnabled();
138 settings
.use_one_copy
= IsUIOneCopyEnabled();
140 // TODO(reveman): We currently assume that the compositor will use BGRA_8888
141 // if it's able to, and RGBA_8888 otherwise. Since we don't know what it will
142 // use we hardcode BGRA_8888 here for now. We should instead
143 // move decisions about GpuMemoryBuffer format to the browser embedder so we
144 // know it here, and pass that decision to the compositor for each usage.
146 gfx::GpuMemoryBuffer::Format format
= gfx::GpuMemoryBuffer::BGRA_8888
;
148 // Use PERSISTENT_MAP memory buffers to support partial tile raster for
149 // software raster into GpuMemoryBuffers.
150 gfx::GpuMemoryBuffer::Usage usage
= gfx::GpuMemoryBuffer::PERSISTENT_MAP
;
151 settings
.use_persistent_map_for_gpu_memory_buffers
= true;
153 settings
.use_image_texture_target
=
154 context_factory_
->GetImageTextureTarget(format
, usage
);
156 // Note: gathering of pixel refs is only needed when using multiple
158 settings
.gather_pixel_refs
= false;
160 settings
.use_compositor_animation_timelines
=
161 command_line
->HasSwitch(switches::kUIEnableCompositorAnimationTimelines
);
163 base::TimeTicks before_create
= base::TimeTicks::Now();
165 cc::LayerTreeHost::InitParams params
;
166 params
.client
= this;
167 params
.shared_bitmap_manager
= context_factory_
->GetSharedBitmapManager();
168 params
.gpu_memory_buffer_manager
=
169 context_factory_
->GetGpuMemoryBufferManager();
170 params
.task_graph_runner
= context_factory_
->GetTaskGraphRunner();
171 params
.settings
= &settings
;
172 params
.main_task_runner
= task_runner_
;
173 host_
= cc::LayerTreeHost::CreateSingleThreaded(this, ¶ms
);
174 UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor",
175 base::TimeTicks::Now() - before_create
);
176 host_
->SetRootLayer(root_web_layer_
);
177 host_
->set_surface_id_namespace(surface_id_allocator_
->id_namespace());
178 host_
->SetLayerTreeHostClientReady();
181 Compositor::~Compositor() {
182 TRACE_EVENT0("shutdown", "Compositor::destructor");
184 CancelCompositorLock();
185 DCHECK(!compositor_lock_
);
187 FOR_EACH_OBSERVER(CompositorObserver
, observer_list_
,
188 OnCompositingShuttingDown(this));
190 FOR_EACH_OBSERVER(CompositorAnimationObserver
, animation_observer_list_
,
191 OnCompositingShuttingDown(this));
193 DCHECK(begin_frame_observer_list_
.empty());
196 root_layer_
->ResetCompositor();
198 // Stop all outstanding draws before telling the ContextFactory to tear
199 // down any contexts that the |host_| may rely upon.
202 context_factory_
->RemoveCompositor(this);
205 void Compositor::SetOutputSurface(
206 scoped_ptr
<cc::OutputSurface
> output_surface
) {
207 host_
->SetOutputSurface(output_surface
.Pass());
210 void Compositor::ScheduleDraw() {
211 host_
->SetNeedsCommit();
214 void Compositor::SetRootLayer(Layer
* root_layer
) {
215 if (root_layer_
== root_layer
)
218 root_layer_
->ResetCompositor();
219 root_layer_
= root_layer
;
220 root_web_layer_
->RemoveAllChildren();
222 root_layer_
->SetCompositor(this, root_web_layer_
);
225 void Compositor::SetHostHasTransparentBackground(
226 bool host_has_transparent_background
) {
227 host_
->set_has_transparent_background(host_has_transparent_background
);
230 void Compositor::ScheduleFullRedraw() {
231 // TODO(enne): Some callers (mac) call this function expecting that it
232 // will also commit. This should probably just redraw the screen
233 // from damage and not commit. ScheduleDraw/ScheduleRedraw need
235 host_
->SetNeedsRedraw();
236 host_
->SetNeedsCommit();
239 void Compositor::ScheduleRedrawRect(const gfx::Rect
& damage_rect
) {
240 // TODO(enne): Make this not commit. See ScheduleFullRedraw.
241 host_
->SetNeedsRedrawRect(damage_rect
);
242 host_
->SetNeedsCommit();
245 void Compositor::FinishAllRendering() {
246 host_
->FinishAllRendering();
249 void Compositor::DisableSwapUntilResize() {
250 host_
->FinishAllRendering();
251 context_factory_
->ResizeDisplay(this, gfx::Size());
254 void Compositor::SetLatencyInfo(const ui::LatencyInfo
& latency_info
) {
255 scoped_ptr
<cc::SwapPromise
> swap_promise(
256 new cc::LatencyInfoSwapPromise(latency_info
));
257 host_
->QueueSwapPromise(swap_promise
.Pass());
260 void Compositor::SetScaleAndSize(float scale
, const gfx::Size
& size_in_pixel
) {
262 if (!size_in_pixel
.IsEmpty()) {
263 size_
= size_in_pixel
;
264 host_
->SetViewportSize(size_in_pixel
);
265 root_web_layer_
->SetBounds(size_in_pixel
);
266 context_factory_
->ResizeDisplay(this, size_in_pixel
);
268 if (device_scale_factor_
!= scale
) {
269 device_scale_factor_
= scale
;
270 host_
->SetDeviceScaleFactor(scale
);
272 root_layer_
->OnDeviceScaleFactorChanged(scale
);
276 void Compositor::SetBackgroundColor(SkColor color
) {
277 host_
->set_background_color(color
);
281 void Compositor::SetVisible(bool visible
) {
282 host_
->SetVisible(visible
);
285 bool Compositor::IsVisible() {
286 return host_
->visible();
289 void Compositor::SetAuthoritativeVSyncInterval(
290 const base::TimeDelta
& interval
) {
291 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
292 cc::switches::kEnableBeginFrameScheduling
)) {
293 host_
->SetAuthoritativeVSyncInterval(interval
);
297 vsync_manager_
->SetAuthoritativeVSyncInterval(interval
);
300 scoped_refptr
<CompositorVSyncManager
> Compositor::vsync_manager() const {
301 return vsync_manager_
;
304 void Compositor::AddObserver(CompositorObserver
* observer
) {
305 observer_list_
.AddObserver(observer
);
308 void Compositor::RemoveObserver(CompositorObserver
* observer
) {
309 observer_list_
.RemoveObserver(observer
);
312 bool Compositor::HasObserver(const CompositorObserver
* observer
) const {
313 return observer_list_
.HasObserver(observer
);
316 void Compositor::AddAnimationObserver(CompositorAnimationObserver
* observer
) {
317 animation_observer_list_
.AddObserver(observer
);
318 host_
->SetNeedsAnimate();
321 void Compositor::RemoveAnimationObserver(
322 CompositorAnimationObserver
* observer
) {
323 animation_observer_list_
.RemoveObserver(observer
);
326 bool Compositor::HasAnimationObserver(
327 const CompositorAnimationObserver
* observer
) const {
328 return animation_observer_list_
.HasObserver(observer
);
331 void Compositor::AddBeginFrameObserver(CompositorBeginFrameObserver
* observer
) {
332 DCHECK(std::find(begin_frame_observer_list_
.begin(),
333 begin_frame_observer_list_
.end(), observer
) ==
334 begin_frame_observer_list_
.end());
336 if (begin_frame_observer_list_
.empty())
337 host_
->SetChildrenNeedBeginFrames(true);
339 if (missed_begin_frame_args_
.IsValid())
340 observer
->OnSendBeginFrame(missed_begin_frame_args_
);
342 begin_frame_observer_list_
.push_back(observer
);
345 void Compositor::RemoveBeginFrameObserver(
346 CompositorBeginFrameObserver
* observer
) {
347 auto it
= std::find(begin_frame_observer_list_
.begin(),
348 begin_frame_observer_list_
.end(), observer
);
349 DCHECK(it
!= begin_frame_observer_list_
.end());
350 begin_frame_observer_list_
.erase(it
);
352 if (begin_frame_observer_list_
.empty()) {
353 host_
->SetChildrenNeedBeginFrames(false);
354 missed_begin_frame_args_
= cc::BeginFrameArgs();
358 void Compositor::BeginMainFrame(const cc::BeginFrameArgs
& args
) {
359 FOR_EACH_OBSERVER(CompositorAnimationObserver
,
360 animation_observer_list_
,
361 OnAnimationStep(args
.frame_time
));
362 if (animation_observer_list_
.might_have_observers())
363 host_
->SetNeedsAnimate();
366 void Compositor::BeginMainFrameNotExpectedSoon() {
369 static void SendDamagedRectsRecursive(ui::Layer
* layer
) {
370 layer
->SendDamagedRects();
371 for (auto* child
: layer
->children())
372 SendDamagedRectsRecursive(child
);
375 void Compositor::Layout() {
378 SendDamagedRectsRecursive(root_layer());
381 void Compositor::RequestNewOutputSurface() {
382 context_factory_
->CreateOutputSurface(weak_ptr_factory_
.GetWeakPtr());
385 void Compositor::DidInitializeOutputSurface() {
388 void Compositor::DidFailToInitializeOutputSurface() {
389 // The OutputSurface should already be bound/initialized before being given to
394 void Compositor::DidCommit() {
396 FOR_EACH_OBSERVER(CompositorObserver
,
398 OnCompositingDidCommit(this));
401 void Compositor::DidCommitAndDrawFrame() {
404 void Compositor::DidCompleteSwapBuffers() {
405 FOR_EACH_OBSERVER(CompositorObserver
, observer_list_
,
406 OnCompositingEnded(this));
409 void Compositor::DidPostSwapBuffers() {
410 base::TimeTicks start_time
= base::TimeTicks::Now();
411 FOR_EACH_OBSERVER(CompositorObserver
, observer_list_
,
412 OnCompositingStarted(this, start_time
));
415 void Compositor::DidAbortSwapBuffers() {
416 FOR_EACH_OBSERVER(CompositorObserver
,
418 OnCompositingAborted(this));
421 void Compositor::SendBeginFramesToChildren(const cc::BeginFrameArgs
& args
) {
422 for (auto observer
: begin_frame_observer_list_
)
423 observer
->OnSendBeginFrame(args
);
425 missed_begin_frame_args_
= args
;
426 missed_begin_frame_args_
.type
= cc::BeginFrameArgs::MISSED
;
429 const cc::LayerTreeDebugState
& Compositor::GetLayerTreeDebugState() const {
430 return host_
->debug_state();
433 void Compositor::SetLayerTreeDebugState(
434 const cc::LayerTreeDebugState
& debug_state
) {
435 host_
->SetDebugState(debug_state
);
438 const cc::RendererSettings
& Compositor::GetRendererSettings() const {
439 return host_
->settings().renderer_settings
;
442 scoped_refptr
<CompositorLock
> Compositor::GetCompositorLock() {
443 if (!compositor_lock_
) {
444 compositor_lock_
= new CompositorLock(this);
445 host_
->SetDeferCommits(true);
446 FOR_EACH_OBSERVER(CompositorObserver
,
448 OnCompositingLockStateChanged(this));
450 return compositor_lock_
;
453 void Compositor::UnlockCompositor() {
454 DCHECK(compositor_lock_
);
455 compositor_lock_
= NULL
;
456 host_
->SetDeferCommits(false);
457 FOR_EACH_OBSERVER(CompositorObserver
,
459 OnCompositingLockStateChanged(this));
462 void Compositor::CancelCompositorLock() {
463 if (compositor_lock_
)
464 compositor_lock_
->CancelLock();