Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / cc / scheduler / scheduler.cc
blobb190988e8571ec8ec38978309b73df7caf700dd5
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/debug/trace_event.h"
11 #include "base/debug/trace_event_argument.h"
12 #include "base/logging.h"
13 #include "base/single_thread_task_runner.h"
14 #include "cc/debug/devtools_instrumentation.h"
15 #include "cc/debug/traced_value.h"
16 #include "cc/scheduler/delay_based_time_source.h"
17 #include "ui/gfx/frame_time.h"
19 namespace cc {
21 BeginFrameSource* SchedulerFrameSourcesConstructor::ConstructPrimaryFrameSource(
22 Scheduler* scheduler) {
23 if (!scheduler->settings_.throttle_frame_production) {
24 TRACE_EVENT1("cc",
25 "Scheduler::Scheduler()",
26 "PrimaryFrameSource",
27 "BackToBackBeginFrameSource");
28 DCHECK(!scheduler->primary_frame_source_internal_);
29 scheduler->primary_frame_source_internal_ =
30 BackToBackBeginFrameSource::Create(scheduler->task_runner_.get());
31 return scheduler->primary_frame_source_internal_.get();
32 } else if (scheduler->settings_.use_external_begin_frame_source) {
33 TRACE_EVENT1("cc",
34 "Scheduler::Scheduler()",
35 "PrimaryFrameSource",
36 "ExternalBeginFrameSource");
37 DCHECK(scheduler->primary_frame_source_internal_)
38 << "Need external BeginFrameSource";
39 return scheduler->primary_frame_source_internal_.get();
40 } else {
41 TRACE_EVENT1("cc",
42 "Scheduler::Scheduler()",
43 "PrimaryFrameSource",
44 "SyntheticBeginFrameSource");
45 scoped_ptr<SyntheticBeginFrameSource> synthetic_source =
46 SyntheticBeginFrameSource::Create(scheduler->task_runner_.get(),
47 scheduler->Now(),
48 BeginFrameArgs::DefaultInterval());
50 DCHECK(!scheduler->vsync_observer_);
51 scheduler->vsync_observer_ = synthetic_source.get();
53 DCHECK(!scheduler->primary_frame_source_internal_);
54 scheduler->primary_frame_source_internal_ = synthetic_source.Pass();
55 return scheduler->primary_frame_source_internal_.get();
59 BeginFrameSource*
60 SchedulerFrameSourcesConstructor::ConstructBackgroundFrameSource(
61 Scheduler* scheduler) {
62 TRACE_EVENT1("cc",
63 "Scheduler::Scheduler()",
64 "BackgroundFrameSource",
65 "SyntheticBeginFrameSource");
66 DCHECK(!(scheduler->background_frame_source_internal_));
67 scheduler->background_frame_source_internal_ =
68 SyntheticBeginFrameSource::Create(
69 scheduler->task_runner_.get(), scheduler->Now(),
70 scheduler->settings_.background_frame_interval);
71 return scheduler->background_frame_source_internal_.get();
74 Scheduler::Scheduler(
75 SchedulerClient* client,
76 const SchedulerSettings& scheduler_settings,
77 int layer_tree_host_id,
78 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
79 base::PowerMonitor* power_monitor,
80 scoped_ptr<BeginFrameSource> external_begin_frame_source,
81 SchedulerFrameSourcesConstructor* frame_sources_constructor)
82 : frame_source_(),
83 primary_frame_source_(NULL),
84 background_frame_source_(NULL),
85 primary_frame_source_internal_(external_begin_frame_source.Pass()),
86 background_frame_source_internal_(),
87 vsync_observer_(NULL),
88 settings_(scheduler_settings),
89 client_(client),
90 layer_tree_host_id_(layer_tree_host_id),
91 task_runner_(task_runner),
92 power_monitor_(power_monitor),
93 begin_retro_frame_posted_(false),
94 state_machine_(scheduler_settings),
95 inside_process_scheduled_actions_(false),
96 inside_action_(SchedulerStateMachine::ACTION_NONE),
97 weak_factory_(this) {
98 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
99 "Scheduler::Scheduler",
100 "settings",
101 settings_.AsValue());
102 DCHECK(client_);
103 DCHECK(!state_machine_.BeginFrameNeeded());
105 begin_retro_frame_closure_ =
106 base::Bind(&Scheduler::BeginRetroFrame, weak_factory_.GetWeakPtr());
107 begin_impl_frame_deadline_closure_ = base::Bind(
108 &Scheduler::OnBeginImplFrameDeadline, weak_factory_.GetWeakPtr());
109 poll_for_draw_triggers_closure_ = base::Bind(
110 &Scheduler::PollForAnticipatedDrawTriggers, weak_factory_.GetWeakPtr());
111 advance_commit_state_closure_ = base::Bind(
112 &Scheduler::PollToAdvanceCommitState, weak_factory_.GetWeakPtr());
114 frame_source_ = BeginFrameSourceMultiplexer::Create();
115 frame_source_->AddObserver(this);
117 // Primary frame source
118 primary_frame_source_ =
119 frame_sources_constructor->ConstructPrimaryFrameSource(this);
120 frame_source_->AddSource(primary_frame_source_);
121 primary_frame_source_->SetClientReady();
123 // Background ticking frame source
124 background_frame_source_ =
125 frame_sources_constructor->ConstructBackgroundFrameSource(this);
126 frame_source_->AddSource(background_frame_source_);
128 SetupPowerMonitoring();
131 Scheduler::~Scheduler() {
132 TeardownPowerMonitoring();
133 if (frame_source_->NeedsBeginFrames())
134 frame_source_->SetNeedsBeginFrames(false);
137 base::TimeTicks Scheduler::Now() const {
138 base::TimeTicks now = gfx::FrameTime::Now();
139 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.now"),
140 "Scheduler::Now",
141 "now",
142 now);
143 return now;
146 void Scheduler::SetupPowerMonitoring() {
147 if (settings_.disable_hi_res_timer_tasks_on_battery) {
148 DCHECK(power_monitor_);
149 power_monitor_->AddObserver(this);
150 state_machine_.SetImplLatencyTakesPriorityOnBattery(
151 power_monitor_->IsOnBatteryPower());
155 void Scheduler::TeardownPowerMonitoring() {
156 if (settings_.disable_hi_res_timer_tasks_on_battery) {
157 DCHECK(power_monitor_);
158 power_monitor_->RemoveObserver(this);
162 void Scheduler::OnPowerStateChange(bool on_battery_power) {
163 DCHECK(settings_.disable_hi_res_timer_tasks_on_battery);
164 state_machine_.SetImplLatencyTakesPriorityOnBattery(on_battery_power);
167 void Scheduler::CommitVSyncParameters(base::TimeTicks timebase,
168 base::TimeDelta interval) {
169 // TODO(brianderson): We should not be receiving 0 intervals.
170 if (interval == base::TimeDelta())
171 interval = BeginFrameArgs::DefaultInterval();
173 if (vsync_observer_)
174 vsync_observer_->OnUpdateVSyncParameters(timebase, interval);
177 void Scheduler::SetEstimatedParentDrawTime(base::TimeDelta draw_time) {
178 DCHECK_GE(draw_time.ToInternalValue(), 0);
179 estimated_parent_draw_time_ = draw_time;
182 void Scheduler::SetCanStart() {
183 state_machine_.SetCanStart();
184 ProcessScheduledActions();
187 void Scheduler::SetVisible(bool visible) {
188 state_machine_.SetVisible(visible);
189 if (visible) {
190 frame_source_->SetActiveSource(primary_frame_source_);
191 } else {
192 frame_source_->SetActiveSource(background_frame_source_);
194 ProcessScheduledActions();
197 void Scheduler::SetCanDraw(bool can_draw) {
198 state_machine_.SetCanDraw(can_draw);
199 ProcessScheduledActions();
202 void Scheduler::NotifyReadyToActivate() {
203 state_machine_.NotifyReadyToActivate();
204 ProcessScheduledActions();
207 void Scheduler::NotifyReadyToDraw() {
208 // Empty for now, until we take action based on the notification as part of
209 // crbugs 352894, 383157, 421923.
212 void Scheduler::SetNeedsCommit() {
213 state_machine_.SetNeedsCommit();
214 ProcessScheduledActions();
217 void Scheduler::SetNeedsRedraw() {
218 state_machine_.SetNeedsRedraw();
219 ProcessScheduledActions();
222 void Scheduler::SetNeedsAnimate() {
223 state_machine_.SetNeedsAnimate();
224 ProcessScheduledActions();
227 void Scheduler::SetNeedsManageTiles() {
228 DCHECK(!IsInsideAction(SchedulerStateMachine::ACTION_MANAGE_TILES));
229 state_machine_.SetNeedsManageTiles();
230 ProcessScheduledActions();
233 void Scheduler::SetMaxSwapsPending(int max) {
234 state_machine_.SetMaxSwapsPending(max);
237 void Scheduler::DidSwapBuffers() {
238 state_machine_.DidSwapBuffers();
240 // There is no need to call ProcessScheduledActions here because
241 // swapping should not trigger any new actions.
242 if (!inside_process_scheduled_actions_) {
243 DCHECK_EQ(state_machine_.NextAction(), SchedulerStateMachine::ACTION_NONE);
247 void Scheduler::DidSwapBuffersComplete() {
248 state_machine_.DidSwapBuffersComplete();
249 ProcessScheduledActions();
252 void Scheduler::SetImplLatencyTakesPriority(bool impl_latency_takes_priority) {
253 state_machine_.SetImplLatencyTakesPriority(impl_latency_takes_priority);
254 ProcessScheduledActions();
257 void Scheduler::NotifyReadyToCommit() {
258 TRACE_EVENT0("cc", "Scheduler::NotifyReadyToCommit");
259 state_machine_.NotifyReadyToCommit();
260 ProcessScheduledActions();
263 void Scheduler::BeginMainFrameAborted(bool did_handle) {
264 TRACE_EVENT0("cc", "Scheduler::BeginMainFrameAborted");
265 state_machine_.BeginMainFrameAborted(did_handle);
266 ProcessScheduledActions();
269 void Scheduler::DidManageTiles() {
270 state_machine_.DidManageTiles();
273 void Scheduler::DidLoseOutputSurface() {
274 TRACE_EVENT0("cc", "Scheduler::DidLoseOutputSurface");
275 state_machine_.DidLoseOutputSurface();
276 if (frame_source_->NeedsBeginFrames())
277 frame_source_->SetNeedsBeginFrames(false);
278 begin_retro_frame_args_.clear();
279 ProcessScheduledActions();
282 void Scheduler::DidCreateAndInitializeOutputSurface() {
283 TRACE_EVENT0("cc", "Scheduler::DidCreateAndInitializeOutputSurface");
284 DCHECK(!frame_source_->NeedsBeginFrames());
285 DCHECK(begin_impl_frame_deadline_task_.IsCancelled());
286 state_machine_.DidCreateAndInitializeOutputSurface();
287 ProcessScheduledActions();
290 void Scheduler::NotifyBeginMainFrameStarted() {
291 TRACE_EVENT0("cc", "Scheduler::NotifyBeginMainFrameStarted");
292 state_machine_.NotifyBeginMainFrameStarted();
295 base::TimeTicks Scheduler::AnticipatedDrawTime() const {
296 if (!frame_source_->NeedsBeginFrames() ||
297 begin_impl_frame_args_.interval <= base::TimeDelta())
298 return base::TimeTicks();
300 base::TimeTicks now = Now();
301 base::TimeTicks timebase = std::max(begin_impl_frame_args_.frame_time,
302 begin_impl_frame_args_.deadline);
303 int64 intervals = 1 + ((now - timebase) / begin_impl_frame_args_.interval);
304 return timebase + (begin_impl_frame_args_.interval * intervals);
307 base::TimeTicks Scheduler::LastBeginImplFrameTime() {
308 return begin_impl_frame_args_.frame_time;
311 void Scheduler::SetupNextBeginFrameIfNeeded() {
312 if (!task_runner_.get())
313 return;
315 bool needs_begin_frame = state_machine_.BeginFrameNeeded();
317 bool at_end_of_deadline =
318 (state_machine_.begin_impl_frame_state() ==
319 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE);
321 bool should_call_set_needs_begin_frame =
322 // Always request the BeginFrame immediately if it wasn't needed before.
323 (needs_begin_frame && !frame_source_->NeedsBeginFrames()) ||
324 // Only stop requesting BeginFrames after a deadline.
325 (!needs_begin_frame && frame_source_->NeedsBeginFrames() &&
326 at_end_of_deadline);
328 if (should_call_set_needs_begin_frame) {
329 frame_source_->SetNeedsBeginFrames(needs_begin_frame);
332 if (at_end_of_deadline) {
333 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
336 PostBeginRetroFrameIfNeeded();
337 SetupPollingMechanisms(needs_begin_frame);
340 // We may need to poll when we can't rely on BeginFrame to advance certain
341 // state or to avoid deadlock.
342 void Scheduler::SetupPollingMechanisms(bool needs_begin_frame) {
343 bool needs_advance_commit_state_timer = false;
344 // Setup PollForAnticipatedDrawTriggers if we need to monitor state but
345 // aren't expecting any more BeginFrames. This should only be needed by
346 // the synchronous compositor when BeginFrameNeeded is false.
347 if (state_machine_.ShouldPollForAnticipatedDrawTriggers()) {
348 DCHECK(!state_machine_.SupportsProactiveBeginFrame());
349 DCHECK(!needs_begin_frame);
350 if (poll_for_draw_triggers_task_.IsCancelled()) {
351 poll_for_draw_triggers_task_.Reset(poll_for_draw_triggers_closure_);
352 base::TimeDelta delay = begin_impl_frame_args_.IsValid()
353 ? begin_impl_frame_args_.interval
354 : BeginFrameArgs::DefaultInterval();
355 task_runner_->PostDelayedTask(
356 FROM_HERE, poll_for_draw_triggers_task_.callback(), delay);
358 } else {
359 poll_for_draw_triggers_task_.Cancel();
361 // At this point we'd prefer to advance through the commit flow by
362 // drawing a frame, however it's possible that the frame rate controller
363 // will not give us a BeginFrame until the commit completes. See
364 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
365 // we set a repeating timer to poll on ProcessScheduledActions until we
366 // successfully reach BeginFrame. Synchronous compositor does not use
367 // frame rate controller or have the circular wait in the bug.
368 if (IsBeginMainFrameSentOrStarted() &&
369 !settings_.using_synchronous_renderer_compositor) {
370 needs_advance_commit_state_timer = true;
374 if (needs_advance_commit_state_timer) {
375 if (advance_commit_state_task_.IsCancelled() &&
376 begin_impl_frame_args_.IsValid()) {
377 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
378 // set the interval to twice the interval from the previous frame.
379 advance_commit_state_task_.Reset(advance_commit_state_closure_);
380 task_runner_->PostDelayedTask(FROM_HERE,
381 advance_commit_state_task_.callback(),
382 begin_impl_frame_args_.interval * 2);
384 } else {
385 advance_commit_state_task_.Cancel();
389 // BeginFrame is the mechanism that tells us that now is a good time to start
390 // making a frame. Usually this means that user input for the frame is complete.
391 // If the scheduler is busy, we queue the BeginFrame to be handled later as
392 // a BeginRetroFrame.
393 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs& args) {
394 TRACE_EVENT1("cc", "Scheduler::BeginFrame", "args", args.AsValue());
396 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
397 // sent us the last BeginFrame we have missed. As we might not be able to
398 // actually make rendering for this call, handle it like a "retro frame".
399 // TODO(brainderson): Add a test for this functionality ASAP!
400 if (args.type == BeginFrameArgs::MISSED) {
401 begin_retro_frame_args_.push_back(args);
402 PostBeginRetroFrameIfNeeded();
403 return true;
406 BeginFrameArgs adjusted_args(args);
407 adjusted_args.deadline -= EstimatedParentDrawTime();
409 bool should_defer_begin_frame;
410 if (settings_.using_synchronous_renderer_compositor) {
411 should_defer_begin_frame = false;
412 } else {
413 should_defer_begin_frame =
414 !begin_retro_frame_args_.empty() || begin_retro_frame_posted_ ||
415 !frame_source_->NeedsBeginFrames() ||
416 (state_machine_.begin_impl_frame_state() !=
417 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
420 if (should_defer_begin_frame) {
421 begin_retro_frame_args_.push_back(adjusted_args);
422 TRACE_EVENT_INSTANT0(
423 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD);
424 // Queuing the frame counts as "using it", so we need to return true.
425 } else {
426 BeginImplFrame(adjusted_args);
428 return true;
431 // BeginRetroFrame is called for BeginFrames that we've deferred because
432 // the scheduler was in the middle of processing a previous BeginFrame.
433 void Scheduler::BeginRetroFrame() {
434 TRACE_EVENT0("cc", "Scheduler::BeginRetroFrame");
435 DCHECK(!settings_.using_synchronous_renderer_compositor);
436 DCHECK(begin_retro_frame_posted_);
437 begin_retro_frame_posted_ = false;
439 // If there aren't any retroactive BeginFrames, then we've lost the
440 // OutputSurface and should abort.
441 if (begin_retro_frame_args_.empty())
442 return;
444 // Discard expired BeginRetroFrames
445 // Today, we should always end up with at most one un-expired BeginRetroFrame
446 // because deadlines will not be greater than the next frame time. We don't
447 // DCHECK though because some systems don't always have monotonic timestamps.
448 // TODO(brianderson): In the future, long deadlines could result in us not
449 // draining the queue if we don't catch up. If we consistently can't catch
450 // up, our fallback should be to lower our frame rate.
451 base::TimeTicks now = Now();
452 base::TimeDelta draw_duration_estimate = client_->DrawDurationEstimate();
453 while (!begin_retro_frame_args_.empty()) {
454 base::TimeTicks adjusted_deadline = AdjustedBeginImplFrameDeadline(
455 begin_retro_frame_args_.front(), draw_duration_estimate);
456 if (now <= adjusted_deadline)
457 break;
459 TRACE_EVENT_INSTANT2("cc",
460 "Scheduler::BeginRetroFrame discarding",
461 TRACE_EVENT_SCOPE_THREAD,
462 "deadline - now",
463 (adjusted_deadline - now).InMicroseconds(),
464 "BeginFrameArgs",
465 begin_retro_frame_args_.front().AsValue());
466 begin_retro_frame_args_.pop_front();
467 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
470 if (begin_retro_frame_args_.empty()) {
471 TRACE_EVENT_INSTANT0("cc",
472 "Scheduler::BeginRetroFrames all expired",
473 TRACE_EVENT_SCOPE_THREAD);
474 } else {
475 BeginFrameArgs front = begin_retro_frame_args_.front();
476 begin_retro_frame_args_.pop_front();
477 BeginImplFrame(front);
481 // There could be a race between the posted BeginRetroFrame and a new
482 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
483 // will check if there is a pending BeginRetroFrame to ensure we handle
484 // BeginFrames in FIFO order.
485 void Scheduler::PostBeginRetroFrameIfNeeded() {
486 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
487 "Scheduler::PostBeginRetroFrameIfNeeded",
488 "state",
489 AsValue());
490 if (!frame_source_->NeedsBeginFrames())
491 return;
493 if (begin_retro_frame_args_.empty() || begin_retro_frame_posted_)
494 return;
496 // begin_retro_frame_args_ should always be empty for the
497 // synchronous compositor.
498 DCHECK(!settings_.using_synchronous_renderer_compositor);
500 if (state_machine_.begin_impl_frame_state() !=
501 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE)
502 return;
504 begin_retro_frame_posted_ = true;
505 task_runner_->PostTask(FROM_HERE, begin_retro_frame_closure_);
508 // BeginImplFrame starts a compositor frame that will wait up until a deadline
509 // for a BeginMainFrame+activation to complete before it times out and draws
510 // any asynchronous animation and scroll/pinch updates.
511 void Scheduler::BeginImplFrame(const BeginFrameArgs& args) {
512 bool main_thread_is_in_high_latency_mode =
513 state_machine_.MainThreadIsInHighLatencyMode();
514 TRACE_EVENT2("cc",
515 "Scheduler::BeginImplFrame",
516 "args",
517 args.AsValue(),
518 "main_thread_is_high_latency",
519 main_thread_is_in_high_latency_mode);
520 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
521 "MainThreadLatency",
522 main_thread_is_in_high_latency_mode);
523 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
524 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
525 DCHECK(state_machine_.HasInitializedOutputSurface());
527 advance_commit_state_task_.Cancel();
529 base::TimeDelta draw_duration_estimate = client_->DrawDurationEstimate();
530 begin_impl_frame_args_ = args;
531 begin_impl_frame_args_.deadline -= draw_duration_estimate;
533 if (!state_machine_.impl_latency_takes_priority() &&
534 main_thread_is_in_high_latency_mode &&
535 CanCommitAndActivateBeforeDeadline()) {
536 state_machine_.SetSkipNextBeginMainFrameToReduceLatency();
539 client_->WillBeginImplFrame(begin_impl_frame_args_);
540 state_machine_.OnBeginImplFrame(begin_impl_frame_args_);
541 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_);
543 ProcessScheduledActions();
545 state_machine_.OnBeginImplFrameDeadlinePending();
546 ScheduleBeginImplFrameDeadline(
547 AdjustedBeginImplFrameDeadline(args, draw_duration_estimate));
550 base::TimeTicks Scheduler::AdjustedBeginImplFrameDeadline(
551 const BeginFrameArgs& args,
552 base::TimeDelta draw_duration_estimate) const {
553 if (settings_.using_synchronous_renderer_compositor) {
554 // The synchronous compositor needs to draw right away.
555 return base::TimeTicks();
556 } else if (state_machine_.ShouldTriggerBeginImplFrameDeadlineEarly()) {
557 // We are ready to draw a new active tree immediately.
558 return base::TimeTicks();
559 } else if (state_machine_.needs_redraw()) {
560 // We have an animation or fast input path on the impl thread that wants
561 // to draw, so don't wait too long for a new active tree.
562 return args.deadline - draw_duration_estimate;
563 } else {
564 // The impl thread doesn't have anything it wants to draw and we are just
565 // waiting for a new active tree, so post the deadline for the next
566 // expected BeginImplFrame start. This allows us to draw immediately when
567 // there is a new active tree, instead of waiting for the next
568 // BeginImplFrame.
569 // TODO(brianderson): Handle long deadlines (that are past the next frame's
570 // frame time) properly instead of using this hack.
571 return args.frame_time + args.interval;
575 void Scheduler::ScheduleBeginImplFrameDeadline(base::TimeTicks deadline) {
576 TRACE_EVENT1(
577 "cc", "Scheduler::ScheduleBeginImplFrameDeadline", "deadline", deadline);
578 if (settings_.using_synchronous_renderer_compositor) {
579 // The synchronous renderer compositor has to make its GL calls
580 // within this call.
581 // TODO(brianderson): Have the OutputSurface initiate the deadline tasks
582 // so the sychronous renderer compositor can take advantage of splitting
583 // up the BeginImplFrame and deadline as well.
584 OnBeginImplFrameDeadline();
585 return;
587 begin_impl_frame_deadline_task_.Cancel();
588 begin_impl_frame_deadline_task_.Reset(begin_impl_frame_deadline_closure_);
590 base::TimeDelta delta = deadline - Now();
591 if (delta <= base::TimeDelta())
592 delta = base::TimeDelta();
593 task_runner_->PostDelayedTask(
594 FROM_HERE, begin_impl_frame_deadline_task_.callback(), delta);
597 void Scheduler::OnBeginImplFrameDeadline() {
598 TRACE_EVENT0("cc", "Scheduler::OnBeginImplFrameDeadline");
599 begin_impl_frame_deadline_task_.Cancel();
601 // We split the deadline actions up into two phases so the state machine
602 // has a chance to trigger actions that should occur durring and after
603 // the deadline separately. For example:
604 // * Sending the BeginMainFrame will not occur after the deadline in
605 // order to wait for more user-input before starting the next commit.
606 // * Creating a new OuputSurface will not occur during the deadline in
607 // order to allow the state machine to "settle" first.
608 state_machine_.OnBeginImplFrameDeadline();
609 ProcessScheduledActions();
610 state_machine_.OnBeginImplFrameIdle();
611 ProcessScheduledActions();
613 client_->DidBeginImplFrameDeadline();
616 void Scheduler::PollForAnticipatedDrawTriggers() {
617 TRACE_EVENT0("cc", "Scheduler::PollForAnticipatedDrawTriggers");
618 poll_for_draw_triggers_task_.Cancel();
619 state_machine_.DidEnterPollForAnticipatedDrawTriggers();
620 ProcessScheduledActions();
621 state_machine_.DidLeavePollForAnticipatedDrawTriggers();
624 void Scheduler::PollToAdvanceCommitState() {
625 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
626 advance_commit_state_task_.Cancel();
627 ProcessScheduledActions();
630 void Scheduler::DrawAndSwapIfPossible() {
631 DrawResult result = client_->ScheduledActionDrawAndSwapIfPossible();
632 state_machine_.DidDrawIfPossibleCompleted(result);
635 void Scheduler::ProcessScheduledActions() {
636 // We do not allow ProcessScheduledActions to be recursive.
637 // The top-level call will iteratively execute the next action for us anyway.
638 if (inside_process_scheduled_actions_)
639 return;
641 base::AutoReset<bool> mark_inside(&inside_process_scheduled_actions_, true);
643 SchedulerStateMachine::Action action;
644 do {
645 action = state_machine_.NextAction();
646 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
647 "SchedulerStateMachine",
648 "state",
649 AsValue());
650 VLOG(2) << "Scheduler::ProcessScheduledActions: "
651 << SchedulerStateMachine::ActionToString(action) << " "
652 << state_machine_.GetStatesForDebugging();
653 state_machine_.UpdateState(action);
654 base::AutoReset<SchedulerStateMachine::Action>
655 mark_inside_action(&inside_action_, action);
656 switch (action) {
657 case SchedulerStateMachine::ACTION_NONE:
658 break;
659 case SchedulerStateMachine::ACTION_ANIMATE:
660 client_->ScheduledActionAnimate();
661 break;
662 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME:
663 client_->ScheduledActionSendBeginMainFrame();
664 break;
665 case SchedulerStateMachine::ACTION_COMMIT:
666 client_->ScheduledActionCommit();
667 break;
668 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE:
669 client_->ScheduledActionActivateSyncTree();
670 break;
671 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE:
672 DrawAndSwapIfPossible();
673 break;
674 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED:
675 client_->ScheduledActionDrawAndSwapForced();
676 break;
677 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT:
678 // No action is actually performed, but this allows the state machine to
679 // advance out of its waiting to draw state without actually drawing.
680 break;
681 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION:
682 client_->ScheduledActionBeginOutputSurfaceCreation();
683 break;
684 case SchedulerStateMachine::ACTION_MANAGE_TILES:
685 client_->ScheduledActionManageTiles();
686 break;
688 } while (action != SchedulerStateMachine::ACTION_NONE);
690 SetupNextBeginFrameIfNeeded();
691 client_->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
693 if (state_machine_.ShouldTriggerBeginImplFrameDeadlineEarly()) {
694 DCHECK(!settings_.using_synchronous_renderer_compositor);
695 ScheduleBeginImplFrameDeadline(base::TimeTicks());
699 bool Scheduler::WillDrawIfNeeded() const {
700 return !state_machine_.PendingDrawsShouldBeAborted();
703 scoped_refptr<base::debug::ConvertableToTraceFormat> Scheduler::AsValue()
704 const {
705 scoped_refptr<base::debug::TracedValue> state =
706 new base::debug::TracedValue();
707 AsValueInto(state.get());
708 return state;
711 void Scheduler::AsValueInto(base::debug::TracedValue* state) const {
712 state->BeginDictionary("state_machine");
713 state_machine_.AsValueInto(state, Now());
714 state->EndDictionary();
716 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
717 bool frame_tracing_enabled = false;
718 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
719 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
720 &frame_tracing_enabled);
721 if (frame_tracing_enabled) {
722 state->BeginDictionary("frame_source_");
723 frame_source_->AsValueInto(state);
724 state->EndDictionary();
727 state->BeginDictionary("scheduler_state");
728 state->SetDouble("time_until_anticipated_draw_time_ms",
729 (AnticipatedDrawTime() - Now()).InMillisecondsF());
730 state->SetDouble("estimated_parent_draw_time_ms",
731 estimated_parent_draw_time_.InMillisecondsF());
732 state->SetBoolean("last_set_needs_begin_frame_",
733 frame_source_->NeedsBeginFrames());
734 state->SetBoolean("begin_retro_frame_posted_", begin_retro_frame_posted_);
735 state->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_.size());
736 state->SetBoolean("begin_impl_frame_deadline_task_",
737 !begin_impl_frame_deadline_task_.IsCancelled());
738 state->SetBoolean("poll_for_draw_triggers_task_",
739 !poll_for_draw_triggers_task_.IsCancelled());
740 state->SetBoolean("advance_commit_state_task_",
741 !advance_commit_state_task_.IsCancelled());
742 state->BeginDictionary("begin_impl_frame_args");
743 begin_impl_frame_args_.AsValueInto(state);
744 state->EndDictionary();
746 state->EndDictionary();
748 state->BeginDictionary("client_state");
749 state->SetDouble("draw_duration_estimate_ms",
750 client_->DrawDurationEstimate().InMillisecondsF());
751 state->SetDouble(
752 "begin_main_frame_to_commit_duration_estimate_ms",
753 client_->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
754 state->SetDouble(
755 "commit_to_activate_duration_estimate_ms",
756 client_->CommitToActivateDurationEstimate().InMillisecondsF());
757 state->EndDictionary();
760 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
761 // Check if the main thread computation and commit can be finished before the
762 // impl thread's deadline.
763 base::TimeTicks estimated_draw_time =
764 begin_impl_frame_args_.frame_time +
765 client_->BeginMainFrameToCommitDurationEstimate() +
766 client_->CommitToActivateDurationEstimate();
768 TRACE_EVENT2(
769 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
770 "CanCommitAndActivateBeforeDeadline",
771 "time_left_after_drawing_ms",
772 (begin_impl_frame_args_.deadline - estimated_draw_time).InMillisecondsF(),
773 "state",
774 AsValue());
776 return estimated_draw_time < begin_impl_frame_args_.deadline;
779 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
780 return (state_machine_.commit_state() ==
781 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT ||
782 state_machine_.commit_state() ==
783 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED);
786 } // namespace cc