ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / cc / scheduler / scheduler.cc
blobba1af7328153c30fe9b571736f0cad981d9b00e9
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 base::PowerMonitor* power_monitor,
83 scoped_ptr<BeginFrameSource> external_begin_frame_source,
84 SchedulerFrameSourcesConstructor* frame_sources_constructor)
85 : frame_source_(),
86 primary_frame_source_(NULL),
87 background_frame_source_(NULL),
88 primary_frame_source_internal_(external_begin_frame_source.Pass()),
89 background_frame_source_internal_(),
90 vsync_observer_(NULL),
91 throttle_frame_production_(scheduler_settings.throttle_frame_production),
92 settings_(scheduler_settings),
93 client_(client),
94 layer_tree_host_id_(layer_tree_host_id),
95 task_runner_(task_runner),
96 power_monitor_(power_monitor),
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_);
136 SetupPowerMonitoring();
139 Scheduler::~Scheduler() {
140 TeardownPowerMonitoring();
141 if (frame_source_->NeedsBeginFrames())
142 frame_source_->SetNeedsBeginFrames(false);
145 base::TimeTicks Scheduler::Now() const {
146 base::TimeTicks now = gfx::FrameTime::Now();
147 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.now"),
148 "Scheduler::Now",
149 "now",
150 now);
151 return now;
154 void Scheduler::SetupPowerMonitoring() {
155 if (settings_.disable_hi_res_timer_tasks_on_battery) {
156 DCHECK(power_monitor_);
157 power_monitor_->AddObserver(this);
158 state_machine_.SetImplLatencyTakesPriorityOnBattery(
159 power_monitor_->IsOnBatteryPower());
163 void Scheduler::TeardownPowerMonitoring() {
164 if (settings_.disable_hi_res_timer_tasks_on_battery) {
165 DCHECK(power_monitor_);
166 power_monitor_->RemoveObserver(this);
170 void Scheduler::OnPowerStateChange(bool on_battery_power) {
171 DCHECK(settings_.disable_hi_res_timer_tasks_on_battery);
172 state_machine_.SetImplLatencyTakesPriorityOnBattery(on_battery_power);
175 void Scheduler::CommitVSyncParameters(base::TimeTicks timebase,
176 base::TimeDelta interval) {
177 // TODO(brianderson): We should not be receiving 0 intervals.
178 if (interval == base::TimeDelta())
179 interval = BeginFrameArgs::DefaultInterval();
181 if (vsync_observer_)
182 vsync_observer_->OnUpdateVSyncParameters(timebase, interval);
185 void Scheduler::SetEstimatedParentDrawTime(base::TimeDelta draw_time) {
186 DCHECK_GE(draw_time.ToInternalValue(), 0);
187 estimated_parent_draw_time_ = draw_time;
190 void Scheduler::SetCanStart() {
191 state_machine_.SetCanStart();
192 ProcessScheduledActions();
195 void Scheduler::UpdateActiveFrameSource() {
196 if (state_machine_.visible()) {
197 if (throttle_frame_production_) {
198 frame_source_->SetActiveSource(primary_frame_source_);
199 } else {
200 frame_source_->SetActiveSource(unthrottled_frame_source_);
202 } else {
203 frame_source_->SetActiveSource(background_frame_source_);
205 ProcessScheduledActions();
208 void Scheduler::SetVisible(bool visible) {
209 state_machine_.SetVisible(visible);
210 UpdateActiveFrameSource();
213 void Scheduler::SetCanDraw(bool can_draw) {
214 state_machine_.SetCanDraw(can_draw);
215 ProcessScheduledActions();
218 void Scheduler::NotifyReadyToActivate() {
219 state_machine_.NotifyReadyToActivate();
220 ProcessScheduledActions();
223 void Scheduler::NotifyReadyToDraw() {
224 // Empty for now, until we take action based on the notification as part of
225 // crbugs 352894, 383157, 421923.
228 void Scheduler::SetThrottleFrameProduction(bool throttle) {
229 throttle_frame_production_ = throttle;
230 UpdateActiveFrameSource();
233 void Scheduler::SetNeedsCommit() {
234 state_machine_.SetNeedsCommit();
235 ProcessScheduledActions();
238 void Scheduler::SetNeedsRedraw() {
239 state_machine_.SetNeedsRedraw();
240 ProcessScheduledActions();
243 void Scheduler::SetNeedsAnimate() {
244 state_machine_.SetNeedsAnimate();
245 ProcessScheduledActions();
248 void Scheduler::SetNeedsPrepareTiles() {
249 DCHECK(!IsInsideAction(SchedulerStateMachine::ACTION_PREPARE_TILES));
250 state_machine_.SetNeedsPrepareTiles();
251 ProcessScheduledActions();
254 void Scheduler::SetMaxSwapsPending(int max) {
255 state_machine_.SetMaxSwapsPending(max);
258 void Scheduler::DidSwapBuffers() {
259 state_machine_.DidSwapBuffers();
261 // There is no need to call ProcessScheduledActions here because
262 // swapping should not trigger any new actions.
263 if (!inside_process_scheduled_actions_) {
264 DCHECK_EQ(state_machine_.NextAction(), SchedulerStateMachine::ACTION_NONE);
268 void Scheduler::DidSwapBuffersComplete() {
269 state_machine_.DidSwapBuffersComplete();
270 ProcessScheduledActions();
273 void Scheduler::SetImplLatencyTakesPriority(bool impl_latency_takes_priority) {
274 state_machine_.SetImplLatencyTakesPriority(impl_latency_takes_priority);
275 ProcessScheduledActions();
278 void Scheduler::NotifyReadyToCommit() {
279 TRACE_EVENT0("cc", "Scheduler::NotifyReadyToCommit");
280 state_machine_.NotifyReadyToCommit();
281 ProcessScheduledActions();
284 void Scheduler::BeginMainFrameAborted(CommitEarlyOutReason reason) {
285 TRACE_EVENT1("cc", "Scheduler::BeginMainFrameAborted", "reason",
286 CommitEarlyOutReasonToString(reason));
287 state_machine_.BeginMainFrameAborted(reason);
288 ProcessScheduledActions();
291 void Scheduler::DidPrepareTiles() {
292 state_machine_.DidPrepareTiles();
295 void Scheduler::DidLoseOutputSurface() {
296 TRACE_EVENT0("cc", "Scheduler::DidLoseOutputSurface");
297 begin_retro_frame_args_.clear();
298 begin_retro_frame_task_.Cancel();
299 state_machine_.DidLoseOutputSurface();
300 ProcessScheduledActions();
303 void Scheduler::DidCreateAndInitializeOutputSurface() {
304 TRACE_EVENT0("cc", "Scheduler::DidCreateAndInitializeOutputSurface");
305 DCHECK(!frame_source_->NeedsBeginFrames());
306 DCHECK(begin_impl_frame_deadline_task_.IsCancelled());
307 state_machine_.DidCreateAndInitializeOutputSurface();
308 ProcessScheduledActions();
311 void Scheduler::NotifyBeginMainFrameStarted() {
312 TRACE_EVENT0("cc", "Scheduler::NotifyBeginMainFrameStarted");
313 state_machine_.NotifyBeginMainFrameStarted();
316 base::TimeTicks Scheduler::AnticipatedDrawTime() const {
317 if (!frame_source_->NeedsBeginFrames() ||
318 begin_impl_frame_args_.interval <= base::TimeDelta())
319 return base::TimeTicks();
321 base::TimeTicks now = Now();
322 base::TimeTicks timebase = std::max(begin_impl_frame_args_.frame_time,
323 begin_impl_frame_args_.deadline);
324 int64 intervals = 1 + ((now - timebase) / begin_impl_frame_args_.interval);
325 return timebase + (begin_impl_frame_args_.interval * intervals);
328 base::TimeTicks Scheduler::LastBeginImplFrameTime() {
329 return begin_impl_frame_args_.frame_time;
332 void Scheduler::SetupNextBeginFrameIfNeeded() {
333 if (!task_runner_.get())
334 return;
336 if (state_machine_.ShouldSetNeedsBeginFrames(
337 frame_source_->NeedsBeginFrames())) {
338 frame_source_->SetNeedsBeginFrames(state_machine_.BeginFrameNeeded());
339 if (!frame_source_->NeedsBeginFrames()) {
340 client_->SendBeginMainFrameNotExpectedSoon();
344 if (state_machine_.begin_impl_frame_state() ==
345 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE) {
346 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
349 PostBeginRetroFrameIfNeeded();
350 SetupPollingMechanisms();
353 // We may need to poll when we can't rely on BeginFrame to advance certain
354 // state or to avoid deadlock.
355 void Scheduler::SetupPollingMechanisms() {
356 bool needs_advance_commit_state_timer = false;
357 // Setup PollForAnticipatedDrawTriggers if we need to monitor state but
358 // aren't expecting any more BeginFrames. This should only be needed by
359 // the synchronous compositor when BeginFrameNeeded is false.
360 if (state_machine_.ShouldPollForAnticipatedDrawTriggers()) {
361 DCHECK(!state_machine_.SupportsProactiveBeginFrame());
362 if (poll_for_draw_triggers_task_.IsCancelled()) {
363 poll_for_draw_triggers_task_.Reset(poll_for_draw_triggers_closure_);
364 base::TimeDelta delay = begin_impl_frame_args_.IsValid()
365 ? begin_impl_frame_args_.interval
366 : BeginFrameArgs::DefaultInterval();
367 task_runner_->PostDelayedTask(
368 FROM_HERE, poll_for_draw_triggers_task_.callback(), delay);
370 } else {
371 poll_for_draw_triggers_task_.Cancel();
373 // At this point we'd prefer to advance through the commit flow by
374 // drawing a frame, however it's possible that the frame rate controller
375 // will not give us a BeginFrame until the commit completes. See
376 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
377 // we set a repeating timer to poll on ProcessScheduledActions until we
378 // successfully reach BeginFrame. Synchronous compositor does not use
379 // frame rate controller or have the circular wait in the bug.
380 if (IsBeginMainFrameSentOrStarted() &&
381 !settings_.using_synchronous_renderer_compositor) {
382 needs_advance_commit_state_timer = true;
386 if (needs_advance_commit_state_timer) {
387 if (advance_commit_state_task_.IsCancelled() &&
388 begin_impl_frame_args_.IsValid()) {
389 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
390 // set the interval to twice the interval from the previous frame.
391 advance_commit_state_task_.Reset(advance_commit_state_closure_);
392 task_runner_->PostDelayedTask(FROM_HERE,
393 advance_commit_state_task_.callback(),
394 begin_impl_frame_args_.interval * 2);
396 } else {
397 advance_commit_state_task_.Cancel();
401 // BeginFrame is the mechanism that tells us that now is a good time to start
402 // making a frame. Usually this means that user input for the frame is complete.
403 // If the scheduler is busy, we queue the BeginFrame to be handled later as
404 // a BeginRetroFrame.
405 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs& args) {
406 TRACE_EVENT1("cc,benchmark", "Scheduler::BeginFrame", "args", args.AsValue());
408 // Deliver BeginFrames to children.
409 if (settings_.forward_begin_frames_to_children &&
410 state_machine_.children_need_begin_frames()) {
411 BeginFrameArgs adjusted_args_for_children(args);
412 // Adjust a deadline for child schedulers.
413 // TODO(simonhong): Once we have commitless update, we can get rid of
414 // BeginMainFrameToCommitDurationEstimate() +
415 // CommitToActivateDurationEstimate().
416 adjusted_args_for_children.deadline -=
417 (client_->BeginMainFrameToCommitDurationEstimate() +
418 client_->CommitToActivateDurationEstimate() +
419 client_->DrawDurationEstimate() + EstimatedParentDrawTime());
420 client_->SendBeginFramesToChildren(adjusted_args_for_children);
423 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
424 // sent us the last BeginFrame we have missed. As we might not be able to
425 // actually make rendering for this call, handle it like a "retro frame".
426 // TODO(brainderson): Add a test for this functionality ASAP!
427 if (args.type == BeginFrameArgs::MISSED) {
428 begin_retro_frame_args_.push_back(args);
429 PostBeginRetroFrameIfNeeded();
430 return true;
433 BeginFrameArgs adjusted_args(args);
434 adjusted_args.deadline -= EstimatedParentDrawTime();
436 bool should_defer_begin_frame;
437 if (settings_.using_synchronous_renderer_compositor) {
438 should_defer_begin_frame = false;
439 } else {
440 should_defer_begin_frame =
441 !begin_retro_frame_args_.empty() ||
442 !begin_retro_frame_task_.IsCancelled() ||
443 !frame_source_->NeedsBeginFrames() ||
444 (state_machine_.begin_impl_frame_state() !=
445 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
448 if (should_defer_begin_frame) {
449 begin_retro_frame_args_.push_back(adjusted_args);
450 TRACE_EVENT_INSTANT0(
451 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD);
452 // Queuing the frame counts as "using it", so we need to return true.
453 } else {
454 BeginImplFrame(adjusted_args);
456 return true;
459 void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
460 DCHECK(settings_.forward_begin_frames_to_children);
461 state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames);
462 ProcessScheduledActions();
465 // BeginRetroFrame is called for BeginFrames that we've deferred because
466 // the scheduler was in the middle of processing a previous BeginFrame.
467 void Scheduler::BeginRetroFrame() {
468 TRACE_EVENT0("cc,benchmark", "Scheduler::BeginRetroFrame");
469 DCHECK(!settings_.using_synchronous_renderer_compositor);
470 DCHECK(!begin_retro_frame_args_.empty());
471 DCHECK(!begin_retro_frame_task_.IsCancelled());
472 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
473 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
475 begin_retro_frame_task_.Cancel();
477 // Discard expired BeginRetroFrames
478 // Today, we should always end up with at most one un-expired BeginRetroFrame
479 // because deadlines will not be greater than the next frame time. We don't
480 // DCHECK though because some systems don't always have monotonic timestamps.
481 // TODO(brianderson): In the future, long deadlines could result in us not
482 // draining the queue if we don't catch up. If we consistently can't catch
483 // up, our fallback should be to lower our frame rate.
484 base::TimeTicks now = Now();
486 while (!begin_retro_frame_args_.empty()) {
487 const BeginFrameArgs& args = begin_retro_frame_args_.front();
488 base::TimeTicks expiration_time = args.frame_time + args.interval;
489 if (now <= expiration_time)
490 break;
491 TRACE_EVENT_INSTANT2(
492 "cc", "Scheduler::BeginRetroFrame discarding", TRACE_EVENT_SCOPE_THREAD,
493 "expiration_time - now", (expiration_time - now).InMillisecondsF(),
494 "BeginFrameArgs", begin_retro_frame_args_.front().AsValue());
495 begin_retro_frame_args_.pop_front();
496 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
499 if (begin_retro_frame_args_.empty()) {
500 TRACE_EVENT_INSTANT0("cc",
501 "Scheduler::BeginRetroFrames all expired",
502 TRACE_EVENT_SCOPE_THREAD);
503 } else {
504 BeginFrameArgs front = begin_retro_frame_args_.front();
505 begin_retro_frame_args_.pop_front();
506 BeginImplFrame(front);
510 // There could be a race between the posted BeginRetroFrame and a new
511 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
512 // will check if there is a pending BeginRetroFrame to ensure we handle
513 // BeginFrames in FIFO order.
514 void Scheduler::PostBeginRetroFrameIfNeeded() {
515 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
516 "Scheduler::PostBeginRetroFrameIfNeeded",
517 "state",
518 AsValue());
519 if (!frame_source_->NeedsBeginFrames())
520 return;
522 if (begin_retro_frame_args_.empty() || !begin_retro_frame_task_.IsCancelled())
523 return;
525 // begin_retro_frame_args_ should always be empty for the
526 // synchronous compositor.
527 DCHECK(!settings_.using_synchronous_renderer_compositor);
529 if (state_machine_.begin_impl_frame_state() !=
530 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE)
531 return;
533 begin_retro_frame_task_.Reset(begin_retro_frame_closure_);
535 task_runner_->PostTask(FROM_HERE, begin_retro_frame_task_.callback());
538 // BeginImplFrame starts a compositor frame that will wait up until a deadline
539 // for a BeginMainFrame+activation to complete before it times out and draws
540 // any asynchronous animation and scroll/pinch updates.
541 void Scheduler::BeginImplFrame(const BeginFrameArgs& args) {
542 bool main_thread_is_in_high_latency_mode =
543 state_machine_.MainThreadIsInHighLatencyMode();
544 TRACE_EVENT2("cc,benchmark",
545 "Scheduler::BeginImplFrame",
546 "args",
547 args.AsValue(),
548 "main_thread_is_high_latency",
549 main_thread_is_in_high_latency_mode);
550 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
551 "MainThreadLatency",
552 main_thread_is_in_high_latency_mode);
553 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
554 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
555 DCHECK(state_machine_.HasInitializedOutputSurface());
557 advance_commit_state_task_.Cancel();
559 begin_impl_frame_args_ = args;
560 begin_impl_frame_args_.deadline -= client_->DrawDurationEstimate();
562 if (!state_machine_.impl_latency_takes_priority() &&
563 main_thread_is_in_high_latency_mode &&
564 CanCommitAndActivateBeforeDeadline()) {
565 state_machine_.SetSkipNextBeginMainFrameToReduceLatency();
568 state_machine_.OnBeginImplFrame(begin_impl_frame_args_);
569 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_);
570 client_->WillBeginImplFrame(begin_impl_frame_args_);
572 ProcessScheduledActions();
574 state_machine_.OnBeginImplFrameDeadlinePending();
576 if (settings_.using_synchronous_renderer_compositor) {
577 // The synchronous renderer compositor has to make its GL calls
578 // within this call.
579 // TODO(brianderson): Have the OutputSurface initiate the deadline tasks
580 // so the synchronous renderer compositor can take advantage of splitting
581 // up the BeginImplFrame and deadline as well.
582 OnBeginImplFrameDeadline();
583 } else {
584 ScheduleBeginImplFrameDeadline();
588 void Scheduler::ScheduleBeginImplFrameDeadline() {
589 // The synchronous compositor does not post a deadline task.
590 DCHECK(!settings_.using_synchronous_renderer_compositor);
592 begin_impl_frame_deadline_task_.Cancel();
593 begin_impl_frame_deadline_task_.Reset(begin_impl_frame_deadline_closure_);
595 begin_impl_frame_deadline_mode_ =
596 state_machine_.CurrentBeginImplFrameDeadlineMode();
598 base::TimeTicks deadline;
599 switch (begin_impl_frame_deadline_mode_) {
600 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_IMMEDIATE:
601 // We are ready to draw a new active tree immediately.
602 // We don't use Now() here because it's somewhat expensive to call.
603 deadline = base::TimeTicks();
604 break;
605 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_REGULAR:
606 // We are animating on the impl thread but we can wait for some time.
607 deadline = begin_impl_frame_args_.deadline;
608 break;
609 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_LATE:
610 // We are blocked for one reason or another and we should wait.
611 // TODO(brianderson): Handle long deadlines (that are past the next
612 // frame's frame time) properly instead of using this hack.
613 deadline =
614 begin_impl_frame_args_.frame_time + begin_impl_frame_args_.interval;
615 break;
618 TRACE_EVENT1(
619 "cc", "Scheduler::ScheduleBeginImplFrameDeadline", "deadline", deadline);
621 base::TimeDelta delta = deadline - Now();
622 if (delta <= base::TimeDelta())
623 delta = base::TimeDelta();
624 task_runner_->PostDelayedTask(
625 FROM_HERE, begin_impl_frame_deadline_task_.callback(), delta);
628 void Scheduler::RescheduleBeginImplFrameDeadlineIfNeeded() {
629 if (settings_.using_synchronous_renderer_compositor)
630 return;
632 if (state_machine_.begin_impl_frame_state() !=
633 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME)
634 return;
636 if (begin_impl_frame_deadline_mode_ !=
637 state_machine_.CurrentBeginImplFrameDeadlineMode())
638 ScheduleBeginImplFrameDeadline();
641 void Scheduler::OnBeginImplFrameDeadline() {
642 TRACE_EVENT0("cc,benchmark", "Scheduler::OnBeginImplFrameDeadline");
643 begin_impl_frame_deadline_task_.Cancel();
644 // We split the deadline actions up into two phases so the state machine
645 // has a chance to trigger actions that should occur durring and after
646 // the deadline separately. For example:
647 // * Sending the BeginMainFrame will not occur after the deadline in
648 // order to wait for more user-input before starting the next commit.
649 // * Creating a new OuputSurface will not occur during the deadline in
650 // order to allow the state machine to "settle" first.
652 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
653 tracked_objects::ScopedTracker tracking_profile1(
654 FROM_HERE_WITH_EXPLICIT_FUNCTION(
655 "461509 Scheduler::OnBeginImplFrameDeadline1"));
656 state_machine_.OnBeginImplFrameDeadline();
657 ProcessScheduledActions();
659 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
660 tracked_objects::ScopedTracker tracking_profile2(
661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
662 "461509 Scheduler::OnBeginImplFrameDeadline2"));
663 state_machine_.OnBeginImplFrameIdle();
664 ProcessScheduledActions();
666 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
667 tracked_objects::ScopedTracker tracking_profile3(
668 FROM_HERE_WITH_EXPLICIT_FUNCTION(
669 "461509 Scheduler::OnBeginImplFrameDeadline3"));
670 client_->DidBeginImplFrameDeadline();
673 void Scheduler::PollForAnticipatedDrawTriggers() {
674 TRACE_EVENT0("cc", "Scheduler::PollForAnticipatedDrawTriggers");
675 poll_for_draw_triggers_task_.Cancel();
676 state_machine_.DidEnterPollForAnticipatedDrawTriggers();
677 ProcessScheduledActions();
678 state_machine_.DidLeavePollForAnticipatedDrawTriggers();
681 void Scheduler::PollToAdvanceCommitState() {
682 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
683 advance_commit_state_task_.Cancel();
684 ProcessScheduledActions();
687 void Scheduler::DrawAndSwapIfPossible() {
688 DrawResult result = client_->ScheduledActionDrawAndSwapIfPossible();
689 state_machine_.DidDrawIfPossibleCompleted(result);
692 void Scheduler::SetDeferCommits(bool defer_commits) {
693 TRACE_EVENT1("cc", "Scheduler::SetDeferCommits",
694 "defer_commits",
695 defer_commits);
696 state_machine_.SetDeferCommits(defer_commits);
697 ProcessScheduledActions();
700 void Scheduler::ProcessScheduledActions() {
701 // We do not allow ProcessScheduledActions to be recursive.
702 // The top-level call will iteratively execute the next action for us anyway.
703 if (inside_process_scheduled_actions_)
704 return;
706 base::AutoReset<bool> mark_inside(&inside_process_scheduled_actions_, true);
708 SchedulerStateMachine::Action action;
709 do {
710 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
711 tracked_objects::ScopedTracker tracking_profile1(
712 FROM_HERE_WITH_EXPLICIT_FUNCTION(
713 "461509 Scheduler::ProcessScheduledActions1"));
714 action = state_machine_.NextAction();
715 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
716 "SchedulerStateMachine",
717 "state",
718 AsValue());
719 VLOG(2) << "Scheduler::ProcessScheduledActions: "
720 << SchedulerStateMachine::ActionToString(action) << " "
721 << state_machine_.GetStatesForDebugging();
722 state_machine_.UpdateState(action);
723 base::AutoReset<SchedulerStateMachine::Action>
724 mark_inside_action(&inside_action_, action);
725 switch (action) {
726 case SchedulerStateMachine::ACTION_NONE:
727 break;
728 case SchedulerStateMachine::ACTION_ANIMATE: {
729 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
730 // fixed.
731 tracked_objects::ScopedTracker tracking_profile2(
732 FROM_HERE_WITH_EXPLICIT_FUNCTION(
733 "461509 Scheduler::ProcessScheduledActions2"));
734 client_->ScheduledActionAnimate();
735 break;
737 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME: {
738 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
739 // fixed.
740 tracked_objects::ScopedTracker tracking_profile3(
741 FROM_HERE_WITH_EXPLICIT_FUNCTION(
742 "461509 Scheduler::ProcessScheduledActions3"));
743 client_->ScheduledActionSendBeginMainFrame();
744 break;
746 case SchedulerStateMachine::ACTION_COMMIT: {
747 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
748 // fixed.
749 tracked_objects::ScopedTracker tracking_profile4(
750 FROM_HERE_WITH_EXPLICIT_FUNCTION(
751 "461509 Scheduler::ProcessScheduledActions4"));
752 client_->ScheduledActionCommit();
753 break;
755 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE: {
756 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
757 // fixed.
758 tracked_objects::ScopedTracker tracking_profile5(
759 FROM_HERE_WITH_EXPLICIT_FUNCTION(
760 "461509 Scheduler::ProcessScheduledActions5"));
761 client_->ScheduledActionActivateSyncTree();
762 break;
764 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE: {
765 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
766 // fixed.
767 tracked_objects::ScopedTracker tracking_profile6(
768 FROM_HERE_WITH_EXPLICIT_FUNCTION(
769 "461509 Scheduler::ProcessScheduledActions6"));
770 DrawAndSwapIfPossible();
771 break;
773 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED: {
774 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
775 // fixed.
776 tracked_objects::ScopedTracker tracking_profile7(
777 FROM_HERE_WITH_EXPLICIT_FUNCTION(
778 "461509 Scheduler::ProcessScheduledActions7"));
779 client_->ScheduledActionDrawAndSwapForced();
780 break;
782 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT:
783 // No action is actually performed, but this allows the state machine to
784 // advance out of its waiting to draw state without actually drawing.
785 break;
786 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION: {
787 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
788 // fixed.
789 tracked_objects::ScopedTracker tracking_profile8(
790 FROM_HERE_WITH_EXPLICIT_FUNCTION(
791 "461509 Scheduler::ProcessScheduledActions8"));
792 client_->ScheduledActionBeginOutputSurfaceCreation();
793 break;
795 case SchedulerStateMachine::ACTION_PREPARE_TILES: {
796 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
797 // fixed.
798 tracked_objects::ScopedTracker tracking_profile9(
799 FROM_HERE_WITH_EXPLICIT_FUNCTION(
800 "461509 Scheduler::ProcessScheduledActions9"));
801 client_->ScheduledActionPrepareTiles();
802 break;
805 } while (action != SchedulerStateMachine::ACTION_NONE);
807 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
808 tracked_objects::ScopedTracker tracking_profile10(
809 FROM_HERE_WITH_EXPLICIT_FUNCTION(
810 "461509 Scheduler::ProcessScheduledActions10"));
811 SetupNextBeginFrameIfNeeded();
812 client_->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
814 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
815 tracked_objects::ScopedTracker tracking_profile11(
816 FROM_HERE_WITH_EXPLICIT_FUNCTION(
817 "461509 Scheduler::ProcessScheduledActions11"));
818 RescheduleBeginImplFrameDeadlineIfNeeded();
821 scoped_refptr<base::trace_event::ConvertableToTraceFormat> Scheduler::AsValue()
822 const {
823 scoped_refptr<base::trace_event::TracedValue> state =
824 new base::trace_event::TracedValue();
825 AsValueInto(state.get());
826 return state;
829 void Scheduler::AsValueInto(base::trace_event::TracedValue* state) const {
830 state->BeginDictionary("state_machine");
831 state_machine_.AsValueInto(state, Now());
832 state->EndDictionary();
834 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
835 bool frame_tracing_enabled = false;
836 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
837 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
838 &frame_tracing_enabled);
839 if (frame_tracing_enabled) {
840 state->BeginDictionary("frame_source_");
841 frame_source_->AsValueInto(state);
842 state->EndDictionary();
845 state->BeginDictionary("scheduler_state");
846 state->SetDouble("time_until_anticipated_draw_time_ms",
847 (AnticipatedDrawTime() - Now()).InMillisecondsF());
848 state->SetDouble("estimated_parent_draw_time_ms",
849 estimated_parent_draw_time_.InMillisecondsF());
850 state->SetBoolean("last_set_needs_begin_frame_",
851 frame_source_->NeedsBeginFrames());
852 state->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_.size());
853 state->SetBoolean("begin_retro_frame_task_",
854 !begin_retro_frame_task_.IsCancelled());
855 state->SetBoolean("begin_impl_frame_deadline_task_",
856 !begin_impl_frame_deadline_task_.IsCancelled());
857 state->SetBoolean("poll_for_draw_triggers_task_",
858 !poll_for_draw_triggers_task_.IsCancelled());
859 state->SetBoolean("advance_commit_state_task_",
860 !advance_commit_state_task_.IsCancelled());
861 state->BeginDictionary("begin_impl_frame_args");
862 begin_impl_frame_args_.AsValueInto(state);
863 state->EndDictionary();
865 state->EndDictionary();
867 state->BeginDictionary("client_state");
868 state->SetDouble("draw_duration_estimate_ms",
869 client_->DrawDurationEstimate().InMillisecondsF());
870 state->SetDouble(
871 "begin_main_frame_to_commit_duration_estimate_ms",
872 client_->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
873 state->SetDouble(
874 "commit_to_activate_duration_estimate_ms",
875 client_->CommitToActivateDurationEstimate().InMillisecondsF());
876 state->EndDictionary();
879 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
880 // Check if the main thread computation and commit can be finished before the
881 // impl thread's deadline.
882 base::TimeTicks estimated_draw_time =
883 begin_impl_frame_args_.frame_time +
884 client_->BeginMainFrameToCommitDurationEstimate() +
885 client_->CommitToActivateDurationEstimate();
887 TRACE_EVENT2(
888 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
889 "CanCommitAndActivateBeforeDeadline",
890 "time_left_after_drawing_ms",
891 (begin_impl_frame_args_.deadline - estimated_draw_time).InMillisecondsF(),
892 "state",
893 AsValue());
895 return estimated_draw_time < begin_impl_frame_args_.deadline;
898 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
899 return (state_machine_.commit_state() ==
900 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT ||
901 state_machine_.commit_state() ==
902 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED);
905 } // namespace cc