[Enhanced Bookmark] Change "Bookmark Bar" to "Bookmark bar" on Android
[chromium-blink-merge.git] / cc / scheduler / scheduler.cc
blob37e7c5352b0db92479aa8e49e6c04431cca1a8a7
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 state_machine_(scheduler_settings),
98 inside_process_scheduled_actions_(false),
99 inside_action_(SchedulerStateMachine::ACTION_NONE),
100 weak_factory_(this) {
101 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
102 "Scheduler::Scheduler",
103 "settings",
104 settings_.AsValue());
105 DCHECK(client_);
106 DCHECK(!state_machine_.BeginFrameNeeded());
108 begin_retro_frame_closure_ =
109 base::Bind(&Scheduler::BeginRetroFrame, weak_factory_.GetWeakPtr());
110 begin_impl_frame_deadline_closure_ = base::Bind(
111 &Scheduler::OnBeginImplFrameDeadline, weak_factory_.GetWeakPtr());
112 poll_for_draw_triggers_closure_ = base::Bind(
113 &Scheduler::PollForAnticipatedDrawTriggers, 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 bool needs_advance_commit_state_timer = false;
335 // Setup PollForAnticipatedDrawTriggers if we need to monitor state but
336 // aren't expecting any more BeginFrames. This should only be needed by
337 // the synchronous compositor when BeginFrameNeeded is false.
338 if (state_machine_.ShouldPollForAnticipatedDrawTriggers()) {
339 DCHECK(!state_machine_.SupportsProactiveBeginFrame());
340 if (poll_for_draw_triggers_task_.IsCancelled()) {
341 poll_for_draw_triggers_task_.Reset(poll_for_draw_triggers_closure_);
342 base::TimeDelta delay = begin_impl_frame_args_.IsValid()
343 ? begin_impl_frame_args_.interval
344 : BeginFrameArgs::DefaultInterval();
345 task_runner_->PostDelayedTask(
346 FROM_HERE, poll_for_draw_triggers_task_.callback(), delay);
348 } else {
349 poll_for_draw_triggers_task_.Cancel();
351 // At this point we'd prefer to advance through the commit flow by
352 // drawing a frame, however it's possible that the frame rate controller
353 // will not give us a BeginFrame until the commit completes. See
354 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
355 // we set a repeating timer to poll on ProcessScheduledActions until we
356 // successfully reach BeginFrame. Synchronous compositor does not use
357 // frame rate controller or have the circular wait in the bug.
358 if (IsBeginMainFrameSentOrStarted() &&
359 !settings_.using_synchronous_renderer_compositor) {
360 needs_advance_commit_state_timer = true;
364 if (needs_advance_commit_state_timer) {
365 if (advance_commit_state_task_.IsCancelled() &&
366 begin_impl_frame_args_.IsValid()) {
367 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
368 // set the interval to twice the interval from the previous frame.
369 advance_commit_state_task_.Reset(advance_commit_state_closure_);
370 task_runner_->PostDelayedTask(FROM_HERE,
371 advance_commit_state_task_.callback(),
372 begin_impl_frame_args_.interval * 2);
374 } else {
375 advance_commit_state_task_.Cancel();
379 // BeginFrame is the mechanism that tells us that now is a good time to start
380 // making a frame. Usually this means that user input for the frame is complete.
381 // If the scheduler is busy, we queue the BeginFrame to be handled later as
382 // a BeginRetroFrame.
383 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs& args) {
384 TRACE_EVENT1("cc,benchmark", "Scheduler::BeginFrame", "args", args.AsValue());
386 // Deliver BeginFrames to children.
387 if (state_machine_.children_need_begin_frames()) {
388 BeginFrameArgs adjusted_args_for_children(args);
389 // Adjust a deadline for child schedulers.
390 // TODO(simonhong): Once we have commitless update, we can get rid of
391 // BeginMainFrameToCommitDurationEstimate() +
392 // CommitToActivateDurationEstimate().
393 adjusted_args_for_children.deadline -=
394 (client_->BeginMainFrameToCommitDurationEstimate() +
395 client_->CommitToActivateDurationEstimate() +
396 client_->DrawDurationEstimate() + EstimatedParentDrawTime());
397 client_->SendBeginFramesToChildren(adjusted_args_for_children);
400 BeginFrameArgs adjusted_args(args);
401 adjusted_args.deadline -= EstimatedParentDrawTime();
403 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
404 // sent us the last BeginFrame we have missed. As we might not be able to
405 // actually make rendering for this call, handle it like a "retro frame".
406 // TODO(brainderson): Add a test for this functionality ASAP!
407 if (adjusted_args.type == BeginFrameArgs::MISSED) {
408 begin_retro_frame_args_.push_back(adjusted_args);
409 PostBeginRetroFrameIfNeeded();
410 return true;
413 bool should_defer_begin_frame;
414 if (settings_.using_synchronous_renderer_compositor) {
415 should_defer_begin_frame = false;
416 } else {
417 should_defer_begin_frame =
418 !begin_retro_frame_args_.empty() ||
419 !begin_retro_frame_task_.IsCancelled() ||
420 !frame_source_->NeedsBeginFrames() ||
421 (state_machine_.begin_impl_frame_state() !=
422 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
425 if (should_defer_begin_frame) {
426 begin_retro_frame_args_.push_back(adjusted_args);
427 TRACE_EVENT_INSTANT0(
428 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD);
429 // Queuing the frame counts as "using it", so we need to return true.
430 } else {
431 BeginImplFrame(adjusted_args);
433 return true;
436 void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
437 state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames);
438 ProcessScheduledActions();
441 void Scheduler::SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) {
442 authoritative_vsync_interval_ = interval;
443 if (vsync_observer_)
444 vsync_observer_->OnUpdateVSyncParameters(last_vsync_timebase_, interval);
447 // BeginRetroFrame is called for BeginFrames that we've deferred because
448 // the scheduler was in the middle of processing a previous BeginFrame.
449 void Scheduler::BeginRetroFrame() {
450 TRACE_EVENT0("cc,benchmark", "Scheduler::BeginRetroFrame");
451 DCHECK(!settings_.using_synchronous_renderer_compositor);
452 DCHECK(!begin_retro_frame_args_.empty());
453 DCHECK(!begin_retro_frame_task_.IsCancelled());
454 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
455 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
457 begin_retro_frame_task_.Cancel();
459 // Discard expired BeginRetroFrames
460 // Today, we should always end up with at most one un-expired BeginRetroFrame
461 // because deadlines will not be greater than the next frame time. We don't
462 // DCHECK though because some systems don't always have monotonic timestamps.
463 // TODO(brianderson): In the future, long deadlines could result in us not
464 // draining the queue if we don't catch up. If we consistently can't catch
465 // up, our fallback should be to lower our frame rate.
466 base::TimeTicks now = Now();
468 while (!begin_retro_frame_args_.empty()) {
469 const BeginFrameArgs& args = begin_retro_frame_args_.front();
470 base::TimeTicks expiration_time = args.frame_time + args.interval;
471 if (now <= expiration_time)
472 break;
473 TRACE_EVENT_INSTANT2(
474 "cc", "Scheduler::BeginRetroFrame discarding", TRACE_EVENT_SCOPE_THREAD,
475 "expiration_time - now", (expiration_time - now).InMillisecondsF(),
476 "BeginFrameArgs", begin_retro_frame_args_.front().AsValue());
477 begin_retro_frame_args_.pop_front();
478 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
481 if (begin_retro_frame_args_.empty()) {
482 TRACE_EVENT_INSTANT0("cc",
483 "Scheduler::BeginRetroFrames all expired",
484 TRACE_EVENT_SCOPE_THREAD);
485 } else {
486 BeginFrameArgs front = begin_retro_frame_args_.front();
487 begin_retro_frame_args_.pop_front();
488 BeginImplFrame(front);
492 // There could be a race between the posted BeginRetroFrame and a new
493 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
494 // will check if there is a pending BeginRetroFrame to ensure we handle
495 // BeginFrames in FIFO order.
496 void Scheduler::PostBeginRetroFrameIfNeeded() {
497 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
498 "Scheduler::PostBeginRetroFrameIfNeeded",
499 "state",
500 AsValue());
501 if (!frame_source_->NeedsBeginFrames())
502 return;
504 if (begin_retro_frame_args_.empty() || !begin_retro_frame_task_.IsCancelled())
505 return;
507 // begin_retro_frame_args_ should always be empty for the
508 // synchronous compositor.
509 DCHECK(!settings_.using_synchronous_renderer_compositor);
511 if (state_machine_.begin_impl_frame_state() !=
512 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE)
513 return;
515 begin_retro_frame_task_.Reset(begin_retro_frame_closure_);
517 task_runner_->PostTask(FROM_HERE, begin_retro_frame_task_.callback());
520 // BeginImplFrame starts a compositor frame that will wait up until a deadline
521 // for a BeginMainFrame+activation to complete before it times out and draws
522 // any asynchronous animation and scroll/pinch updates.
523 void Scheduler::BeginImplFrame(const BeginFrameArgs& args) {
524 bool main_thread_is_in_high_latency_mode =
525 state_machine_.MainThreadIsInHighLatencyMode();
526 TRACE_EVENT2("cc,benchmark",
527 "Scheduler::BeginImplFrame",
528 "args",
529 args.AsValue(),
530 "main_thread_is_high_latency",
531 main_thread_is_in_high_latency_mode);
532 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
533 "MainThreadLatency",
534 main_thread_is_in_high_latency_mode);
535 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
536 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
537 DCHECK(state_machine_.HasInitializedOutputSurface());
539 advance_commit_state_task_.Cancel();
541 begin_impl_frame_args_ = args;
542 begin_impl_frame_args_.deadline -= client_->DrawDurationEstimate();
544 if (!state_machine_.impl_latency_takes_priority() &&
545 main_thread_is_in_high_latency_mode &&
546 CanCommitAndActivateBeforeDeadline()) {
547 state_machine_.SetSkipNextBeginMainFrameToReduceLatency();
550 state_machine_.OnBeginImplFrame();
551 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_);
552 client_->WillBeginImplFrame(begin_impl_frame_args_);
554 ProcessScheduledActions();
556 state_machine_.OnBeginImplFrameDeadlinePending();
558 if (settings_.using_synchronous_renderer_compositor) {
559 // The synchronous renderer compositor has to make its GL calls
560 // within this call.
561 // TODO(brianderson): Have the OutputSurface initiate the deadline tasks
562 // so the synchronous renderer compositor can take advantage of splitting
563 // up the BeginImplFrame and deadline as well.
564 OnBeginImplFrameDeadline();
565 } else {
566 ScheduleBeginImplFrameDeadline();
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_IMMEDIATE:
583 // We are ready to draw a new active tree immediately.
584 // We don't use Now() here because it's somewhat expensive to call.
585 deadline = base::TimeTicks();
586 break;
587 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_REGULAR:
588 // We are animating on the impl thread but we can wait for some time.
589 deadline = begin_impl_frame_args_.deadline;
590 break;
591 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_LATE:
592 // We are blocked for one reason or another and we should wait.
593 // TODO(brianderson): Handle long deadlines (that are past the next
594 // frame's frame time) properly instead of using this hack.
595 deadline =
596 begin_impl_frame_args_.frame_time + begin_impl_frame_args_.interval;
597 break;
600 TRACE_EVENT1(
601 "cc", "Scheduler::ScheduleBeginImplFrameDeadline", "deadline", deadline);
603 base::TimeDelta delta = deadline - Now();
604 if (delta <= base::TimeDelta())
605 delta = base::TimeDelta();
606 task_runner_->PostDelayedTask(
607 FROM_HERE, begin_impl_frame_deadline_task_.callback(), delta);
610 void Scheduler::RescheduleBeginImplFrameDeadlineIfNeeded() {
611 if (settings_.using_synchronous_renderer_compositor)
612 return;
614 if (state_machine_.begin_impl_frame_state() !=
615 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME)
616 return;
618 if (begin_impl_frame_deadline_mode_ !=
619 state_machine_.CurrentBeginImplFrameDeadlineMode())
620 ScheduleBeginImplFrameDeadline();
623 void Scheduler::OnBeginImplFrameDeadline() {
624 TRACE_EVENT0("cc,benchmark", "Scheduler::OnBeginImplFrameDeadline");
625 begin_impl_frame_deadline_task_.Cancel();
626 // We split the deadline actions up into two phases so the state machine
627 // has a chance to trigger actions that should occur durring and after
628 // the deadline separately. For example:
629 // * Sending the BeginMainFrame will not occur after the deadline in
630 // order to wait for more user-input before starting the next commit.
631 // * Creating a new OuputSurface will not occur during the deadline in
632 // order to allow the state machine to "settle" first.
634 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
635 tracked_objects::ScopedTracker tracking_profile1(
636 FROM_HERE_WITH_EXPLICIT_FUNCTION(
637 "461509 Scheduler::OnBeginImplFrameDeadline1"));
638 state_machine_.OnBeginImplFrameDeadline();
639 ProcessScheduledActions();
640 state_machine_.OnBeginImplFrameIdle();
641 ProcessScheduledActions();
643 client_->DidBeginImplFrameDeadline();
644 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
647 void Scheduler::PollForAnticipatedDrawTriggers() {
648 TRACE_EVENT0("cc", "Scheduler::PollForAnticipatedDrawTriggers");
649 poll_for_draw_triggers_task_.Cancel();
650 state_machine_.DidEnterPollForAnticipatedDrawTriggers();
651 ProcessScheduledActions();
652 state_machine_.DidLeavePollForAnticipatedDrawTriggers();
655 void Scheduler::PollToAdvanceCommitState() {
656 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
657 advance_commit_state_task_.Cancel();
658 ProcessScheduledActions();
661 void Scheduler::DrawAndSwapIfPossible() {
662 DrawResult result = client_->ScheduledActionDrawAndSwapIfPossible();
663 state_machine_.DidDrawIfPossibleCompleted(result);
666 void Scheduler::SetDeferCommits(bool defer_commits) {
667 TRACE_EVENT1("cc", "Scheduler::SetDeferCommits",
668 "defer_commits",
669 defer_commits);
670 state_machine_.SetDeferCommits(defer_commits);
671 ProcessScheduledActions();
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_)
678 return;
680 base::AutoReset<bool> mark_inside(&inside_process_scheduled_actions_, true);
682 SchedulerStateMachine::Action action;
683 do {
684 action = state_machine_.NextAction();
685 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
686 "SchedulerStateMachine",
687 "state",
688 AsValue());
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);
695 switch (action) {
696 case SchedulerStateMachine::ACTION_NONE:
697 break;
698 case SchedulerStateMachine::ACTION_ANIMATE:
699 client_->ScheduledActionAnimate();
700 break;
701 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME:
702 client_->ScheduledActionSendBeginMainFrame();
703 break;
704 case SchedulerStateMachine::ACTION_COMMIT: {
705 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
706 // fixed.
707 tracked_objects::ScopedTracker tracking_profile4(
708 FROM_HERE_WITH_EXPLICIT_FUNCTION(
709 "461509 Scheduler::ProcessScheduledActions4"));
710 client_->ScheduledActionCommit();
711 break;
713 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE:
714 client_->ScheduledActionActivateSyncTree();
715 break;
716 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE: {
717 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
718 // fixed.
719 tracked_objects::ScopedTracker tracking_profile6(
720 FROM_HERE_WITH_EXPLICIT_FUNCTION(
721 "461509 Scheduler::ProcessScheduledActions6"));
722 DrawAndSwapIfPossible();
723 break;
725 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED:
726 client_->ScheduledActionDrawAndSwapForced();
727 break;
728 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT:
729 // No action is actually performed, but this allows the state machine to
730 // advance out of its waiting to draw state without actually drawing.
731 break;
732 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION:
733 client_->ScheduledActionBeginOutputSurfaceCreation();
734 break;
735 case SchedulerStateMachine::ACTION_PREPARE_TILES:
736 client_->ScheduledActionPrepareTiles();
737 break;
739 } while (action != SchedulerStateMachine::ACTION_NONE);
741 SetupPollingMechanisms();
743 client_->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
745 RescheduleBeginImplFrameDeadlineIfNeeded();
747 SetupNextBeginFrameIfNeeded();
750 scoped_refptr<base::trace_event::ConvertableToTraceFormat> Scheduler::AsValue()
751 const {
752 scoped_refptr<base::trace_event::TracedValue> state =
753 new base::trace_event::TracedValue();
754 AsValueInto(state.get());
755 return state;
758 void Scheduler::AsValueInto(base::trace_event::TracedValue* state) const {
759 state->BeginDictionary("state_machine");
760 state_machine_.AsValueInto(state);
761 state->EndDictionary();
763 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
764 bool frame_tracing_enabled = false;
765 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
766 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
767 &frame_tracing_enabled);
768 if (frame_tracing_enabled) {
769 state->BeginDictionary("frame_source_");
770 frame_source_->AsValueInto(state);
771 state->EndDictionary();
774 state->BeginDictionary("scheduler_state");
775 state->SetDouble("time_until_anticipated_draw_time_ms",
776 (AnticipatedDrawTime() - Now()).InMillisecondsF());
777 state->SetDouble("estimated_parent_draw_time_ms",
778 estimated_parent_draw_time_.InMillisecondsF());
779 state->SetBoolean("last_set_needs_begin_frame_",
780 frame_source_->NeedsBeginFrames());
781 state->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_.size());
782 state->SetBoolean("begin_retro_frame_task_",
783 !begin_retro_frame_task_.IsCancelled());
784 state->SetBoolean("begin_impl_frame_deadline_task_",
785 !begin_impl_frame_deadline_task_.IsCancelled());
786 state->SetBoolean("poll_for_draw_triggers_task_",
787 !poll_for_draw_triggers_task_.IsCancelled());
788 state->SetBoolean("advance_commit_state_task_",
789 !advance_commit_state_task_.IsCancelled());
790 state->BeginDictionary("begin_impl_frame_args");
791 begin_impl_frame_args_.AsValueInto(state);
792 state->EndDictionary();
794 base::TimeTicks now = Now();
795 base::TimeTicks frame_time = begin_impl_frame_args_.frame_time;
796 base::TimeTicks deadline = begin_impl_frame_args_.deadline;
797 base::TimeDelta interval = begin_impl_frame_args_.interval;
798 state->BeginDictionary("major_timestamps_in_ms");
799 state->SetDouble("0_interval", interval.InMillisecondsF());
800 state->SetDouble("1_now_to_deadline", (deadline - now).InMillisecondsF());
801 state->SetDouble("2_frame_time_to_now", (now - frame_time).InMillisecondsF());
802 state->SetDouble("3_frame_time_to_deadline",
803 (deadline - frame_time).InMillisecondsF());
804 state->SetDouble("4_now", (now - base::TimeTicks()).InMillisecondsF());
805 state->SetDouble("5_frame_time",
806 (frame_time - base::TimeTicks()).InMillisecondsF());
807 state->SetDouble("6_deadline",
808 (deadline - base::TimeTicks()).InMillisecondsF());
809 state->EndDictionary();
811 state->EndDictionary();
813 state->BeginDictionary("client_state");
814 state->SetDouble("draw_duration_estimate_ms",
815 client_->DrawDurationEstimate().InMillisecondsF());
816 state->SetDouble(
817 "begin_main_frame_to_commit_duration_estimate_ms",
818 client_->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
819 state->SetDouble(
820 "commit_to_activate_duration_estimate_ms",
821 client_->CommitToActivateDurationEstimate().InMillisecondsF());
822 state->EndDictionary();
825 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
826 // Check if the main thread computation and commit can be finished before the
827 // impl thread's deadline.
828 base::TimeTicks estimated_draw_time =
829 begin_impl_frame_args_.frame_time +
830 client_->BeginMainFrameToCommitDurationEstimate() +
831 client_->CommitToActivateDurationEstimate();
833 TRACE_EVENT2(
834 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
835 "CanCommitAndActivateBeforeDeadline",
836 "time_left_after_drawing_ms",
837 (begin_impl_frame_args_.deadline - estimated_draw_time).InMillisecondsF(),
838 "state",
839 AsValue());
841 return estimated_draw_time < begin_impl_frame_args_.deadline;
844 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
845 return (state_machine_.commit_state() ==
846 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT ||
847 state_machine_.commit_state() ==
848 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED);
851 } // namespace cc