cc: Make scheduling be driven by vsync for android webview.
[chromium-blink-merge.git] / cc / scheduler / scheduler.cc
blob3525c55afcd547394f43a4c8812931ad85dce476
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/profiler/scoped_tracker.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/trace_event/trace_event.h"
14 #include "base/trace_event/trace_event_argument.h"
15 #include "cc/debug/devtools_instrumentation.h"
16 #include "cc/debug/traced_value.h"
17 #include "cc/scheduler/delay_based_time_source.h"
18 #include "ui/gfx/frame_time.h"
20 namespace cc {
22 BeginFrameSource* SchedulerFrameSourcesConstructor::ConstructPrimaryFrameSource(
23 Scheduler* scheduler) {
24 if (scheduler->settings_.use_external_begin_frame_source) {
25 TRACE_EVENT1("cc",
26 "Scheduler::Scheduler()",
27 "PrimaryFrameSource",
28 "ExternalBeginFrameSource");
29 DCHECK(scheduler->primary_frame_source_internal_)
30 << "Need external BeginFrameSource";
31 return scheduler->primary_frame_source_internal_.get();
32 } else {
33 TRACE_EVENT1("cc",
34 "Scheduler::Scheduler()",
35 "PrimaryFrameSource",
36 "SyntheticBeginFrameSource");
37 scoped_ptr<SyntheticBeginFrameSource> synthetic_source =
38 SyntheticBeginFrameSource::Create(scheduler->task_runner_.get(),
39 scheduler->Now(),
40 BeginFrameArgs::DefaultInterval());
42 DCHECK(!scheduler->vsync_observer_);
43 scheduler->vsync_observer_ = synthetic_source.get();
45 DCHECK(!scheduler->primary_frame_source_internal_);
46 scheduler->primary_frame_source_internal_ = synthetic_source.Pass();
47 return scheduler->primary_frame_source_internal_.get();
51 BeginFrameSource*
52 SchedulerFrameSourcesConstructor::ConstructBackgroundFrameSource(
53 Scheduler* scheduler) {
54 TRACE_EVENT1("cc",
55 "Scheduler::Scheduler()",
56 "BackgroundFrameSource",
57 "SyntheticBeginFrameSource");
58 DCHECK(!(scheduler->background_frame_source_internal_));
59 scheduler->background_frame_source_internal_ =
60 SyntheticBeginFrameSource::Create(
61 scheduler->task_runner_.get(), scheduler->Now(),
62 scheduler->settings_.background_frame_interval);
63 return scheduler->background_frame_source_internal_.get();
66 BeginFrameSource*
67 SchedulerFrameSourcesConstructor::ConstructUnthrottledFrameSource(
68 Scheduler* scheduler) {
69 TRACE_EVENT1("cc", "Scheduler::Scheduler()", "UnthrottledFrameSource",
70 "BackToBackBeginFrameSource");
71 DCHECK(!scheduler->unthrottled_frame_source_internal_);
72 scheduler->unthrottled_frame_source_internal_ =
73 BackToBackBeginFrameSource::Create(scheduler->task_runner_.get());
74 return scheduler->unthrottled_frame_source_internal_.get();
77 Scheduler::Scheduler(
78 SchedulerClient* client,
79 const SchedulerSettings& scheduler_settings,
80 int layer_tree_host_id,
81 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
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 authoritative_vsync_interval_(base::TimeDelta()),
91 last_vsync_timebase_(base::TimeTicks()),
92 throttle_frame_production_(scheduler_settings.throttle_frame_production),
93 settings_(scheduler_settings),
94 client_(client),
95 layer_tree_host_id_(layer_tree_host_id),
96 task_runner_(task_runner),
97 begin_impl_frame_deadline_mode_(
98 SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_NONE),
99 state_machine_(scheduler_settings),
100 inside_process_scheduled_actions_(false),
101 inside_action_(SchedulerStateMachine::ACTION_NONE),
102 weak_factory_(this) {
103 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
104 "Scheduler::Scheduler",
105 "settings",
106 settings_.AsValue());
107 DCHECK(client_);
108 DCHECK(!state_machine_.BeginFrameNeeded());
110 begin_retro_frame_closure_ =
111 base::Bind(&Scheduler::BeginRetroFrame, weak_factory_.GetWeakPtr());
112 begin_impl_frame_deadline_closure_ = base::Bind(
113 &Scheduler::OnBeginImplFrameDeadline, weak_factory_.GetWeakPtr());
114 advance_commit_state_closure_ = base::Bind(
115 &Scheduler::PollToAdvanceCommitState, weak_factory_.GetWeakPtr());
117 frame_source_ = BeginFrameSourceMultiplexer::Create();
118 frame_source_->AddObserver(this);
120 // Primary frame source
121 primary_frame_source_ =
122 frame_sources_constructor->ConstructPrimaryFrameSource(this);
123 frame_source_->AddSource(primary_frame_source_);
124 primary_frame_source_->SetClientReady();
126 // Background ticking frame source
127 background_frame_source_ =
128 frame_sources_constructor->ConstructBackgroundFrameSource(this);
129 frame_source_->AddSource(background_frame_source_);
131 // Unthrottled frame source
132 unthrottled_frame_source_ =
133 frame_sources_constructor->ConstructUnthrottledFrameSource(this);
134 frame_source_->AddSource(unthrottled_frame_source_);
137 Scheduler::~Scheduler() {
138 if (frame_source_->NeedsBeginFrames())
139 frame_source_->SetNeedsBeginFrames(false);
142 base::TimeTicks Scheduler::Now() const {
143 base::TimeTicks now = gfx::FrameTime::Now();
144 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.now"),
145 "Scheduler::Now",
146 "now",
147 now);
148 return now;
151 void Scheduler::CommitVSyncParameters(base::TimeTicks timebase,
152 base::TimeDelta interval) {
153 if (authoritative_vsync_interval_ != base::TimeDelta()) {
154 interval = authoritative_vsync_interval_;
155 } else if (interval == base::TimeDelta()) {
156 // TODO(brianderson): We should not be receiving 0 intervals.
157 interval = BeginFrameArgs::DefaultInterval();
160 last_vsync_timebase_ = timebase;
162 if (vsync_observer_)
163 vsync_observer_->OnUpdateVSyncParameters(timebase, interval);
166 void Scheduler::SetEstimatedParentDrawTime(base::TimeDelta draw_time) {
167 DCHECK_GE(draw_time.ToInternalValue(), 0);
168 estimated_parent_draw_time_ = draw_time;
171 void Scheduler::SetCanStart() {
172 state_machine_.SetCanStart();
173 ProcessScheduledActions();
176 void Scheduler::UpdateActiveFrameSource() {
177 if (state_machine_.visible()) {
178 if (throttle_frame_production_) {
179 frame_source_->SetActiveSource(primary_frame_source_);
180 } else {
181 frame_source_->SetActiveSource(unthrottled_frame_source_);
183 } else {
184 frame_source_->SetActiveSource(background_frame_source_);
186 ProcessScheduledActions();
189 void Scheduler::SetVisible(bool visible) {
190 state_machine_.SetVisible(visible);
191 UpdateActiveFrameSource();
194 void Scheduler::SetCanDraw(bool can_draw) {
195 state_machine_.SetCanDraw(can_draw);
196 ProcessScheduledActions();
199 void Scheduler::NotifyReadyToActivate() {
200 state_machine_.NotifyReadyToActivate();
201 ProcessScheduledActions();
204 void Scheduler::NotifyReadyToDraw() {
205 // Empty for now, until we take action based on the notification as part of
206 // crbugs 352894, 383157, 421923.
209 void Scheduler::SetThrottleFrameProduction(bool throttle) {
210 throttle_frame_production_ = throttle;
211 UpdateActiveFrameSource();
214 void Scheduler::SetNeedsCommit() {
215 state_machine_.SetNeedsCommit();
216 ProcessScheduledActions();
219 void Scheduler::SetNeedsRedraw() {
220 state_machine_.SetNeedsRedraw();
221 ProcessScheduledActions();
224 void Scheduler::SetNeedsAnimate() {
225 state_machine_.SetNeedsAnimate();
226 ProcessScheduledActions();
229 void Scheduler::SetNeedsPrepareTiles() {
230 DCHECK(!IsInsideAction(SchedulerStateMachine::ACTION_PREPARE_TILES));
231 state_machine_.SetNeedsPrepareTiles();
232 ProcessScheduledActions();
235 void Scheduler::SetMaxSwapsPending(int max) {
236 state_machine_.SetMaxSwapsPending(max);
239 void Scheduler::DidSwapBuffers() {
240 state_machine_.DidSwapBuffers();
242 // There is no need to call ProcessScheduledActions here because
243 // swapping should not trigger any new actions.
244 if (!inside_process_scheduled_actions_) {
245 DCHECK_EQ(state_machine_.NextAction(), SchedulerStateMachine::ACTION_NONE);
249 void Scheduler::DidSwapBuffersComplete() {
250 state_machine_.DidSwapBuffersComplete();
251 ProcessScheduledActions();
254 void Scheduler::SetImplLatencyTakesPriority(bool impl_latency_takes_priority) {
255 state_machine_.SetImplLatencyTakesPriority(impl_latency_takes_priority);
256 ProcessScheduledActions();
259 void Scheduler::NotifyReadyToCommit() {
260 TRACE_EVENT0("cc", "Scheduler::NotifyReadyToCommit");
261 state_machine_.NotifyReadyToCommit();
262 ProcessScheduledActions();
265 void Scheduler::BeginMainFrameAborted(CommitEarlyOutReason reason) {
266 TRACE_EVENT1("cc", "Scheduler::BeginMainFrameAborted", "reason",
267 CommitEarlyOutReasonToString(reason));
268 state_machine_.BeginMainFrameAborted(reason);
269 ProcessScheduledActions();
272 void Scheduler::DidPrepareTiles() {
273 state_machine_.DidPrepareTiles();
276 void Scheduler::DidLoseOutputSurface() {
277 TRACE_EVENT0("cc", "Scheduler::DidLoseOutputSurface");
278 begin_retro_frame_args_.clear();
279 begin_retro_frame_task_.Cancel();
280 state_machine_.DidLoseOutputSurface();
281 ProcessScheduledActions();
284 void Scheduler::DidCreateAndInitializeOutputSurface() {
285 TRACE_EVENT0("cc", "Scheduler::DidCreateAndInitializeOutputSurface");
286 DCHECK(!frame_source_->NeedsBeginFrames());
287 DCHECK(begin_impl_frame_deadline_task_.IsCancelled());
288 state_machine_.DidCreateAndInitializeOutputSurface();
289 ProcessScheduledActions();
292 void Scheduler::NotifyBeginMainFrameStarted() {
293 TRACE_EVENT0("cc", "Scheduler::NotifyBeginMainFrameStarted");
294 state_machine_.NotifyBeginMainFrameStarted();
297 base::TimeTicks Scheduler::AnticipatedDrawTime() const {
298 if (!frame_source_->NeedsBeginFrames() ||
299 begin_impl_frame_args_.interval <= base::TimeDelta())
300 return base::TimeTicks();
302 base::TimeTicks now = Now();
303 base::TimeTicks timebase = std::max(begin_impl_frame_args_.frame_time,
304 begin_impl_frame_args_.deadline);
305 int64 intervals = 1 + ((now - timebase) / begin_impl_frame_args_.interval);
306 return timebase + (begin_impl_frame_args_.interval * intervals);
309 base::TimeTicks Scheduler::LastBeginImplFrameTime() {
310 return begin_impl_frame_args_.frame_time;
313 void Scheduler::SetupNextBeginFrameIfNeeded() {
314 // Never call SetNeedsBeginFrames if the frame source already has the right
315 // value.
316 if (frame_source_->NeedsBeginFrames() != state_machine_.BeginFrameNeeded()) {
317 if (state_machine_.BeginFrameNeeded()) {
318 // Call SetNeedsBeginFrames(true) as soon as possible.
319 frame_source_->SetNeedsBeginFrames(true);
320 } else if (state_machine_.begin_impl_frame_state() ==
321 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE) {
322 // Call SetNeedsBeginFrames(false) in between frames only.
323 frame_source_->SetNeedsBeginFrames(false);
324 client_->SendBeginMainFrameNotExpectedSoon();
328 PostBeginRetroFrameIfNeeded();
331 // We may need to poll when we can't rely on BeginFrame to advance certain
332 // state or to avoid deadlock.
333 void Scheduler::SetupPollingMechanisms() {
334 // At this point we'd prefer to advance through the commit flow by
335 // drawing a frame, however it's possible that the frame rate controller
336 // will not give us a BeginFrame until the commit completes. See
337 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
338 // we set a repeating timer to poll on ProcessScheduledActions until we
339 // successfully reach BeginFrame. Synchronous compositor does not use
340 // frame rate controller or have the circular wait in the bug.
341 if (IsBeginMainFrameSentOrStarted() &&
342 !settings_.using_synchronous_renderer_compositor) {
343 if (advance_commit_state_task_.IsCancelled() &&
344 begin_impl_frame_args_.IsValid()) {
345 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
346 // set the interval to twice the interval from the previous frame.
347 advance_commit_state_task_.Reset(advance_commit_state_closure_);
348 task_runner_->PostDelayedTask(FROM_HERE,
349 advance_commit_state_task_.callback(),
350 begin_impl_frame_args_.interval * 2);
352 } else {
353 advance_commit_state_task_.Cancel();
357 // BeginFrame is the mechanism that tells us that now is a good time to start
358 // making a frame. Usually this means that user input for the frame is complete.
359 // If the scheduler is busy, we queue the BeginFrame to be handled later as
360 // a BeginRetroFrame.
361 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs& args) {
362 TRACE_EVENT1("cc,benchmark", "Scheduler::BeginFrame", "args", args.AsValue());
364 // Deliver BeginFrames to children.
365 if (state_machine_.children_need_begin_frames()) {
366 BeginFrameArgs adjusted_args_for_children(args);
367 // Adjust a deadline for child schedulers.
368 // TODO(simonhong): Once we have commitless update, we can get rid of
369 // BeginMainFrameToCommitDurationEstimate() +
370 // CommitToActivateDurationEstimate().
371 adjusted_args_for_children.deadline -=
372 (client_->BeginMainFrameToCommitDurationEstimate() +
373 client_->CommitToActivateDurationEstimate() +
374 client_->DrawDurationEstimate() + EstimatedParentDrawTime());
375 client_->SendBeginFramesToChildren(adjusted_args_for_children);
378 BeginFrameArgs adjusted_args(args);
379 adjusted_args.deadline -= EstimatedParentDrawTime();
381 if (settings_.using_synchronous_renderer_compositor) {
382 BeginImplFrameSynchronous(adjusted_args);
383 return true;
386 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
387 // sent us the last BeginFrame we have missed. As we might not be able to
388 // actually make rendering for this call, handle it like a "retro frame".
389 // TODO(brainderson): Add a test for this functionality ASAP!
390 if (adjusted_args.type == BeginFrameArgs::MISSED) {
391 begin_retro_frame_args_.push_back(adjusted_args);
392 PostBeginRetroFrameIfNeeded();
393 return true;
396 bool should_defer_begin_frame =
397 !begin_retro_frame_args_.empty() ||
398 !begin_retro_frame_task_.IsCancelled() ||
399 !frame_source_->NeedsBeginFrames() ||
400 (state_machine_.begin_impl_frame_state() !=
401 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
403 if (should_defer_begin_frame) {
404 begin_retro_frame_args_.push_back(adjusted_args);
405 TRACE_EVENT_INSTANT0(
406 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD);
407 // Queuing the frame counts as "using it", so we need to return true.
408 } else {
409 BeginImplFrameWithDeadline(adjusted_args);
411 return true;
414 void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
415 state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames);
416 ProcessScheduledActions();
419 void Scheduler::SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) {
420 authoritative_vsync_interval_ = interval;
421 if (vsync_observer_)
422 vsync_observer_->OnUpdateVSyncParameters(last_vsync_timebase_, interval);
425 void Scheduler::OnDrawForOutputSurface() {
426 DCHECK(settings_.using_synchronous_renderer_compositor);
427 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
428 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
429 DCHECK(!BeginImplFrameDeadlinePending());
431 state_machine_.OnBeginImplFrameDeadline();
432 ProcessScheduledActions();
434 state_machine_.OnBeginImplFrameIdle();
435 ProcessScheduledActions();
438 // BeginRetroFrame is called for BeginFrames that we've deferred because
439 // the scheduler was in the middle of processing a previous BeginFrame.
440 void Scheduler::BeginRetroFrame() {
441 TRACE_EVENT0("cc,benchmark", "Scheduler::BeginRetroFrame");
442 DCHECK(!settings_.using_synchronous_renderer_compositor);
443 DCHECK(!begin_retro_frame_args_.empty());
444 DCHECK(!begin_retro_frame_task_.IsCancelled());
445 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
446 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
448 begin_retro_frame_task_.Cancel();
450 // Discard expired BeginRetroFrames
451 // Today, we should always end up with at most one un-expired BeginRetroFrame
452 // because deadlines will not be greater than the next frame time. We don't
453 // DCHECK though because some systems don't always have monotonic timestamps.
454 // TODO(brianderson): In the future, long deadlines could result in us not
455 // draining the queue if we don't catch up. If we consistently can't catch
456 // up, our fallback should be to lower our frame rate.
457 base::TimeTicks now = Now();
459 while (!begin_retro_frame_args_.empty()) {
460 const BeginFrameArgs& args = begin_retro_frame_args_.front();
461 base::TimeTicks expiration_time = args.frame_time + args.interval;
462 if (now <= expiration_time)
463 break;
464 TRACE_EVENT_INSTANT2(
465 "cc", "Scheduler::BeginRetroFrame discarding", TRACE_EVENT_SCOPE_THREAD,
466 "expiration_time - now", (expiration_time - now).InMillisecondsF(),
467 "BeginFrameArgs", begin_retro_frame_args_.front().AsValue());
468 begin_retro_frame_args_.pop_front();
469 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
472 if (begin_retro_frame_args_.empty()) {
473 TRACE_EVENT_INSTANT0("cc",
474 "Scheduler::BeginRetroFrames all expired",
475 TRACE_EVENT_SCOPE_THREAD);
476 } else {
477 BeginFrameArgs front = begin_retro_frame_args_.front();
478 begin_retro_frame_args_.pop_front();
479 BeginImplFrameWithDeadline(front);
483 // There could be a race between the posted BeginRetroFrame and a new
484 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
485 // will check if there is a pending BeginRetroFrame to ensure we handle
486 // BeginFrames in FIFO order.
487 void Scheduler::PostBeginRetroFrameIfNeeded() {
488 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
489 "Scheduler::PostBeginRetroFrameIfNeeded",
490 "state",
491 AsValue());
492 if (!frame_source_->NeedsBeginFrames())
493 return;
495 if (begin_retro_frame_args_.empty() || !begin_retro_frame_task_.IsCancelled())
496 return;
498 // begin_retro_frame_args_ should always be empty for the
499 // synchronous compositor.
500 DCHECK(!settings_.using_synchronous_renderer_compositor);
502 if (state_machine_.begin_impl_frame_state() !=
503 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE)
504 return;
506 begin_retro_frame_task_.Reset(begin_retro_frame_closure_);
508 task_runner_->PostTask(FROM_HERE, begin_retro_frame_task_.callback());
511 void Scheduler::BeginImplFrameWithDeadline(const BeginFrameArgs& args) {
512 BeginImplFrame(args);
514 // The deadline will be scheduled in ProcessScheduledActions.
515 state_machine_.OnBeginImplFrameDeadlinePending();
516 ProcessScheduledActions();
519 void Scheduler::BeginImplFrameSynchronous(const BeginFrameArgs& args) {
520 BeginImplFrame(args);
521 FinishImplFrame();
524 void Scheduler::FinishImplFrame() {
525 state_machine_.OnBeginImplFrameIdle();
526 ProcessScheduledActions();
528 client_->DidBeginImplFrameDeadline();
529 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
532 // BeginImplFrame starts a compositor frame that will wait up until a deadline
533 // for a BeginMainFrame+activation to complete before it times out and draws
534 // any asynchronous animation and scroll/pinch updates.
535 void Scheduler::BeginImplFrame(const BeginFrameArgs& args) {
536 bool main_thread_is_in_high_latency_mode =
537 state_machine_.MainThreadIsInHighLatencyMode();
538 TRACE_EVENT2("cc,benchmark",
539 "Scheduler::BeginImplFrame",
540 "args",
541 args.AsValue(),
542 "main_thread_is_high_latency",
543 main_thread_is_in_high_latency_mode);
544 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
545 "MainThreadLatency",
546 main_thread_is_in_high_latency_mode);
547 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
548 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
549 DCHECK(!BeginImplFrameDeadlinePending());
550 DCHECK(state_machine_.HasInitializedOutputSurface());
552 advance_commit_state_task_.Cancel();
554 begin_impl_frame_args_ = args;
555 begin_impl_frame_args_.deadline -= client_->DrawDurationEstimate();
557 if (!state_machine_.impl_latency_takes_priority() &&
558 main_thread_is_in_high_latency_mode &&
559 CanCommitAndActivateBeforeDeadline()) {
560 state_machine_.SetSkipNextBeginMainFrameToReduceLatency();
563 state_machine_.OnBeginImplFrame();
564 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_);
565 client_->WillBeginImplFrame(begin_impl_frame_args_);
567 ProcessScheduledActions();
570 void Scheduler::ScheduleBeginImplFrameDeadline() {
571 // The synchronous compositor does not post a deadline task.
572 DCHECK(!settings_.using_synchronous_renderer_compositor);
574 begin_impl_frame_deadline_task_.Cancel();
575 begin_impl_frame_deadline_task_.Reset(begin_impl_frame_deadline_closure_);
577 begin_impl_frame_deadline_mode_ =
578 state_machine_.CurrentBeginImplFrameDeadlineMode();
580 base::TimeTicks deadline;
581 switch (begin_impl_frame_deadline_mode_) {
582 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_NONE:
583 // No deadline.
584 return;
585 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_IMMEDIATE:
586 // We are ready to draw a new active tree immediately.
587 // We don't use Now() here because it's somewhat expensive to call.
588 deadline = base::TimeTicks();
589 break;
590 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_REGULAR:
591 // We are animating on the impl thread but we can wait for some time.
592 deadline = begin_impl_frame_args_.deadline;
593 break;
594 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_LATE:
595 // We are blocked for one reason or another and we should wait.
596 // TODO(brianderson): Handle long deadlines (that are past the next
597 // frame's frame time) properly instead of using this hack.
598 deadline =
599 begin_impl_frame_args_.frame_time + begin_impl_frame_args_.interval;
600 break;
603 TRACE_EVENT2("cc", "Scheduler::ScheduleBeginImplFrameDeadline", "mode",
604 SchedulerStateMachine::BeginImplFrameDeadlineModeToString(
605 begin_impl_frame_deadline_mode_),
606 "deadline", deadline);
608 base::TimeDelta delta = std::max(deadline - Now(), base::TimeDelta());
609 task_runner_->PostDelayedTask(
610 FROM_HERE, begin_impl_frame_deadline_task_.callback(), delta);
613 void Scheduler::ScheduleBeginImplFrameDeadlineIfNeeded() {
614 if (settings_.using_synchronous_renderer_compositor)
615 return;
617 if (state_machine_.begin_impl_frame_state() !=
618 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME)
619 return;
621 if (begin_impl_frame_deadline_mode_ ==
622 state_machine_.CurrentBeginImplFrameDeadlineMode() &&
623 BeginImplFrameDeadlinePending())
624 return;
626 ScheduleBeginImplFrameDeadline();
629 void Scheduler::OnBeginImplFrameDeadline() {
630 TRACE_EVENT0("cc,benchmark", "Scheduler::OnBeginImplFrameDeadline");
631 begin_impl_frame_deadline_task_.Cancel();
632 // We split the deadline actions up into two phases so the state machine
633 // has a chance to trigger actions that should occur durring and after
634 // the deadline separately. For example:
635 // * Sending the BeginMainFrame will not occur after the deadline in
636 // order to wait for more user-input before starting the next commit.
637 // * Creating a new OuputSurface will not occur during the deadline in
638 // order to allow the state machine to "settle" first.
640 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
641 tracked_objects::ScopedTracker tracking_profile1(
642 FROM_HERE_WITH_EXPLICIT_FUNCTION(
643 "461509 Scheduler::OnBeginImplFrameDeadline1"));
644 state_machine_.OnBeginImplFrameDeadline();
645 ProcessScheduledActions();
646 FinishImplFrame();
650 void Scheduler::PollToAdvanceCommitState() {
651 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
652 advance_commit_state_task_.Cancel();
653 ProcessScheduledActions();
656 void Scheduler::DrawAndSwapIfPossible() {
657 DrawResult result = client_->ScheduledActionDrawAndSwapIfPossible();
658 state_machine_.DidDrawIfPossibleCompleted(result);
661 void Scheduler::SetDeferCommits(bool defer_commits) {
662 TRACE_EVENT1("cc", "Scheduler::SetDeferCommits",
663 "defer_commits",
664 defer_commits);
665 state_machine_.SetDeferCommits(defer_commits);
666 ProcessScheduledActions();
669 void Scheduler::ProcessScheduledActions() {
670 // We do not allow ProcessScheduledActions to be recursive.
671 // The top-level call will iteratively execute the next action for us anyway.
672 if (inside_process_scheduled_actions_)
673 return;
675 base::AutoReset<bool> mark_inside(&inside_process_scheduled_actions_, true);
677 SchedulerStateMachine::Action action;
678 do {
679 action = state_machine_.NextAction();
680 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
681 "SchedulerStateMachine",
682 "state",
683 AsValue());
684 VLOG(2) << "Scheduler::ProcessScheduledActions: "
685 << SchedulerStateMachine::ActionToString(action) << " "
686 << state_machine_.GetStatesForDebugging();
687 state_machine_.UpdateState(action);
688 base::AutoReset<SchedulerStateMachine::Action>
689 mark_inside_action(&inside_action_, action);
690 switch (action) {
691 case SchedulerStateMachine::ACTION_NONE:
692 break;
693 case SchedulerStateMachine::ACTION_ANIMATE:
694 client_->ScheduledActionAnimate();
695 break;
696 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME:
697 client_->ScheduledActionSendBeginMainFrame();
698 break;
699 case SchedulerStateMachine::ACTION_COMMIT: {
700 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
701 // fixed.
702 tracked_objects::ScopedTracker tracking_profile4(
703 FROM_HERE_WITH_EXPLICIT_FUNCTION(
704 "461509 Scheduler::ProcessScheduledActions4"));
705 client_->ScheduledActionCommit();
706 break;
708 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE:
709 client_->ScheduledActionActivateSyncTree();
710 break;
711 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE: {
712 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
713 // fixed.
714 tracked_objects::ScopedTracker tracking_profile6(
715 FROM_HERE_WITH_EXPLICIT_FUNCTION(
716 "461509 Scheduler::ProcessScheduledActions6"));
717 DrawAndSwapIfPossible();
718 break;
720 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED:
721 client_->ScheduledActionDrawAndSwapForced();
722 break;
723 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT:
724 // No action is actually performed, but this allows the state machine to
725 // advance out of its waiting to draw state without actually drawing.
726 break;
727 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION:
728 client_->ScheduledActionBeginOutputSurfaceCreation();
729 break;
730 case SchedulerStateMachine::ACTION_PREPARE_TILES:
731 client_->ScheduledActionPrepareTiles();
732 break;
733 case SchedulerStateMachine::ACTION_INVALIDATE_OUTPUT_SURFACE: {
734 client_->ScheduledActionInvalidateOutputSurface();
735 break;
738 } while (action != SchedulerStateMachine::ACTION_NONE);
740 SetupPollingMechanisms();
742 client_->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
744 ScheduleBeginImplFrameDeadlineIfNeeded();
746 SetupNextBeginFrameIfNeeded();
749 scoped_refptr<base::trace_event::ConvertableToTraceFormat> Scheduler::AsValue()
750 const {
751 scoped_refptr<base::trace_event::TracedValue> state =
752 new base::trace_event::TracedValue();
753 AsValueInto(state.get());
754 return state;
757 void Scheduler::AsValueInto(base::trace_event::TracedValue* state) const {
758 state->BeginDictionary("state_machine");
759 state_machine_.AsValueInto(state);
760 state->EndDictionary();
762 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
763 bool frame_tracing_enabled = false;
764 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
765 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
766 &frame_tracing_enabled);
767 if (frame_tracing_enabled) {
768 state->BeginDictionary("frame_source_");
769 frame_source_->AsValueInto(state);
770 state->EndDictionary();
773 state->BeginDictionary("scheduler_state");
774 state->SetDouble("time_until_anticipated_draw_time_ms",
775 (AnticipatedDrawTime() - Now()).InMillisecondsF());
776 state->SetDouble("estimated_parent_draw_time_ms",
777 estimated_parent_draw_time_.InMillisecondsF());
778 state->SetBoolean("last_set_needs_begin_frame_",
779 frame_source_->NeedsBeginFrames());
780 state->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_.size());
781 state->SetBoolean("begin_retro_frame_task_",
782 !begin_retro_frame_task_.IsCancelled());
783 state->SetBoolean("begin_impl_frame_deadline_task_",
784 !begin_impl_frame_deadline_task_.IsCancelled());
785 state->SetBoolean("advance_commit_state_task_",
786 !advance_commit_state_task_.IsCancelled());
787 state->BeginDictionary("begin_impl_frame_args");
788 begin_impl_frame_args_.AsValueInto(state);
789 state->EndDictionary();
791 base::TimeTicks now = Now();
792 base::TimeTicks frame_time = begin_impl_frame_args_.frame_time;
793 base::TimeTicks deadline = begin_impl_frame_args_.deadline;
794 base::TimeDelta interval = begin_impl_frame_args_.interval;
795 state->BeginDictionary("major_timestamps_in_ms");
796 state->SetDouble("0_interval", interval.InMillisecondsF());
797 state->SetDouble("1_now_to_deadline", (deadline - now).InMillisecondsF());
798 state->SetDouble("2_frame_time_to_now", (now - frame_time).InMillisecondsF());
799 state->SetDouble("3_frame_time_to_deadline",
800 (deadline - frame_time).InMillisecondsF());
801 state->SetDouble("4_now", (now - base::TimeTicks()).InMillisecondsF());
802 state->SetDouble("5_frame_time",
803 (frame_time - base::TimeTicks()).InMillisecondsF());
804 state->SetDouble("6_deadline",
805 (deadline - base::TimeTicks()).InMillisecondsF());
806 state->EndDictionary();
808 state->EndDictionary();
810 state->BeginDictionary("client_state");
811 state->SetDouble("draw_duration_estimate_ms",
812 client_->DrawDurationEstimate().InMillisecondsF());
813 state->SetDouble(
814 "begin_main_frame_to_commit_duration_estimate_ms",
815 client_->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
816 state->SetDouble(
817 "commit_to_activate_duration_estimate_ms",
818 client_->CommitToActivateDurationEstimate().InMillisecondsF());
819 state->EndDictionary();
822 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
823 // Check if the main thread computation and commit can be finished before the
824 // impl thread's deadline.
825 base::TimeTicks estimated_draw_time =
826 begin_impl_frame_args_.frame_time +
827 client_->BeginMainFrameToCommitDurationEstimate() +
828 client_->CommitToActivateDurationEstimate();
830 TRACE_EVENT2(
831 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
832 "CanCommitAndActivateBeforeDeadline",
833 "time_left_after_drawing_ms",
834 (begin_impl_frame_args_.deadline - estimated_draw_time).InMillisecondsF(),
835 "state",
836 AsValue());
838 return estimated_draw_time < begin_impl_frame_args_.deadline;
841 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
842 return (state_machine_.commit_state() ==
843 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT ||
844 state_machine_.commit_state() ==
845 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED);
848 } // namespace cc