Add ExitFunnel instrumentation to browser rendezvous path.
[chromium-blink-merge.git] / cc / scheduler / scheduler.cc
blob904a0574515dac727b021f59386a721a0bb2f3c7
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"
7 #include <algorithm>
9 #include "base/auto_reset.h"
10 #include "base/logging.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/trace_event/trace_event.h"
13 #include "base/trace_event/trace_event_argument.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"
19 namespace cc {
21 BeginFrameSource* SchedulerFrameSourcesConstructor::ConstructPrimaryFrameSource(
22 Scheduler* scheduler) {
23 if (scheduler->settings_.use_external_begin_frame_source) {
24 TRACE_EVENT1("cc",
25 "Scheduler::Scheduler()",
26 "PrimaryFrameSource",
27 "ExternalBeginFrameSource");
28 DCHECK(scheduler->primary_frame_source_internal_)
29 << "Need external BeginFrameSource";
30 return scheduler->primary_frame_source_internal_.get();
31 } else {
32 TRACE_EVENT1("cc",
33 "Scheduler::Scheduler()",
34 "PrimaryFrameSource",
35 "SyntheticBeginFrameSource");
36 scoped_ptr<SyntheticBeginFrameSource> synthetic_source =
37 SyntheticBeginFrameSource::Create(scheduler->task_runner_.get(),
38 scheduler->Now(),
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();
50 BeginFrameSource*
51 SchedulerFrameSourcesConstructor::ConstructBackgroundFrameSource(
52 Scheduler* scheduler) {
53 TRACE_EVENT1("cc",
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();
65 BeginFrameSource*
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();
76 Scheduler::Scheduler(
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)
84 : frame_source_(),
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),
92 client_(client),
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),
99 weak_factory_(this) {
100 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
101 "Scheduler::Scheduler",
102 "settings",
103 settings_.AsValue());
104 DCHECK(client_);
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"),
147 "Scheduler::Now",
148 "now",
149 now);
150 return 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();
180 if (vsync_observer_)
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_);
198 } else {
199 frame_source_->SetActiveSource(unthrottled_frame_source_);
201 } else {
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())
333 return;
335 if (state_machine_.ShouldSetNeedsBeginFrames(
336 frame_source_->NeedsBeginFrames())) {
337 frame_source_->SetNeedsBeginFrames(state_machine_.BeginFrameNeeded());
338 if (!frame_source_->NeedsBeginFrames()) {
339 client_->SendBeginMainFrameNotExpectedSoon();
343 if (state_machine_.begin_impl_frame_state() ==
344 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE) {
345 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
348 PostBeginRetroFrameIfNeeded();
349 SetupPollingMechanisms();
352 // We may need to poll when we can't rely on BeginFrame to advance certain
353 // state or to avoid deadlock.
354 void Scheduler::SetupPollingMechanisms() {
355 bool needs_advance_commit_state_timer = false;
356 // Setup PollForAnticipatedDrawTriggers if we need to monitor state but
357 // aren't expecting any more BeginFrames. This should only be needed by
358 // the synchronous compositor when BeginFrameNeeded is false.
359 if (state_machine_.ShouldPollForAnticipatedDrawTriggers()) {
360 DCHECK(!state_machine_.SupportsProactiveBeginFrame());
361 if (poll_for_draw_triggers_task_.IsCancelled()) {
362 poll_for_draw_triggers_task_.Reset(poll_for_draw_triggers_closure_);
363 base::TimeDelta delay = begin_impl_frame_args_.IsValid()
364 ? begin_impl_frame_args_.interval
365 : BeginFrameArgs::DefaultInterval();
366 task_runner_->PostDelayedTask(
367 FROM_HERE, poll_for_draw_triggers_task_.callback(), delay);
369 } else {
370 poll_for_draw_triggers_task_.Cancel();
372 // At this point we'd prefer to advance through the commit flow by
373 // drawing a frame, however it's possible that the frame rate controller
374 // will not give us a BeginFrame until the commit completes. See
375 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
376 // we set a repeating timer to poll on ProcessScheduledActions until we
377 // successfully reach BeginFrame. Synchronous compositor does not use
378 // frame rate controller or have the circular wait in the bug.
379 if (IsBeginMainFrameSentOrStarted() &&
380 !settings_.using_synchronous_renderer_compositor) {
381 needs_advance_commit_state_timer = true;
385 if (needs_advance_commit_state_timer) {
386 if (advance_commit_state_task_.IsCancelled() &&
387 begin_impl_frame_args_.IsValid()) {
388 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
389 // set the interval to twice the interval from the previous frame.
390 advance_commit_state_task_.Reset(advance_commit_state_closure_);
391 task_runner_->PostDelayedTask(FROM_HERE,
392 advance_commit_state_task_.callback(),
393 begin_impl_frame_args_.interval * 2);
395 } else {
396 advance_commit_state_task_.Cancel();
400 // BeginFrame is the mechanism that tells us that now is a good time to start
401 // making a frame. Usually this means that user input for the frame is complete.
402 // If the scheduler is busy, we queue the BeginFrame to be handled later as
403 // a BeginRetroFrame.
404 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs& args) {
405 TRACE_EVENT1("cc,benchmark", "Scheduler::BeginFrame", "args", args.AsValue());
407 // Deliver BeginFrames to children.
408 if (settings_.forward_begin_frames_to_children &&
409 state_machine_.children_need_begin_frames()) {
410 BeginFrameArgs adjusted_args_for_children(args);
411 // Adjust a deadline for child schedulers.
412 // TODO(simonhong): Once we have commitless update, we can get rid of
413 // BeginMainFrameToCommitDurationEstimate() +
414 // CommitToActivateDurationEstimate().
415 adjusted_args_for_children.deadline -=
416 (client_->BeginMainFrameToCommitDurationEstimate() +
417 client_->CommitToActivateDurationEstimate() +
418 client_->DrawDurationEstimate() + EstimatedParentDrawTime());
419 client_->SendBeginFramesToChildren(adjusted_args_for_children);
422 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
423 // sent us the last BeginFrame we have missed. As we might not be able to
424 // actually make rendering for this call, handle it like a "retro frame".
425 // TODO(brainderson): Add a test for this functionality ASAP!
426 if (args.type == BeginFrameArgs::MISSED) {
427 begin_retro_frame_args_.push_back(args);
428 PostBeginRetroFrameIfNeeded();
429 return true;
432 BeginFrameArgs adjusted_args(args);
433 adjusted_args.deadline -= EstimatedParentDrawTime();
435 bool should_defer_begin_frame;
436 if (settings_.using_synchronous_renderer_compositor) {
437 should_defer_begin_frame = false;
438 } else {
439 should_defer_begin_frame =
440 !begin_retro_frame_args_.empty() ||
441 !begin_retro_frame_task_.IsCancelled() ||
442 !frame_source_->NeedsBeginFrames() ||
443 (state_machine_.begin_impl_frame_state() !=
444 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
447 if (should_defer_begin_frame) {
448 begin_retro_frame_args_.push_back(adjusted_args);
449 TRACE_EVENT_INSTANT0(
450 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD);
451 // Queuing the frame counts as "using it", so we need to return true.
452 } else {
453 BeginImplFrame(adjusted_args);
455 return true;
458 void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
459 DCHECK(settings_.forward_begin_frames_to_children);
460 state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames);
461 ProcessScheduledActions();
464 // BeginRetroFrame is called for BeginFrames that we've deferred because
465 // the scheduler was in the middle of processing a previous BeginFrame.
466 void Scheduler::BeginRetroFrame() {
467 TRACE_EVENT0("cc,benchmark", "Scheduler::BeginRetroFrame");
468 DCHECK(!settings_.using_synchronous_renderer_compositor);
469 DCHECK(!begin_retro_frame_args_.empty());
470 DCHECK(!begin_retro_frame_task_.IsCancelled());
471 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
472 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
474 begin_retro_frame_task_.Cancel();
476 // Discard expired BeginRetroFrames
477 // Today, we should always end up with at most one un-expired BeginRetroFrame
478 // because deadlines will not be greater than the next frame time. We don't
479 // DCHECK though because some systems don't always have monotonic timestamps.
480 // TODO(brianderson): In the future, long deadlines could result in us not
481 // draining the queue if we don't catch up. If we consistently can't catch
482 // up, our fallback should be to lower our frame rate.
483 base::TimeTicks now = Now();
485 while (!begin_retro_frame_args_.empty()) {
486 const BeginFrameArgs& args = begin_retro_frame_args_.front();
487 base::TimeTicks expiration_time = args.frame_time + args.interval;
488 if (now <= expiration_time)
489 break;
490 TRACE_EVENT_INSTANT2(
491 "cc", "Scheduler::BeginRetroFrame discarding", TRACE_EVENT_SCOPE_THREAD,
492 "expiration_time - now", (expiration_time - now).InMillisecondsF(),
493 "BeginFrameArgs", begin_retro_frame_args_.front().AsValue());
494 begin_retro_frame_args_.pop_front();
495 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
498 if (begin_retro_frame_args_.empty()) {
499 TRACE_EVENT_INSTANT0("cc",
500 "Scheduler::BeginRetroFrames all expired",
501 TRACE_EVENT_SCOPE_THREAD);
502 } else {
503 BeginFrameArgs front = begin_retro_frame_args_.front();
504 begin_retro_frame_args_.pop_front();
505 BeginImplFrame(front);
509 // There could be a race between the posted BeginRetroFrame and a new
510 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
511 // will check if there is a pending BeginRetroFrame to ensure we handle
512 // BeginFrames in FIFO order.
513 void Scheduler::PostBeginRetroFrameIfNeeded() {
514 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
515 "Scheduler::PostBeginRetroFrameIfNeeded",
516 "state",
517 AsValue());
518 if (!frame_source_->NeedsBeginFrames())
519 return;
521 if (begin_retro_frame_args_.empty() || !begin_retro_frame_task_.IsCancelled())
522 return;
524 // begin_retro_frame_args_ should always be empty for the
525 // synchronous compositor.
526 DCHECK(!settings_.using_synchronous_renderer_compositor);
528 if (state_machine_.begin_impl_frame_state() !=
529 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE)
530 return;
532 begin_retro_frame_task_.Reset(begin_retro_frame_closure_);
534 task_runner_->PostTask(FROM_HERE, begin_retro_frame_task_.callback());
537 // BeginImplFrame starts a compositor frame that will wait up until a deadline
538 // for a BeginMainFrame+activation to complete before it times out and draws
539 // any asynchronous animation and scroll/pinch updates.
540 void Scheduler::BeginImplFrame(const BeginFrameArgs& args) {
541 bool main_thread_is_in_high_latency_mode =
542 state_machine_.MainThreadIsInHighLatencyMode();
543 TRACE_EVENT2("cc,benchmark",
544 "Scheduler::BeginImplFrame",
545 "args",
546 args.AsValue(),
547 "main_thread_is_high_latency",
548 main_thread_is_in_high_latency_mode);
549 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
550 "MainThreadLatency",
551 main_thread_is_in_high_latency_mode);
552 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
553 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
554 DCHECK(state_machine_.HasInitializedOutputSurface());
556 advance_commit_state_task_.Cancel();
558 begin_impl_frame_args_ = args;
559 begin_impl_frame_args_.deadline -= client_->DrawDurationEstimate();
561 if (!state_machine_.impl_latency_takes_priority() &&
562 main_thread_is_in_high_latency_mode &&
563 CanCommitAndActivateBeforeDeadline()) {
564 state_machine_.SetSkipNextBeginMainFrameToReduceLatency();
567 state_machine_.OnBeginImplFrame(begin_impl_frame_args_);
568 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_);
569 client_->WillBeginImplFrame(begin_impl_frame_args_);
571 ProcessScheduledActions();
573 state_machine_.OnBeginImplFrameDeadlinePending();
575 if (settings_.using_synchronous_renderer_compositor) {
576 // The synchronous renderer compositor has to make its GL calls
577 // within this call.
578 // TODO(brianderson): Have the OutputSurface initiate the deadline tasks
579 // so the synchronous renderer compositor can take advantage of splitting
580 // up the BeginImplFrame and deadline as well.
581 OnBeginImplFrameDeadline();
582 } else {
583 ScheduleBeginImplFrameDeadline();
587 void Scheduler::ScheduleBeginImplFrameDeadline() {
588 // The synchronous compositor does not post a deadline task.
589 DCHECK(!settings_.using_synchronous_renderer_compositor);
591 begin_impl_frame_deadline_task_.Cancel();
592 begin_impl_frame_deadline_task_.Reset(begin_impl_frame_deadline_closure_);
594 begin_impl_frame_deadline_mode_ =
595 state_machine_.CurrentBeginImplFrameDeadlineMode();
597 base::TimeTicks deadline;
598 switch (begin_impl_frame_deadline_mode_) {
599 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_IMMEDIATE:
600 // We are ready to draw a new active tree immediately.
601 // We don't use Now() here because it's somewhat expensive to call.
602 deadline = base::TimeTicks();
603 break;
604 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_REGULAR:
605 // We are animating on the impl thread but we can wait for some time.
606 deadline = begin_impl_frame_args_.deadline;
607 break;
608 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_LATE:
609 // We are blocked for one reason or another and we should wait.
610 // TODO(brianderson): Handle long deadlines (that are past the next
611 // frame's frame time) properly instead of using this hack.
612 deadline =
613 begin_impl_frame_args_.frame_time + begin_impl_frame_args_.interval;
614 break;
617 TRACE_EVENT1(
618 "cc", "Scheduler::ScheduleBeginImplFrameDeadline", "deadline", deadline);
620 base::TimeDelta delta = deadline - Now();
621 if (delta <= base::TimeDelta())
622 delta = base::TimeDelta();
623 task_runner_->PostDelayedTask(
624 FROM_HERE, begin_impl_frame_deadline_task_.callback(), delta);
627 void Scheduler::RescheduleBeginImplFrameDeadlineIfNeeded() {
628 if (settings_.using_synchronous_renderer_compositor)
629 return;
631 if (state_machine_.begin_impl_frame_state() !=
632 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME)
633 return;
635 if (begin_impl_frame_deadline_mode_ !=
636 state_machine_.CurrentBeginImplFrameDeadlineMode())
637 ScheduleBeginImplFrameDeadline();
640 void Scheduler::OnBeginImplFrameDeadline() {
641 TRACE_EVENT0("cc,benchmark", "Scheduler::OnBeginImplFrameDeadline");
642 begin_impl_frame_deadline_task_.Cancel();
643 // We split the deadline actions up into two phases so the state machine
644 // has a chance to trigger actions that should occur durring and after
645 // the deadline separately. For example:
646 // * Sending the BeginMainFrame will not occur after the deadline in
647 // order to wait for more user-input before starting the next commit.
648 // * Creating a new OuputSurface will not occur during the deadline in
649 // order to allow the state machine to "settle" first.
650 state_machine_.OnBeginImplFrameDeadline();
651 ProcessScheduledActions();
652 state_machine_.OnBeginImplFrameIdle();
653 ProcessScheduledActions();
655 client_->DidBeginImplFrameDeadline();
658 void Scheduler::PollForAnticipatedDrawTriggers() {
659 TRACE_EVENT0("cc", "Scheduler::PollForAnticipatedDrawTriggers");
660 poll_for_draw_triggers_task_.Cancel();
661 state_machine_.DidEnterPollForAnticipatedDrawTriggers();
662 ProcessScheduledActions();
663 state_machine_.DidLeavePollForAnticipatedDrawTriggers();
666 void Scheduler::PollToAdvanceCommitState() {
667 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
668 advance_commit_state_task_.Cancel();
669 ProcessScheduledActions();
672 void Scheduler::DrawAndSwapIfPossible() {
673 DrawResult result = client_->ScheduledActionDrawAndSwapIfPossible();
674 state_machine_.DidDrawIfPossibleCompleted(result);
677 void Scheduler::SetDeferCommits(bool defer_commits) {
678 TRACE_EVENT1("cc", "Scheduler::SetDeferCommits",
679 "defer_commits",
680 defer_commits);
681 state_machine_.SetDeferCommits(defer_commits);
682 ProcessScheduledActions();
685 void Scheduler::ProcessScheduledActions() {
686 // We do not allow ProcessScheduledActions to be recursive.
687 // The top-level call will iteratively execute the next action for us anyway.
688 if (inside_process_scheduled_actions_)
689 return;
691 base::AutoReset<bool> mark_inside(&inside_process_scheduled_actions_, true);
693 SchedulerStateMachine::Action action;
694 do {
695 action = state_machine_.NextAction();
696 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
697 "SchedulerStateMachine",
698 "state",
699 AsValue());
700 VLOG(2) << "Scheduler::ProcessScheduledActions: "
701 << SchedulerStateMachine::ActionToString(action) << " "
702 << state_machine_.GetStatesForDebugging();
703 state_machine_.UpdateState(action);
704 base::AutoReset<SchedulerStateMachine::Action>
705 mark_inside_action(&inside_action_, action);
706 switch (action) {
707 case SchedulerStateMachine::ACTION_NONE:
708 break;
709 case SchedulerStateMachine::ACTION_ANIMATE:
710 client_->ScheduledActionAnimate();
711 break;
712 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME:
713 client_->ScheduledActionSendBeginMainFrame();
714 break;
715 case SchedulerStateMachine::ACTION_COMMIT:
716 client_->ScheduledActionCommit();
717 break;
718 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE:
719 client_->ScheduledActionActivateSyncTree();
720 break;
721 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE:
722 DrawAndSwapIfPossible();
723 break;
724 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED:
725 client_->ScheduledActionDrawAndSwapForced();
726 break;
727 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT:
728 // No action is actually performed, but this allows the state machine to
729 // advance out of its waiting to draw state without actually drawing.
730 break;
731 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION:
732 client_->ScheduledActionBeginOutputSurfaceCreation();
733 break;
734 case SchedulerStateMachine::ACTION_PREPARE_TILES:
735 client_->ScheduledActionPrepareTiles();
736 break;
738 } while (action != SchedulerStateMachine::ACTION_NONE);
740 SetupNextBeginFrameIfNeeded();
741 client_->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
743 RescheduleBeginImplFrameDeadlineIfNeeded();
746 scoped_refptr<base::trace_event::ConvertableToTraceFormat> Scheduler::AsValue()
747 const {
748 scoped_refptr<base::trace_event::TracedValue> state =
749 new base::trace_event::TracedValue();
750 AsValueInto(state.get());
751 return state;
754 void Scheduler::AsValueInto(base::trace_event::TracedValue* state) const {
755 state->BeginDictionary("state_machine");
756 state_machine_.AsValueInto(state, Now());
757 state->EndDictionary();
759 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
760 bool frame_tracing_enabled = false;
761 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
762 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
763 &frame_tracing_enabled);
764 if (frame_tracing_enabled) {
765 state->BeginDictionary("frame_source_");
766 frame_source_->AsValueInto(state);
767 state->EndDictionary();
770 state->BeginDictionary("scheduler_state");
771 state->SetDouble("time_until_anticipated_draw_time_ms",
772 (AnticipatedDrawTime() - Now()).InMillisecondsF());
773 state->SetDouble("estimated_parent_draw_time_ms",
774 estimated_parent_draw_time_.InMillisecondsF());
775 state->SetBoolean("last_set_needs_begin_frame_",
776 frame_source_->NeedsBeginFrames());
777 state->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_.size());
778 state->SetBoolean("begin_retro_frame_task_",
779 !begin_retro_frame_task_.IsCancelled());
780 state->SetBoolean("begin_impl_frame_deadline_task_",
781 !begin_impl_frame_deadline_task_.IsCancelled());
782 state->SetBoolean("poll_for_draw_triggers_task_",
783 !poll_for_draw_triggers_task_.IsCancelled());
784 state->SetBoolean("advance_commit_state_task_",
785 !advance_commit_state_task_.IsCancelled());
786 state->BeginDictionary("begin_impl_frame_args");
787 begin_impl_frame_args_.AsValueInto(state);
788 state->EndDictionary();
790 state->EndDictionary();
792 state->BeginDictionary("client_state");
793 state->SetDouble("draw_duration_estimate_ms",
794 client_->DrawDurationEstimate().InMillisecondsF());
795 state->SetDouble(
796 "begin_main_frame_to_commit_duration_estimate_ms",
797 client_->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
798 state->SetDouble(
799 "commit_to_activate_duration_estimate_ms",
800 client_->CommitToActivateDurationEstimate().InMillisecondsF());
801 state->EndDictionary();
804 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
805 // Check if the main thread computation and commit can be finished before the
806 // impl thread's deadline.
807 base::TimeTicks estimated_draw_time =
808 begin_impl_frame_args_.frame_time +
809 client_->BeginMainFrameToCommitDurationEstimate() +
810 client_->CommitToActivateDurationEstimate();
812 TRACE_EVENT2(
813 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
814 "CanCommitAndActivateBeforeDeadline",
815 "time_left_after_drawing_ms",
816 (begin_impl_frame_args_.deadline - estimated_draw_time).InMillisecondsF(),
817 "state",
818 AsValue());
820 return estimated_draw_time < begin_impl_frame_args_.deadline;
823 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
824 return (state_machine_.commit_state() ==
825 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT ||
826 state_machine_.commit_state() ==
827 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED);
830 } // namespace cc