[tracing] Expose memory-infra to Blink (chromium-side changes).
[chromium-blink-merge.git] / cc / scheduler / scheduler.cc
blobd2520335c0cd77a605b651ec633c04462f65828c
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::ConstructUnthrottledFrameSource(
53 Scheduler* scheduler) {
54 TRACE_EVENT1("cc", "Scheduler::Scheduler()", "UnthrottledFrameSource",
55 "BackToBackBeginFrameSource");
56 DCHECK(!scheduler->unthrottled_frame_source_internal_);
57 scheduler->unthrottled_frame_source_internal_ =
58 BackToBackBeginFrameSource::Create(scheduler->task_runner_.get());
59 return scheduler->unthrottled_frame_source_internal_.get();
62 Scheduler::Scheduler(
63 SchedulerClient* client,
64 const SchedulerSettings& scheduler_settings,
65 int layer_tree_host_id,
66 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
67 scoped_ptr<BeginFrameSource> external_begin_frame_source,
68 SchedulerFrameSourcesConstructor* frame_sources_constructor)
69 : frame_source_(),
70 primary_frame_source_(NULL),
71 primary_frame_source_internal_(external_begin_frame_source.Pass()),
72 vsync_observer_(NULL),
73 authoritative_vsync_interval_(base::TimeDelta()),
74 last_vsync_timebase_(base::TimeTicks()),
75 throttle_frame_production_(false),
76 settings_(scheduler_settings),
77 client_(client),
78 layer_tree_host_id_(layer_tree_host_id),
79 task_runner_(task_runner),
80 begin_impl_frame_deadline_mode_(
81 SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_NONE),
82 state_machine_(scheduler_settings),
83 inside_process_scheduled_actions_(false),
84 inside_action_(SchedulerStateMachine::ACTION_NONE),
85 weak_factory_(this) {
86 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
87 "Scheduler::Scheduler",
88 "settings",
89 settings_.AsValue());
90 DCHECK(client_);
91 DCHECK(!state_machine_.BeginFrameNeeded());
93 begin_retro_frame_closure_ =
94 base::Bind(&Scheduler::BeginRetroFrame, weak_factory_.GetWeakPtr());
95 begin_impl_frame_deadline_closure_ = base::Bind(
96 &Scheduler::OnBeginImplFrameDeadline, weak_factory_.GetWeakPtr());
97 advance_commit_state_closure_ = base::Bind(
98 &Scheduler::PollToAdvanceCommitState, weak_factory_.GetWeakPtr());
100 frame_source_ = BeginFrameSourceMultiplexer::Create();
101 frame_source_->AddObserver(this);
103 // Primary frame source
104 primary_frame_source_ =
105 frame_sources_constructor->ConstructPrimaryFrameSource(this);
106 frame_source_->AddSource(primary_frame_source_);
107 primary_frame_source_->SetClientReady();
109 // Unthrottled frame source
110 unthrottled_frame_source_ =
111 frame_sources_constructor->ConstructUnthrottledFrameSource(this);
112 frame_source_->AddSource(unthrottled_frame_source_);
114 SetThrottleFrameProduction(scheduler_settings.throttle_frame_production);
117 Scheduler::~Scheduler() {
118 if (frame_source_->NeedsBeginFrames())
119 frame_source_->SetNeedsBeginFrames(false);
120 frame_source_->SetActiveSource(nullptr);
123 base::TimeTicks Scheduler::Now() const {
124 base::TimeTicks now = gfx::FrameTime::Now();
125 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.now"),
126 "Scheduler::Now",
127 "now",
128 now);
129 return now;
132 void Scheduler::CommitVSyncParameters(base::TimeTicks timebase,
133 base::TimeDelta interval) {
134 if (authoritative_vsync_interval_ != base::TimeDelta()) {
135 interval = authoritative_vsync_interval_;
136 } else if (interval == base::TimeDelta()) {
137 // TODO(brianderson): We should not be receiving 0 intervals.
138 interval = BeginFrameArgs::DefaultInterval();
141 last_vsync_timebase_ = timebase;
143 if (vsync_observer_)
144 vsync_observer_->OnUpdateVSyncParameters(timebase, interval);
147 void Scheduler::SetEstimatedParentDrawTime(base::TimeDelta draw_time) {
148 DCHECK_GE(draw_time.ToInternalValue(), 0);
149 estimated_parent_draw_time_ = draw_time;
152 void Scheduler::SetCanStart() {
153 state_machine_.SetCanStart();
154 ProcessScheduledActions();
157 void Scheduler::SetVisible(bool visible) {
158 state_machine_.SetVisible(visible);
159 ProcessScheduledActions();
162 void Scheduler::SetCanDraw(bool can_draw) {
163 state_machine_.SetCanDraw(can_draw);
164 ProcessScheduledActions();
167 void Scheduler::NotifyReadyToActivate() {
168 state_machine_.NotifyReadyToActivate();
169 ProcessScheduledActions();
172 void Scheduler::NotifyReadyToDraw() {
173 // Future work might still needed for crbug.com/352894.
174 state_machine_.NotifyReadyToDraw();
175 ProcessScheduledActions();
178 void Scheduler::SetThrottleFrameProduction(bool throttle) {
179 throttle_frame_production_ = throttle;
180 if (throttle) {
181 frame_source_->SetActiveSource(primary_frame_source_);
182 } else {
183 frame_source_->SetActiveSource(unthrottled_frame_source_);
185 ProcessScheduledActions();
188 void Scheduler::SetNeedsCommit() {
189 state_machine_.SetNeedsCommit();
190 ProcessScheduledActions();
193 void Scheduler::SetNeedsRedraw() {
194 state_machine_.SetNeedsRedraw();
195 ProcessScheduledActions();
198 void Scheduler::SetNeedsAnimate() {
199 state_machine_.SetNeedsAnimate();
200 ProcessScheduledActions();
203 void Scheduler::SetNeedsPrepareTiles() {
204 DCHECK(!IsInsideAction(SchedulerStateMachine::ACTION_PREPARE_TILES));
205 state_machine_.SetNeedsPrepareTiles();
206 ProcessScheduledActions();
209 void Scheduler::SetWaitForReadyToDraw() {
210 state_machine_.SetWaitForReadyToDraw();
211 ProcessScheduledActions();
214 void Scheduler::SetMaxSwapsPending(int max) {
215 state_machine_.SetMaxSwapsPending(max);
218 void Scheduler::DidSwapBuffers() {
219 state_machine_.DidSwapBuffers();
221 // There is no need to call ProcessScheduledActions here because
222 // swapping should not trigger any new actions.
223 if (!inside_process_scheduled_actions_) {
224 DCHECK_EQ(state_machine_.NextAction(), SchedulerStateMachine::ACTION_NONE);
228 void Scheduler::DidSwapBuffersComplete() {
229 state_machine_.DidSwapBuffersComplete();
230 ProcessScheduledActions();
233 void Scheduler::SetImplLatencyTakesPriority(bool impl_latency_takes_priority) {
234 state_machine_.SetImplLatencyTakesPriority(impl_latency_takes_priority);
235 ProcessScheduledActions();
238 void Scheduler::NotifyReadyToCommit() {
239 TRACE_EVENT0("cc", "Scheduler::NotifyReadyToCommit");
240 state_machine_.NotifyReadyToCommit();
241 ProcessScheduledActions();
244 void Scheduler::BeginMainFrameAborted(CommitEarlyOutReason reason) {
245 TRACE_EVENT1("cc", "Scheduler::BeginMainFrameAborted", "reason",
246 CommitEarlyOutReasonToString(reason));
247 state_machine_.BeginMainFrameAborted(reason);
248 ProcessScheduledActions();
251 void Scheduler::DidPrepareTiles() {
252 state_machine_.DidPrepareTiles();
255 void Scheduler::DidLoseOutputSurface() {
256 TRACE_EVENT0("cc", "Scheduler::DidLoseOutputSurface");
257 begin_retro_frame_args_.clear();
258 begin_retro_frame_task_.Cancel();
259 state_machine_.DidLoseOutputSurface();
260 ProcessScheduledActions();
263 void Scheduler::DidCreateAndInitializeOutputSurface() {
264 TRACE_EVENT0("cc", "Scheduler::DidCreateAndInitializeOutputSurface");
265 DCHECK(!frame_source_->NeedsBeginFrames());
266 DCHECK(begin_impl_frame_deadline_task_.IsCancelled());
267 state_machine_.DidCreateAndInitializeOutputSurface();
268 ProcessScheduledActions();
271 void Scheduler::NotifyBeginMainFrameStarted() {
272 TRACE_EVENT0("cc", "Scheduler::NotifyBeginMainFrameStarted");
273 state_machine_.NotifyBeginMainFrameStarted();
276 base::TimeTicks Scheduler::AnticipatedDrawTime() const {
277 if (!frame_source_->NeedsBeginFrames() ||
278 begin_impl_frame_args_.interval <= base::TimeDelta())
279 return base::TimeTicks();
281 base::TimeTicks now = Now();
282 base::TimeTicks timebase = std::max(begin_impl_frame_args_.frame_time,
283 begin_impl_frame_args_.deadline);
284 int64 intervals = 1 + ((now - timebase) / begin_impl_frame_args_.interval);
285 return timebase + (begin_impl_frame_args_.interval * intervals);
288 base::TimeTicks Scheduler::LastBeginImplFrameTime() {
289 return begin_impl_frame_args_.frame_time;
292 void Scheduler::SetupNextBeginFrameIfNeeded() {
293 // Never call SetNeedsBeginFrames if the frame source already has the right
294 // value.
295 if (frame_source_->NeedsBeginFrames() != state_machine_.BeginFrameNeeded()) {
296 if (state_machine_.BeginFrameNeeded()) {
297 // Call SetNeedsBeginFrames(true) as soon as possible.
298 frame_source_->SetNeedsBeginFrames(true);
299 } else if (state_machine_.begin_impl_frame_state() ==
300 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE) {
301 // Call SetNeedsBeginFrames(false) in between frames only.
302 frame_source_->SetNeedsBeginFrames(false);
303 client_->SendBeginMainFrameNotExpectedSoon();
307 PostBeginRetroFrameIfNeeded();
310 // We may need to poll when we can't rely on BeginFrame to advance certain
311 // state or to avoid deadlock.
312 void Scheduler::SetupPollingMechanisms() {
313 // At this point we'd prefer to advance through the commit flow by
314 // drawing a frame, however it's possible that the frame rate controller
315 // will not give us a BeginFrame until the commit completes. See
316 // crbug.com/317430 for an example of a swap ack being held on commit. Thus
317 // we set a repeating timer to poll on ProcessScheduledActions until we
318 // successfully reach BeginFrame. Synchronous compositor does not use
319 // frame rate controller or have the circular wait in the bug.
320 if (IsBeginMainFrameSentOrStarted() &&
321 !settings_.using_synchronous_renderer_compositor) {
322 if (advance_commit_state_task_.IsCancelled() &&
323 begin_impl_frame_args_.IsValid()) {
324 // Since we'd rather get a BeginImplFrame by the normal mechanism, we
325 // set the interval to twice the interval from the previous frame.
326 advance_commit_state_task_.Reset(advance_commit_state_closure_);
327 task_runner_->PostDelayedTask(FROM_HERE,
328 advance_commit_state_task_.callback(),
329 begin_impl_frame_args_.interval * 2);
331 } else {
332 advance_commit_state_task_.Cancel();
336 // BeginFrame is the mechanism that tells us that now is a good time to start
337 // making a frame. Usually this means that user input for the frame is complete.
338 // If the scheduler is busy, we queue the BeginFrame to be handled later as
339 // a BeginRetroFrame.
340 bool Scheduler::OnBeginFrameMixInDelegate(const BeginFrameArgs& args) {
341 TRACE_EVENT1("cc,benchmark", "Scheduler::BeginFrame", "args", args.AsValue());
343 // TODO(brianderson): Adjust deadline in the DisplayScheduler.
344 BeginFrameArgs adjusted_args(args);
345 adjusted_args.deadline -= EstimatedParentDrawTime();
347 // Deliver BeginFrames to children.
348 // TODO(brianderson): Move this responsibility to the DisplayScheduler.
349 if (state_machine_.children_need_begin_frames())
350 client_->SendBeginFramesToChildren(adjusted_args);
352 if (settings_.using_synchronous_renderer_compositor) {
353 BeginImplFrameSynchronous(adjusted_args);
354 return true;
357 // We have just called SetNeedsBeginFrame(true) and the BeginFrameSource has
358 // sent us the last BeginFrame we have missed. As we might not be able to
359 // actually make rendering for this call, handle it like a "retro frame".
360 // TODO(brainderson): Add a test for this functionality ASAP!
361 if (adjusted_args.type == BeginFrameArgs::MISSED) {
362 begin_retro_frame_args_.push_back(adjusted_args);
363 PostBeginRetroFrameIfNeeded();
364 return true;
367 bool should_defer_begin_frame =
368 !begin_retro_frame_args_.empty() ||
369 !begin_retro_frame_task_.IsCancelled() ||
370 !frame_source_->NeedsBeginFrames() ||
371 (state_machine_.begin_impl_frame_state() !=
372 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
374 if (should_defer_begin_frame) {
375 begin_retro_frame_args_.push_back(adjusted_args);
376 TRACE_EVENT_INSTANT0(
377 "cc", "Scheduler::BeginFrame deferred", TRACE_EVENT_SCOPE_THREAD);
378 // Queuing the frame counts as "using it", so we need to return true.
379 } else {
380 BeginImplFrameWithDeadline(adjusted_args);
382 return true;
385 void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
386 state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames);
387 ProcessScheduledActions();
390 void Scheduler::SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) {
391 authoritative_vsync_interval_ = interval;
392 if (vsync_observer_)
393 vsync_observer_->OnUpdateVSyncParameters(last_vsync_timebase_, interval);
396 void Scheduler::SetVideoNeedsBeginFrames(bool video_needs_begin_frames) {
397 state_machine_.SetVideoNeedsBeginFrames(video_needs_begin_frames);
398 ProcessScheduledActions();
401 void Scheduler::OnDrawForOutputSurface() {
402 DCHECK(settings_.using_synchronous_renderer_compositor);
403 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
404 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
405 DCHECK(!BeginImplFrameDeadlinePending());
407 state_machine_.OnBeginImplFrameDeadline();
408 ProcessScheduledActions();
410 state_machine_.OnBeginImplFrameIdle();
411 ProcessScheduledActions();
414 // BeginRetroFrame is called for BeginFrames that we've deferred because
415 // the scheduler was in the middle of processing a previous BeginFrame.
416 void Scheduler::BeginRetroFrame() {
417 TRACE_EVENT0("cc,benchmark", "Scheduler::BeginRetroFrame");
418 DCHECK(!settings_.using_synchronous_renderer_compositor);
419 DCHECK(!begin_retro_frame_args_.empty());
420 DCHECK(!begin_retro_frame_task_.IsCancelled());
421 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
422 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
424 begin_retro_frame_task_.Cancel();
426 // Discard expired BeginRetroFrames
427 // Today, we should always end up with at most one un-expired BeginRetroFrame
428 // because deadlines will not be greater than the next frame time. We don't
429 // DCHECK though because some systems don't always have monotonic timestamps.
430 // TODO(brianderson): In the future, long deadlines could result in us not
431 // draining the queue if we don't catch up. If we consistently can't catch
432 // up, our fallback should be to lower our frame rate.
433 base::TimeTicks now = Now();
435 while (!begin_retro_frame_args_.empty()) {
436 const BeginFrameArgs& args = begin_retro_frame_args_.front();
437 base::TimeTicks expiration_time = args.frame_time + args.interval;
438 if (now <= expiration_time)
439 break;
440 TRACE_EVENT_INSTANT2(
441 "cc", "Scheduler::BeginRetroFrame discarding", TRACE_EVENT_SCOPE_THREAD,
442 "expiration_time - now", (expiration_time - now).InMillisecondsF(),
443 "BeginFrameArgs", begin_retro_frame_args_.front().AsValue());
444 begin_retro_frame_args_.pop_front();
445 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
448 if (begin_retro_frame_args_.empty()) {
449 TRACE_EVENT_INSTANT0("cc",
450 "Scheduler::BeginRetroFrames all expired",
451 TRACE_EVENT_SCOPE_THREAD);
452 } else {
453 BeginFrameArgs front = begin_retro_frame_args_.front();
454 begin_retro_frame_args_.pop_front();
455 BeginImplFrameWithDeadline(front);
459 // There could be a race between the posted BeginRetroFrame and a new
460 // BeginFrame arriving via the normal mechanism. Scheduler::BeginFrame
461 // will check if there is a pending BeginRetroFrame to ensure we handle
462 // BeginFrames in FIFO order.
463 void Scheduler::PostBeginRetroFrameIfNeeded() {
464 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
465 "Scheduler::PostBeginRetroFrameIfNeeded",
466 "state",
467 AsValue());
468 if (!frame_source_->NeedsBeginFrames())
469 return;
471 if (begin_retro_frame_args_.empty() || !begin_retro_frame_task_.IsCancelled())
472 return;
474 // begin_retro_frame_args_ should always be empty for the
475 // synchronous compositor.
476 DCHECK(!settings_.using_synchronous_renderer_compositor);
478 if (state_machine_.begin_impl_frame_state() !=
479 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE)
480 return;
482 begin_retro_frame_task_.Reset(begin_retro_frame_closure_);
484 task_runner_->PostTask(FROM_HERE, begin_retro_frame_task_.callback());
487 void Scheduler::BeginImplFrameWithDeadline(const BeginFrameArgs& args) {
488 bool main_thread_is_in_high_latency_mode =
489 state_machine_.MainThreadIsInHighLatencyMode();
490 TRACE_EVENT2("cc,benchmark", "Scheduler::BeginImplFrame", "args",
491 args.AsValue(), "main_thread_is_high_latency",
492 main_thread_is_in_high_latency_mode);
493 TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
494 "MainThreadLatency", main_thread_is_in_high_latency_mode);
496 advance_commit_state_task_.Cancel();
498 begin_impl_frame_args_ = args;
499 begin_impl_frame_args_.deadline -= client_->DrawDurationEstimate();
501 if (!state_machine_.impl_latency_takes_priority() &&
502 main_thread_is_in_high_latency_mode &&
503 CanCommitAndActivateBeforeDeadline()) {
504 state_machine_.SetSkipNextBeginMainFrameToReduceLatency();
507 BeginImplFrame();
509 // The deadline will be scheduled in ProcessScheduledActions.
510 state_machine_.OnBeginImplFrameDeadlinePending();
511 ProcessScheduledActions();
514 void Scheduler::BeginImplFrameSynchronous(const BeginFrameArgs& args) {
515 TRACE_EVENT1("cc,benchmark", "Scheduler::BeginImplFrame", "args",
516 args.AsValue());
517 begin_impl_frame_args_ = args;
518 BeginImplFrame();
519 FinishImplFrame();
522 void Scheduler::FinishImplFrame() {
523 state_machine_.OnBeginImplFrameIdle();
524 ProcessScheduledActions();
526 client_->DidFinishImplFrame();
527 frame_source_->DidFinishFrame(begin_retro_frame_args_.size());
530 // BeginImplFrame starts a compositor frame that will wait up until a deadline
531 // for a BeginMainFrame+activation to complete before it times out and draws
532 // any asynchronous animation and scroll/pinch updates.
533 void Scheduler::BeginImplFrame() {
534 DCHECK_EQ(state_machine_.begin_impl_frame_state(),
535 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE);
536 DCHECK(!BeginImplFrameDeadlinePending());
537 DCHECK(state_machine_.HasInitializedOutputSurface());
538 DCHECK(advance_commit_state_task_.IsCancelled());
540 state_machine_.OnBeginImplFrame();
541 devtools_instrumentation::DidBeginFrame(layer_tree_host_id_);
542 client_->WillBeginImplFrame(begin_impl_frame_args_);
544 ProcessScheduledActions();
547 void Scheduler::ScheduleBeginImplFrameDeadline() {
548 // The synchronous compositor does not post a deadline task.
549 DCHECK(!settings_.using_synchronous_renderer_compositor);
551 begin_impl_frame_deadline_task_.Cancel();
552 begin_impl_frame_deadline_task_.Reset(begin_impl_frame_deadline_closure_);
554 begin_impl_frame_deadline_mode_ =
555 state_machine_.CurrentBeginImplFrameDeadlineMode();
557 base::TimeTicks deadline;
558 switch (begin_impl_frame_deadline_mode_) {
559 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_NONE:
560 // No deadline.
561 return;
562 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_IMMEDIATE:
563 // We are ready to draw a new active tree immediately.
564 // We don't use Now() here because it's somewhat expensive to call.
565 deadline = base::TimeTicks();
566 break;
567 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_REGULAR:
568 // We are animating on the impl thread but we can wait for some time.
569 deadline = begin_impl_frame_args_.deadline;
570 break;
571 case SchedulerStateMachine::BEGIN_IMPL_FRAME_DEADLINE_MODE_LATE:
572 // We are blocked for one reason or another and we should wait.
573 // TODO(brianderson): Handle long deadlines (that are past the next
574 // frame's frame time) properly instead of using this hack.
575 deadline =
576 begin_impl_frame_args_.frame_time + begin_impl_frame_args_.interval;
577 break;
578 case SchedulerStateMachine::
579 BEGIN_IMPL_FRAME_DEADLINE_MODE_BLOCKED_ON_READY_TO_DRAW:
580 // We are blocked because we are waiting for ReadyToDraw signal. We would
581 // post deadline after we received ReadyToDraw singal.
582 TRACE_EVENT1("cc", "Scheduler::ScheduleBeginImplFrameDeadline",
583 "deadline_mode", "blocked_on_ready_to_draw");
584 return;
587 TRACE_EVENT2("cc", "Scheduler::ScheduleBeginImplFrameDeadline", "mode",
588 SchedulerStateMachine::BeginImplFrameDeadlineModeToString(
589 begin_impl_frame_deadline_mode_),
590 "deadline", deadline);
592 base::TimeDelta delta = std::max(deadline - Now(), base::TimeDelta());
593 task_runner_->PostDelayedTask(
594 FROM_HERE, begin_impl_frame_deadline_task_.callback(), delta);
597 void Scheduler::ScheduleBeginImplFrameDeadlineIfNeeded() {
598 if (settings_.using_synchronous_renderer_compositor)
599 return;
601 if (state_machine_.begin_impl_frame_state() !=
602 SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME)
603 return;
605 if (begin_impl_frame_deadline_mode_ ==
606 state_machine_.CurrentBeginImplFrameDeadlineMode() &&
607 BeginImplFrameDeadlinePending())
608 return;
610 ScheduleBeginImplFrameDeadline();
613 void Scheduler::OnBeginImplFrameDeadline() {
614 TRACE_EVENT0("cc,benchmark", "Scheduler::OnBeginImplFrameDeadline");
615 begin_impl_frame_deadline_task_.Cancel();
616 // We split the deadline actions up into two phases so the state machine
617 // has a chance to trigger actions that should occur durring and after
618 // the deadline separately. For example:
619 // * Sending the BeginMainFrame will not occur after the deadline in
620 // order to wait for more user-input before starting the next commit.
621 // * Creating a new OuputSurface will not occur during the deadline in
622 // order to allow the state machine to "settle" first.
624 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is fixed.
625 tracked_objects::ScopedTracker tracking_profile1(
626 FROM_HERE_WITH_EXPLICIT_FUNCTION(
627 "461509 Scheduler::OnBeginImplFrameDeadline1"));
628 state_machine_.OnBeginImplFrameDeadline();
629 ProcessScheduledActions();
630 FinishImplFrame();
634 void Scheduler::PollToAdvanceCommitState() {
635 TRACE_EVENT0("cc", "Scheduler::PollToAdvanceCommitState");
636 advance_commit_state_task_.Cancel();
637 ProcessScheduledActions();
640 void Scheduler::DrawAndSwapIfPossible() {
641 DrawResult result = client_->ScheduledActionDrawAndSwapIfPossible();
642 state_machine_.DidDrawIfPossibleCompleted(result);
645 void Scheduler::SetDeferCommits(bool defer_commits) {
646 TRACE_EVENT1("cc", "Scheduler::SetDeferCommits",
647 "defer_commits",
648 defer_commits);
649 state_machine_.SetDeferCommits(defer_commits);
650 ProcessScheduledActions();
653 void Scheduler::ProcessScheduledActions() {
654 // We do not allow ProcessScheduledActions to be recursive.
655 // The top-level call will iteratively execute the next action for us anyway.
656 if (inside_process_scheduled_actions_)
657 return;
659 base::AutoReset<bool> mark_inside(&inside_process_scheduled_actions_, true);
661 SchedulerStateMachine::Action action;
662 do {
663 action = state_machine_.NextAction();
664 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
665 "SchedulerStateMachine",
666 "state",
667 AsValue());
668 VLOG(2) << "Scheduler::ProcessScheduledActions: "
669 << SchedulerStateMachine::ActionToString(action) << " "
670 << state_machine_.GetStatesForDebugging();
671 state_machine_.UpdateState(action);
672 base::AutoReset<SchedulerStateMachine::Action>
673 mark_inside_action(&inside_action_, action);
674 switch (action) {
675 case SchedulerStateMachine::ACTION_NONE:
676 break;
677 case SchedulerStateMachine::ACTION_ANIMATE:
678 client_->ScheduledActionAnimate();
679 break;
680 case SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME:
681 client_->ScheduledActionSendBeginMainFrame();
682 break;
683 case SchedulerStateMachine::ACTION_COMMIT: {
684 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
685 // fixed.
686 tracked_objects::ScopedTracker tracking_profile4(
687 FROM_HERE_WITH_EXPLICIT_FUNCTION(
688 "461509 Scheduler::ProcessScheduledActions4"));
689 client_->ScheduledActionCommit();
690 break;
692 case SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE:
693 client_->ScheduledActionActivateSyncTree();
694 break;
695 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE: {
696 // TODO(robliao): Remove ScopedTracker below once crbug.com/461509 is
697 // fixed.
698 tracked_objects::ScopedTracker tracking_profile6(
699 FROM_HERE_WITH_EXPLICIT_FUNCTION(
700 "461509 Scheduler::ProcessScheduledActions6"));
701 DrawAndSwapIfPossible();
702 break;
704 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED:
705 client_->ScheduledActionDrawAndSwapForced();
706 break;
707 case SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT:
708 // No action is actually performed, but this allows the state machine to
709 // advance out of its waiting to draw state without actually drawing.
710 break;
711 case SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION:
712 client_->ScheduledActionBeginOutputSurfaceCreation();
713 break;
714 case SchedulerStateMachine::ACTION_PREPARE_TILES:
715 client_->ScheduledActionPrepareTiles();
716 break;
717 case SchedulerStateMachine::ACTION_INVALIDATE_OUTPUT_SURFACE: {
718 client_->ScheduledActionInvalidateOutputSurface();
719 break;
722 } while (action != SchedulerStateMachine::ACTION_NONE);
724 SetupPollingMechanisms();
726 client_->DidAnticipatedDrawTimeChange(AnticipatedDrawTime());
728 ScheduleBeginImplFrameDeadlineIfNeeded();
730 SetupNextBeginFrameIfNeeded();
733 scoped_refptr<base::trace_event::ConvertableToTraceFormat> Scheduler::AsValue()
734 const {
735 scoped_refptr<base::trace_event::TracedValue> state =
736 new base::trace_event::TracedValue();
737 AsValueInto(state.get());
738 return state;
741 void Scheduler::AsValueInto(base::trace_event::TracedValue* state) const {
742 state->BeginDictionary("state_machine");
743 state_machine_.AsValueInto(state);
744 state->EndDictionary();
746 // Only trace frame sources when explicitly enabled - http://crbug.com/420607
747 bool frame_tracing_enabled = false;
748 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
749 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
750 &frame_tracing_enabled);
751 if (frame_tracing_enabled) {
752 state->BeginDictionary("frame_source_");
753 frame_source_->AsValueInto(state);
754 state->EndDictionary();
757 state->BeginDictionary("scheduler_state");
758 state->SetDouble("time_until_anticipated_draw_time_ms",
759 (AnticipatedDrawTime() - Now()).InMillisecondsF());
760 state->SetDouble("estimated_parent_draw_time_ms",
761 estimated_parent_draw_time_.InMillisecondsF());
762 state->SetBoolean("last_set_needs_begin_frame_",
763 frame_source_->NeedsBeginFrames());
764 state->SetInteger("begin_retro_frame_args_", begin_retro_frame_args_.size());
765 state->SetBoolean("begin_retro_frame_task_",
766 !begin_retro_frame_task_.IsCancelled());
767 state->SetBoolean("begin_impl_frame_deadline_task_",
768 !begin_impl_frame_deadline_task_.IsCancelled());
769 state->SetBoolean("advance_commit_state_task_",
770 !advance_commit_state_task_.IsCancelled());
771 state->BeginDictionary("begin_impl_frame_args");
772 begin_impl_frame_args_.AsValueInto(state);
773 state->EndDictionary();
775 base::TimeTicks now = Now();
776 base::TimeTicks frame_time = begin_impl_frame_args_.frame_time;
777 base::TimeTicks deadline = begin_impl_frame_args_.deadline;
778 base::TimeDelta interval = begin_impl_frame_args_.interval;
779 state->BeginDictionary("major_timestamps_in_ms");
780 state->SetDouble("0_interval", interval.InMillisecondsF());
781 state->SetDouble("1_now_to_deadline", (deadline - now).InMillisecondsF());
782 state->SetDouble("2_frame_time_to_now", (now - frame_time).InMillisecondsF());
783 state->SetDouble("3_frame_time_to_deadline",
784 (deadline - frame_time).InMillisecondsF());
785 state->SetDouble("4_now", (now - base::TimeTicks()).InMillisecondsF());
786 state->SetDouble("5_frame_time",
787 (frame_time - base::TimeTicks()).InMillisecondsF());
788 state->SetDouble("6_deadline",
789 (deadline - base::TimeTicks()).InMillisecondsF());
790 state->EndDictionary();
792 state->EndDictionary();
794 state->BeginDictionary("client_state");
795 state->SetDouble("draw_duration_estimate_ms",
796 client_->DrawDurationEstimate().InMillisecondsF());
797 state->SetDouble(
798 "begin_main_frame_to_commit_duration_estimate_ms",
799 client_->BeginMainFrameToCommitDurationEstimate().InMillisecondsF());
800 state->SetDouble(
801 "commit_to_activate_duration_estimate_ms",
802 client_->CommitToActivateDurationEstimate().InMillisecondsF());
803 state->EndDictionary();
806 bool Scheduler::CanCommitAndActivateBeforeDeadline() const {
807 // Check if the main thread computation and commit can be finished before the
808 // impl thread's deadline.
809 base::TimeTicks estimated_draw_time =
810 begin_impl_frame_args_.frame_time +
811 client_->BeginMainFrameToCommitDurationEstimate() +
812 client_->CommitToActivateDurationEstimate();
814 TRACE_EVENT2(
815 TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler"),
816 "CanCommitAndActivateBeforeDeadline",
817 "time_left_after_drawing_ms",
818 (begin_impl_frame_args_.deadline - estimated_draw_time).InMillisecondsF(),
819 "state",
820 AsValue());
822 return estimated_draw_time < begin_impl_frame_args_.deadline;
825 bool Scheduler::IsBeginMainFrameSentOrStarted() const {
826 return (state_machine_.commit_state() ==
827 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT ||
828 state_machine_.commit_state() ==
829 SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED);
832 } // namespace cc