1 // Copyright 2011 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 "cc/scheduler/scheduler.h"
9 #include "base/auto_reset.h"
10 #include "base/debug/trace_event.h"
11 #include "base/debug/trace_event_argument.h"
12 #include "base/logging.h"
13 #include "base/single_thread_task_runner.h"
14 #include "cc/debug/devtools_instrumentation.h"
15 #include "cc/debug/traced_value.h"
16 #include "cc/scheduler/delay_based_time_source.h"
17 #include "ui/gfx/frame_time.h"
21 BeginFrameSource
* SchedulerFrameSourcesConstructor::ConstructPrimaryFrameSource(
22 Scheduler
* scheduler
) {
23 if (scheduler
->settings_
.use_external_begin_frame_source
) {
25 "Scheduler::Scheduler()",
27 "ExternalBeginFrameSource");
28 DCHECK(scheduler
->primary_frame_source_internal_
)
29 << "Need external BeginFrameSource";
30 return scheduler
->primary_frame_source_internal_
.get();
33 "Scheduler::Scheduler()",
35 "SyntheticBeginFrameSource");
36 scoped_ptr
<SyntheticBeginFrameSource
> synthetic_source
=
37 SyntheticBeginFrameSource::Create(scheduler
->task_runner_
.get(),
39 BeginFrameArgs::DefaultInterval());
41 DCHECK(!scheduler
->vsync_observer_
);
42 scheduler
->vsync_observer_
= synthetic_source
.get();
44 DCHECK(!scheduler
->primary_frame_source_internal_
);
45 scheduler
->primary_frame_source_internal_
= synthetic_source
.Pass();
46 return scheduler
->primary_frame_source_internal_
.get();
51 SchedulerFrameSourcesConstructor::ConstructBackgroundFrameSource(
52 Scheduler
* scheduler
) {
54 "Scheduler::Scheduler()",
55 "BackgroundFrameSource",
56 "SyntheticBeginFrameSource");
57 DCHECK(!(scheduler
->background_frame_source_internal_
));
58 scheduler
->background_frame_source_internal_
=
59 SyntheticBeginFrameSource::Create(
60 scheduler
->task_runner_
.get(), scheduler
->Now(),
61 scheduler
->settings_
.background_frame_interval
);
62 return scheduler
->background_frame_source_internal_
.get();
66 SchedulerFrameSourcesConstructor::ConstructUnthrottledFrameSource(
67 Scheduler
* scheduler
) {
68 TRACE_EVENT1("cc", "Scheduler::Scheduler()", "UnthrottledFrameSource",
69 "BackToBackBeginFrameSource");
70 DCHECK(!scheduler
->unthrottled_frame_source_internal_
);
71 scheduler
->unthrottled_frame_source_internal_
=
72 BackToBackBeginFrameSource::Create(scheduler
->task_runner_
.get());
73 return scheduler
->unthrottled_frame_source_internal_
.get();
77 SchedulerClient
* client
,
78 const SchedulerSettings
& scheduler_settings
,
79 int layer_tree_host_id
,
80 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
81 base::PowerMonitor
* power_monitor
,
82 scoped_ptr
<BeginFrameSource
> external_begin_frame_source
,
83 SchedulerFrameSourcesConstructor
* frame_sources_constructor
)
85 primary_frame_source_(NULL
),
86 background_frame_source_(NULL
),
87 primary_frame_source_internal_(external_begin_frame_source
.Pass()),
88 background_frame_source_internal_(),
89 vsync_observer_(NULL
),
90 throttle_frame_production_(scheduler_settings
.throttle_frame_production
),
91 settings_(scheduler_settings
),
93 layer_tree_host_id_(layer_tree_host_id
),
94 task_runner_(task_runner
),
95 power_monitor_(power_monitor
),
96 state_machine_(scheduler_settings
),
97 inside_process_scheduled_actions_(false),
98 inside_action_(SchedulerStateMachine::ACTION_NONE
),
100 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
101 "Scheduler::Scheduler",
103 settings_
.AsValue());
105 DCHECK(!state_machine_
.BeginFrameNeeded());
107 begin_retro_frame_closure_
=
108 base::Bind(&Scheduler::BeginRetroFrame
, weak_factory_
.GetWeakPtr());
109 begin_impl_frame_deadline_closure_
= base::Bind(
110 &Scheduler::OnBeginImplFrameDeadline
, weak_factory_
.GetWeakPtr());
111 poll_for_draw_triggers_closure_
= base::Bind(
112 &Scheduler::PollForAnticipatedDrawTriggers
, weak_factory_
.GetWeakPtr());
113 advance_commit_state_closure_
= base::Bind(
114 &Scheduler::PollToAdvanceCommitState
, weak_factory_
.GetWeakPtr());
116 frame_source_
= BeginFrameSourceMultiplexer::Create();
117 frame_source_
->AddObserver(this);
119 // Primary frame source
120 primary_frame_source_
=
121 frame_sources_constructor
->ConstructPrimaryFrameSource(this);
122 frame_source_
->AddSource(primary_frame_source_
);
123 primary_frame_source_
->SetClientReady();
125 // Background ticking frame source
126 background_frame_source_
=
127 frame_sources_constructor
->ConstructBackgroundFrameSource(this);
128 frame_source_
->AddSource(background_frame_source_
);
130 // Unthrottled frame source
131 unthrottled_frame_source_
=
132 frame_sources_constructor
->ConstructUnthrottledFrameSource(this);
133 frame_source_
->AddSource(unthrottled_frame_source_
);
135 SetupPowerMonitoring();
138 Scheduler::~Scheduler() {
139 TeardownPowerMonitoring();
140 if (frame_source_
->NeedsBeginFrames())
141 frame_source_
->SetNeedsBeginFrames(false);
144 base::TimeTicks
Scheduler::Now() const {
145 base::TimeTicks now
= gfx::FrameTime::Now();
146 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.now"),
153 void Scheduler::SetupPowerMonitoring() {
154 if (settings_
.disable_hi_res_timer_tasks_on_battery
) {
155 DCHECK(power_monitor_
);
156 power_monitor_
->AddObserver(this);
157 state_machine_
.SetImplLatencyTakesPriorityOnBattery(
158 power_monitor_
->IsOnBatteryPower());
162 void Scheduler::TeardownPowerMonitoring() {
163 if (settings_
.disable_hi_res_timer_tasks_on_battery
) {
164 DCHECK(power_monitor_
);
165 power_monitor_
->RemoveObserver(this);
169 void Scheduler::OnPowerStateChange(bool on_battery_power
) {
170 DCHECK(settings_
.disable_hi_res_timer_tasks_on_battery
);
171 state_machine_
.SetImplLatencyTakesPriorityOnBattery(on_battery_power
);
174 void Scheduler::CommitVSyncParameters(base::TimeTicks timebase
,
175 base::TimeDelta interval
) {
176 // TODO(brianderson): We should not be receiving 0 intervals.
177 if (interval
== base::TimeDelta())
178 interval
= BeginFrameArgs::DefaultInterval();
181 vsync_observer_
->OnUpdateVSyncParameters(timebase
, interval
);
184 void Scheduler::SetEstimatedParentDrawTime(base::TimeDelta draw_time
) {
185 DCHECK_GE(draw_time
.ToInternalValue(), 0);
186 estimated_parent_draw_time_
= draw_time
;
189 void Scheduler::SetCanStart() {
190 state_machine_
.SetCanStart();
191 ProcessScheduledActions();
194 void Scheduler::UpdateActiveFrameSource() {
195 if (state_machine_
.visible()) {
196 if (throttle_frame_production_
) {
197 frame_source_
->SetActiveSource(primary_frame_source_
);
199 frame_source_
->SetActiveSource(unthrottled_frame_source_
);
202 frame_source_
->SetActiveSource(background_frame_source_
);
204 ProcessScheduledActions();
207 void Scheduler::SetVisible(bool visible
) {
208 state_machine_
.SetVisible(visible
);
209 UpdateActiveFrameSource();
212 void Scheduler::SetCanDraw(bool can_draw
) {
213 state_machine_
.SetCanDraw(can_draw
);
214 ProcessScheduledActions();
217 void Scheduler::NotifyReadyToActivate() {
218 state_machine_
.NotifyReadyToActivate();
219 ProcessScheduledActions();
222 void Scheduler::NotifyReadyToDraw() {
223 // Empty for now, until we take action based on the notification as part of
224 // crbugs 352894, 383157, 421923.
227 void Scheduler::SetThrottleFrameProduction(bool throttle
) {
228 throttle_frame_production_
= throttle
;
229 UpdateActiveFrameSource();
232 void Scheduler::SetNeedsCommit() {
233 state_machine_
.SetNeedsCommit();
234 ProcessScheduledActions();
237 void Scheduler::SetNeedsRedraw() {
238 state_machine_
.SetNeedsRedraw();
239 ProcessScheduledActions();
242 void Scheduler::SetNeedsAnimate() {
243 state_machine_
.SetNeedsAnimate();
244 ProcessScheduledActions();
247 void Scheduler::SetNeedsPrepareTiles() {
248 DCHECK(!IsInsideAction(SchedulerStateMachine::ACTION_PREPARE_TILES
));
249 state_machine_
.SetNeedsPrepareTiles();
250 ProcessScheduledActions();
253 void Scheduler::SetMaxSwapsPending(int max
) {
254 state_machine_
.SetMaxSwapsPending(max
);
257 void Scheduler::DidSwapBuffers() {
258 state_machine_
.DidSwapBuffers();
260 // There is no need to call ProcessScheduledActions here because
261 // swapping should not trigger any new actions.
262 if (!inside_process_scheduled_actions_
) {
263 DCHECK_EQ(state_machine_
.NextAction(), SchedulerStateMachine::ACTION_NONE
);
267 void Scheduler::DidSwapBuffersComplete() {
268 state_machine_
.DidSwapBuffersComplete();
269 ProcessScheduledActions();
272 void Scheduler::SetImplLatencyTakesPriority(bool impl_latency_takes_priority
) {
273 state_machine_
.SetImplLatencyTakesPriority(impl_latency_takes_priority
);
274 ProcessScheduledActions();
277 void Scheduler::NotifyReadyToCommit() {
278 TRACE_EVENT0("cc", "Scheduler::NotifyReadyToCommit");
279 state_machine_
.NotifyReadyToCommit();
280 ProcessScheduledActions();
283 void Scheduler::BeginMainFrameAborted(CommitEarlyOutReason reason
) {
284 TRACE_EVENT1("cc", "Scheduler::BeginMainFrameAborted", "reason",
285 CommitEarlyOutReasonToString(reason
));
286 state_machine_
.BeginMainFrameAborted(reason
);
287 ProcessScheduledActions();
290 void Scheduler::DidPrepareTiles() {
291 state_machine_
.DidPrepareTiles();
294 void Scheduler::DidLoseOutputSurface() {
295 TRACE_EVENT0("cc", "Scheduler::DidLoseOutputSurface");
296 begin_retro_frame_args_
.clear();
297 begin_retro_frame_task_
.Cancel();
298 state_machine_
.DidLoseOutputSurface();
299 ProcessScheduledActions();
302 void Scheduler::DidCreateAndInitializeOutputSurface() {
303 TRACE_EVENT0("cc", "Scheduler::DidCreateAndInitializeOutputSurface");
304 DCHECK(!frame_source_
->NeedsBeginFrames());
305 DCHECK(begin_impl_frame_deadline_task_
.IsCancelled());
306 state_machine_
.DidCreateAndInitializeOutputSurface();
307 ProcessScheduledActions();
310 void Scheduler::NotifyBeginMainFrameStarted() {
311 TRACE_EVENT0("cc", "Scheduler::NotifyBeginMainFrameStarted");
312 state_machine_
.NotifyBeginMainFrameStarted();
315 base::TimeTicks
Scheduler::AnticipatedDrawTime() const {
316 if (!frame_source_
->NeedsBeginFrames() ||
317 begin_impl_frame_args_
.interval
<= base::TimeDelta())
318 return base::TimeTicks();
320 base::TimeTicks now
= Now();
321 base::TimeTicks timebase
= std::max(begin_impl_frame_args_
.frame_time
,
322 begin_impl_frame_args_
.deadline
);
323 int64 intervals
= 1 + ((now
- timebase
) / begin_impl_frame_args_
.interval
);
324 return timebase
+ (begin_impl_frame_args_
.interval
* intervals
);
327 base::TimeTicks
Scheduler::LastBeginImplFrameTime() {
328 return begin_impl_frame_args_
.frame_time
;
331 void Scheduler::SetupNextBeginFrameIfNeeded() {
332 if (!task_runner_
.get())
335 if (state_machine_
.ShouldSetNeedsBeginFrames(
336 frame_source_
->NeedsBeginFrames())) {
337 frame_source_
->SetNeedsBeginFrames(state_machine_
.BeginFrameNeeded());
340 if (state_machine_
.begin_impl_frame_state() ==
341 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE
) {
342 frame_source_
->DidFinishFrame(begin_retro_frame_args_
.size());
345 PostBeginRetroFrameIfNeeded();
346 SetupPollingMechanisms();
349 // We may need to poll when we can't rely on BeginFrame to advance certain
350 // state or to avoid deadlock.
351 void Scheduler::SetupPollingMechanisms() {
352 bool needs_advance_commit_state_timer
= false;
353 // Setup PollForAnticipatedDrawTriggers if we need to monitor state but
354 // aren't expecting any more BeginFrames. This should only be needed by
355 // the synchronous compositor when BeginFrameNeeded is false.
356 if (state_machine_
.ShouldPollForAnticipatedDrawTriggers()) {
357 DCHECK(!state_machine_
.SupportsProactiveBeginFrame());
358 if (poll_for_draw_triggers_task_
.IsCancelled()) {
359 poll_for_draw_triggers_task_
.Reset(poll_for_draw_triggers_closure_
);
360 base::TimeDelta delay
= begin_impl_frame_args_
.IsValid()
361 ? begin_impl_frame_args_
.interval
362 : BeginFrameArgs::DefaultInterval();
363 task_runner_
->PostDelayedTask(
364 FROM_HERE
, poll_for_draw_triggers_task_
.callback(), delay
);
367 poll_for_draw_triggers_task_
.Cancel();
369 // At this point we'd prefer to advance through the commit flow by
370 // drawing a frame, however it's possible that the frame rate controller
371 // will not give us a BeginFrame until the commit completes. See
372 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
373 // we set a repeating timer to poll on ProcessScheduledActions until we
374 // successfully reach BeginFrame. Synchronous compositor does not use
375 // frame rate controller or have the circular wait in the bug.
376 if (IsBeginMainFrameSentOrStarted() &&
377 !settings_
.using_synchronous_renderer_compositor
) {
378 needs_advance_commit_state_timer
= true;
382 if (needs_advance_commit_state_timer
) {
383 if (advance_commit_state_task_
.IsCancelled() &&
384 begin_impl_frame_args_
.IsValid()) {
385 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
386 // set the interval to twice the interval from the previous frame.
387 advance_commit_state_task_
.Reset(advance_commit_state_closure_
);
388 task_runner_
->PostDelayedTask(FROM_HERE
,
389 advance_commit_state_task_
.callback(),
390 begin_impl_frame_args_
.interval
* 2);
393 advance_commit_state_task_
.Cancel();
397 // BeginFrame is the mechanism that tells us that now is a good time to start
398 // making a frame. Usually this means that user input for the frame is complete.
399 // If the scheduler is busy, we queue the BeginFrame to be handled later as
400 // a BeginRetroFrame.
401 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs
& args
) {
402 TRACE_EVENT1("cc", "Scheduler::BeginFrame", "args", args
.AsValue());
404 // Deliver BeginFrames to children.
405 if (settings_
.forward_begin_frames_to_children
&&
406 state_machine_
.children_need_begin_frames()) {
407 BeginFrameArgs
adjusted_args_for_children(args
);
408 // Adjust a deadline for child schedulers.
409 // TODO(simonhong): Once we have commitless update, we can get rid of
410 // BeginMainFrameToCommitDurationEstimate() +
411 // CommitToActivateDurationEstimate().
412 adjusted_args_for_children
.deadline
-=
413 (client_
->BeginMainFrameToCommitDurationEstimate() +
414 client_
->CommitToActivateDurationEstimate() +
415 client_
->DrawDurationEstimate() + EstimatedParentDrawTime());
416 client_
->SendBeginFramesToChildren(adjusted_args_for_children
);
419 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
420 // sent us the last BeginFrame we have missed. As we might not be able to
421 // actually make rendering for this call, handle it like a "retro frame".
422 // TODO(brainderson): Add a test for this functionality ASAP!
423 if (args
.type
== BeginFrameArgs::MISSED
) {
424 begin_retro_frame_args_
.push_back(args
);
425 PostBeginRetroFrameIfNeeded();
429 BeginFrameArgs
adjusted_args(args
);
430 adjusted_args
.deadline
-= EstimatedParentDrawTime();
432 bool should_defer_begin_frame
;
433 if (settings_
.using_synchronous_renderer_compositor
) {
434 should_defer_begin_frame
= false;
436 should_defer_begin_frame
=
437 !begin_retro_frame_args_
.empty() ||
438 !begin_retro_frame_task_
.IsCancelled() ||
439 !frame_source_
->NeedsBeginFrames() ||
440 (state_machine_
.begin_impl_frame_state() !=
441 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE
);
444 if (should_defer_begin_frame
) {
445 begin_retro_frame_args_
.push_back(adjusted_args
);
446 TRACE_EVENT_INSTANT0(
447 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD
);
448 // Queuing the frame counts as "using it", so we need to return true.
450 BeginImplFrame(adjusted_args
);
455 void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames
) {
456 DCHECK(settings_
.forward_begin_frames_to_children
);
457 state_machine_
.SetChildrenNeedBeginFrames(children_need_begin_frames
);
458 ProcessScheduledActions();
461 // BeginRetroFrame is called for BeginFrames that we've deferred because
462 // the scheduler was in the middle of processing a previous BeginFrame.
463 void Scheduler::BeginRetroFrame() {
464 TRACE_EVENT0("cc", "Scheduler::BeginRetroFrame");
465 DCHECK(!settings_
.using_synchronous_renderer_compositor
);
466 DCHECK(!begin_retro_frame_args_
.empty());
467 DCHECK(!begin_retro_frame_task_
.IsCancelled());
468 DCHECK_EQ(state_machine_
.begin_impl_frame_state(),
469 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE
);
471 begin_retro_frame_task_
.Cancel();
473 // Discard expired BeginRetroFrames
474 // Today, we should always end up with at most one un-expired BeginRetroFrame
475 // because deadlines will not be greater than the next frame time. We don't
476 // DCHECK though because some systems don't always have monotonic timestamps.
477 // TODO(brianderson): In the future, long deadlines could result in us not
478 // draining the queue if we don't catch up. If we consistently can't catch
479 // up, our fallback should be to lower our frame rate.
480 base::TimeTicks now
= Now();
482 while (!begin_retro_frame_args_
.empty()) {
483 const BeginFrameArgs
& args
= begin_retro_frame_args_
.front();
484 base::TimeTicks expiration_time
= args
.frame_time
+ args
.interval
;
485 if (now
<= expiration_time
)
487 TRACE_EVENT_INSTANT2(
488 "cc", "Scheduler::BeginRetroFrame discarding", TRACE_EVENT_SCOPE_THREAD
,
489 "expiration_time - now", (expiration_time
- now
).InMillisecondsF(),
490 "BeginFrameArgs", begin_retro_frame_args_
.front().AsValue());
491 begin_retro_frame_args_
.pop_front();
492 frame_source_
->DidFinishFrame(begin_retro_frame_args_
.size());
495 if (begin_retro_frame_args_
.empty()) {
496 TRACE_EVENT_INSTANT0("cc",
497 "Scheduler::BeginRetroFrames all expired",
498 TRACE_EVENT_SCOPE_THREAD
);
500 BeginFrameArgs front
= begin_retro_frame_args_
.front();
501 begin_retro_frame_args_
.pop_front();
502 BeginImplFrame(front
);
506 // There could be a race between the posted BeginRetroFrame and a new
507 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
508 // will check if there is a pending BeginRetroFrame to ensure we handle
509 // BeginFrames in FIFO order.
510 void Scheduler::PostBeginRetroFrameIfNeeded() {
511 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
512 "Scheduler::PostBeginRetroFrameIfNeeded",
515 if (!frame_source_
->NeedsBeginFrames())
518 if (begin_retro_frame_args_
.empty() || !begin_retro_frame_task_
.IsCancelled())
521 // begin_retro_frame_args_ should always be empty for the
522 // synchronous compositor.
523 DCHECK(!settings_
.using_synchronous_renderer_compositor
);
525 if (state_machine_
.begin_impl_frame_state() !=
526 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE
)
529 begin_retro_frame_task_
.Reset(begin_retro_frame_closure_
);
531 task_runner_
->PostTask(FROM_HERE
, begin_retro_frame_task_
.callback());
534 // BeginImplFrame starts a compositor frame that will wait up until a deadline
535 // for a BeginMainFrame+activation to complete before it times out and draws
536 // any asynchronous animation and scroll/pinch updates.
537 void Scheduler::BeginImplFrame(const BeginFrameArgs
& args
) {
538 bool main_thread_is_in_high_latency_mode
=
539 state_machine_
.MainThreadIsInHighLatencyMode();
541 "Scheduler::BeginImplFrame",
544 "main_thread_is_high_latency",
545 main_thread_is_in_high_latency_mode
);
546 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
548 main_thread_is_in_high_latency_mode
);
549 DCHECK_EQ(state_machine_
.begin_impl_frame_state(),
550 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE
);
551 DCHECK(state_machine_
.HasInitializedOutputSurface());
553 advance_commit_state_task_
.Cancel();
555 begin_impl_frame_args_
= args
;
556 begin_impl_frame_args_
.deadline
-= client_
->DrawDurationEstimate();
558 if (!state_machine_
.impl_latency_takes_priority() &&
559 main_thread_is_in_high_latency_mode
&&
560 CanCommitAndActivateBeforeDeadline()) {
561 state_machine_
.SetSkipNextBeginMainFrameToReduceLatency();
564 state_machine_
.OnBeginImplFrame(begin_impl_frame_args_
);
565 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_
);
566 client_
->WillBeginImplFrame(begin_impl_frame_args_
);
568 ProcessScheduledActions();
570 state_machine_
.OnBeginImplFrameDeadlinePending();
572 if (settings_
.using_synchronous_renderer_compositor
) {
573 // The synchronous renderer compositor has to make its GL calls
575 // TODO(brianderson): Have the OutputSurface initiate the deadline tasks
576 // so the synchronous renderer compositor can take advantage of splitting
577 // up the BeginImplFrame and deadline as well.
578 OnBeginImplFrameDeadline();
580 ScheduleBeginImplFrameDeadline();
584 void Scheduler::ScheduleBeginImplFrameDeadline() {
585 // The synchronous compositor does not post a deadline task.
586 DCHECK(!settings_
.using_synchronous_renderer_compositor
);
588 begin_impl_frame_deadline_task_
.Cancel();
589 begin_impl_frame_deadline_task_
.Reset(begin_impl_frame_deadline_closure_
);
591 begin_impl_frame_deadline_mode_
=
592 state_machine_
.CurrentBeginImplFrameDeadlineMode();
594 base::TimeTicks deadline
;
595 switch (begin_impl_frame_deadline_mode_
) {
596 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_IMMEDIATE
:
597 // We are ready to draw a new active tree immediately.
598 // We don't use Now() here because it's somewhat expensive to call.
599 deadline
= base::TimeTicks();
601 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_REGULAR
:
602 // We are animating on the impl thread but we can wait for some time.
603 deadline
= begin_impl_frame_args_
.deadline
;
605 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_LATE
:
606 // We are blocked for one reason or another and we should wait.
607 // TODO(brianderson): Handle long deadlines (that are past the next
608 // frame's frame time) properly instead of using this hack.
610 begin_impl_frame_args_
.frame_time
+ begin_impl_frame_args_
.interval
;
615 "cc", "Scheduler::ScheduleBeginImplFrameDeadline", "deadline", deadline
);
617 base::TimeDelta delta
= deadline
- Now();
618 if (delta
<= base::TimeDelta())
619 delta
= base::TimeDelta();
620 task_runner_
->PostDelayedTask(
621 FROM_HERE
, begin_impl_frame_deadline_task_
.callback(), delta
);
624 void Scheduler::RescheduleBeginImplFrameDeadlineIfNeeded() {
625 if (settings_
.using_synchronous_renderer_compositor
)
628 if (state_machine_
.begin_impl_frame_state() !=
629 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME
)
632 if (begin_impl_frame_deadline_mode_
!=
633 state_machine_
.CurrentBeginImplFrameDeadlineMode())
634 ScheduleBeginImplFrameDeadline();
637 void Scheduler::OnBeginImplFrameDeadline() {
638 TRACE_EVENT0("cc", "Scheduler::OnBeginImplFrameDeadline");
639 begin_impl_frame_deadline_task_
.Cancel();
640 // We split the deadline actions up into two phases so the state machine
641 // has a chance to trigger actions that should occur durring and after
642 // the deadline separately. For example:
643 // * Sending the BeginMainFrame will not occur after the deadline in
644 // order to wait for more user-input before starting the next commit.
645 // * Creating a new OuputSurface will not occur during the deadline in
646 // order to allow the state machine to "settle" first.
647 state_machine_
.OnBeginImplFrameDeadline();
648 ProcessScheduledActions();
649 state_machine_
.OnBeginImplFrameIdle();
650 ProcessScheduledActions();
652 client_
->DidBeginImplFrameDeadline();
655 void Scheduler::PollForAnticipatedDrawTriggers() {
656 TRACE_EVENT0("cc", "Scheduler::PollForAnticipatedDrawTriggers");
657 poll_for_draw_triggers_task_
.Cancel();
658 state_machine_
.DidEnterPollForAnticipatedDrawTriggers();
659 ProcessScheduledActions();
660 state_machine_
.DidLeavePollForAnticipatedDrawTriggers();
663 void Scheduler::PollToAdvanceCommitState() {
664 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
665 advance_commit_state_task_
.Cancel();
666 ProcessScheduledActions();
669 void Scheduler::DrawAndSwapIfPossible() {
670 DrawResult result
= client_
->ScheduledActionDrawAndSwapIfPossible();
671 state_machine_
.DidDrawIfPossibleCompleted(result
);
674 void Scheduler::ProcessScheduledActions() {
675 // We do not allow ProcessScheduledActions to be recursive.
676 // The top-level call will iteratively execute the next action for us anyway.
677 if (inside_process_scheduled_actions_
)
680 base::AutoReset
<bool> mark_inside(&inside_process_scheduled_actions_
, true);
682 SchedulerStateMachine::Action action
;
684 action
= state_machine_
.NextAction();
685 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
686 "SchedulerStateMachine",
689 VLOG(2) << "Scheduler::ProcessScheduledActions: "
690 << SchedulerStateMachine::ActionToString(action
) << " "
691 << state_machine_
.GetStatesForDebugging();
692 state_machine_
.UpdateState(action
);
693 base::AutoReset
<SchedulerStateMachine::Action
>
694 mark_inside_action(&inside_action_
, action
);
696 case SchedulerStateMachine::ACTION_NONE
:
698 case SchedulerStateMachine::ACTION_ANIMATE
:
699 client_
->ScheduledActionAnimate();
701 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME
:
702 client_
->ScheduledActionSendBeginMainFrame();
704 case SchedulerStateMachine::ACTION_COMMIT
:
705 client_
->ScheduledActionCommit();
707 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE
:
708 client_
->ScheduledActionActivateSyncTree();
710 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE
:
711 DrawAndSwapIfPossible();
713 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED
:
714 client_
->ScheduledActionDrawAndSwapForced();
716 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT
:
717 // No action is actually performed, but this allows the state machine to
718 // advance out of its waiting to draw state without actually drawing.
720 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION
:
721 client_
->ScheduledActionBeginOutputSurfaceCreation();
723 case SchedulerStateMachine::ACTION_PREPARE_TILES
:
724 client_
->ScheduledActionPrepareTiles();
727 } while (action
!= SchedulerStateMachine::ACTION_NONE
);
729 SetupNextBeginFrameIfNeeded();
730 client_
->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
732 RescheduleBeginImplFrameDeadlineIfNeeded();
735 scoped_refptr
<base::debug::ConvertableToTraceFormat
> Scheduler::AsValue()
737 scoped_refptr
<base::debug::TracedValue
> state
=
738 new base::debug::TracedValue();
739 AsValueInto(state
.get());
743 void Scheduler::AsValueInto(base::debug::TracedValue
* state
) const {
744 state
->BeginDictionary("state_machine");
745 state_machine_
.AsValueInto(state
, Now());
746 state
->EndDictionary();
748 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
749 bool frame_tracing_enabled
= false;
750 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
751 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
752 &frame_tracing_enabled
);
753 if (frame_tracing_enabled
) {
754 state
->BeginDictionary("frame_source_");
755 frame_source_
->AsValueInto(state
);
756 state
->EndDictionary();
759 state
->BeginDictionary("scheduler_state");
760 state
->SetDouble("time_until_anticipated_draw_time_ms",
761 (AnticipatedDrawTime() - Now()).InMillisecondsF());
762 state
->SetDouble("estimated_parent_draw_time_ms",
763 estimated_parent_draw_time_
.InMillisecondsF());
764 state
->SetBoolean("last_set_needs_begin_frame_",
765 frame_source_
->NeedsBeginFrames());
766 state
->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_
.size());
767 state
->SetBoolean("begin_retro_frame_task_",
768 !begin_retro_frame_task_
.IsCancelled());
769 state
->SetBoolean("begin_impl_frame_deadline_task_",
770 !begin_impl_frame_deadline_task_
.IsCancelled());
771 state
->SetBoolean("poll_for_draw_triggers_task_",
772 !poll_for_draw_triggers_task_
.IsCancelled());
773 state
->SetBoolean("advance_commit_state_task_",
774 !advance_commit_state_task_
.IsCancelled());
775 state
->BeginDictionary("begin_impl_frame_args");
776 begin_impl_frame_args_
.AsValueInto(state
);
777 state
->EndDictionary();
779 state
->EndDictionary();
781 state
->BeginDictionary("client_state");
782 state
->SetDouble("draw_duration_estimate_ms",
783 client_
->DrawDurationEstimate().InMillisecondsF());
785 "begin_main_frame_to_commit_duration_estimate_ms",
786 client_
->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
788 "commit_to_activate_duration_estimate_ms",
789 client_
->CommitToActivateDurationEstimate().InMillisecondsF());
790 state
->EndDictionary();
793 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
794 // Check if the main thread computation and commit can be finished before the
795 // impl thread's deadline.
796 base::TimeTicks estimated_draw_time
=
797 begin_impl_frame_args_
.frame_time
+
798 client_
->BeginMainFrameToCommitDurationEstimate() +
799 client_
->CommitToActivateDurationEstimate();
802 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
803 "CanCommitAndActivateBeforeDeadline",
804 "time_left_after_drawing_ms",
805 (begin_impl_frame_args_
.deadline
- estimated_draw_time
).InMillisecondsF(),
809 return estimated_draw_time
< begin_impl_frame_args_
.deadline
;
812 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
813 return (state_machine_
.commit_state() ==
814 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT
||
815 state_machine_
.commit_state() ==
816 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED
);