cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / cc / scheduler / delay_based_time_source.cc
bloba5b6f738df8e831d005fbbd875b5b5848f9964da
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/delay_based_time_source.h"
7 #include <algorithm>
8 #include <cmath>
10 #include "base/bind.h"
11 #include "base/debug/trace_event.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/single_thread_task_runner.h"
16 namespace cc {
18 namespace {
20 // kDoubleTickDivisor prevents ticks from running within the specified
21 // fraction of an interval. This helps account for jitter in the timebase as
22 // well as quick timer reactivation.
23 static const int kDoubleTickDivisor = 2;
25 // kIntervalChangeThreshold is the fraction of the interval that will trigger an
26 // immediate interval change. kPhaseChangeThreshold is the fraction of the
27 // interval that will trigger an immediate phase change. If the changes are
28 // within the thresholds, the change will take place on the next tick. If
29 // either change is outside the thresholds, the next tick will be canceled and
30 // reissued immediately.
31 static const double kIntervalChangeThreshold = 0.25;
32 static const double kPhaseChangeThreshold = 0.25;
34 } // namespace
36 scoped_refptr<DelayBasedTimeSource> DelayBasedTimeSource::Create(
37 base::TimeDelta interval,
38 base::SingleThreadTaskRunner* task_runner) {
39 return make_scoped_refptr(new DelayBasedTimeSource(interval, task_runner));
42 DelayBasedTimeSource::DelayBasedTimeSource(
43 base::TimeDelta interval, base::SingleThreadTaskRunner* task_runner)
44 : client_(NULL),
45 last_tick_time_(base::TimeTicks() - interval),
46 current_parameters_(interval, base::TimeTicks()),
47 next_parameters_(interval, base::TimeTicks()),
48 active_(false),
49 task_runner_(task_runner),
50 weak_factory_(this) {}
52 DelayBasedTimeSource::~DelayBasedTimeSource() {}
54 base::TimeTicks DelayBasedTimeSource::SetActive(bool active) {
55 TRACE_EVENT1("cc", "DelayBasedTimeSource::SetActive", "active", active);
56 if (active == active_)
57 return base::TimeTicks();
58 active_ = active;
60 if (!active_) {
61 weak_factory_.InvalidateWeakPtrs();
62 return base::TimeTicks();
65 PostNextTickTask(Now());
67 // Determine if there was a tick that was missed while not active.
68 base::TimeTicks last_tick_time_if_always_active =
69 current_parameters_.tick_target - current_parameters_.interval;
70 base::TimeTicks new_tick_time_threshold =
71 last_tick_time_ + current_parameters_.interval / kDoubleTickDivisor;
72 if (last_tick_time_if_always_active > new_tick_time_threshold) {
73 last_tick_time_ = last_tick_time_if_always_active;
74 return last_tick_time_;
77 return base::TimeTicks();
80 bool DelayBasedTimeSource::Active() const { return active_; }
82 base::TimeTicks DelayBasedTimeSource::LastTickTime() { return last_tick_time_; }
84 base::TimeTicks DelayBasedTimeSource::NextTickTime() {
85 return Active() ? current_parameters_.tick_target : base::TimeTicks();
88 void DelayBasedTimeSource::OnTimerFired() {
89 DCHECK(active_);
91 last_tick_time_ = current_parameters_.tick_target;
93 PostNextTickTask(Now());
95 // Fire the tick.
96 if (client_)
97 client_->OnTimerTick();
100 void DelayBasedTimeSource::SetClient(TimeSourceClient* client) {
101 client_ = client;
104 void DelayBasedTimeSource::SetTimebaseAndInterval(base::TimeTicks timebase,
105 base::TimeDelta interval) {
106 next_parameters_.interval = interval;
107 next_parameters_.tick_target = timebase;
109 if (!active_) {
110 // If we aren't active, there's no need to reset the timer.
111 return;
114 // If the change in interval is larger than the change threshold,
115 // request an immediate reset.
116 double interval_delta =
117 std::abs((interval - current_parameters_.interval).InSecondsF());
118 double interval_change = interval_delta / interval.InSecondsF();
119 if (interval_change > kIntervalChangeThreshold) {
120 TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::IntervalChanged",
121 TRACE_EVENT_SCOPE_THREAD);
122 SetActive(false);
123 SetActive(true);
124 return;
127 // If the change in phase is greater than the change threshold in either
128 // direction, request an immediate reset. This logic might result in a false
129 // negative if there is a simultaneous small change in the interval and the
130 // fmod just happens to return something near zero. Assuming the timebase
131 // is very recent though, which it should be, we'll still be ok because the
132 // old clock and new clock just happen to line up.
133 double target_delta =
134 std::abs((timebase - current_parameters_.tick_target).InSecondsF());
135 double phase_change =
136 fmod(target_delta, interval.InSecondsF()) / interval.InSecondsF();
137 if (phase_change > kPhaseChangeThreshold &&
138 phase_change < (1.0 - kPhaseChangeThreshold)) {
139 TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::PhaseChanged",
140 TRACE_EVENT_SCOPE_THREAD);
141 SetActive(false);
142 SetActive(true);
143 return;
147 base::TimeTicks DelayBasedTimeSource::Now() const {
148 return base::TimeTicks::Now();
151 // This code tries to achieve an average tick rate as close to interval_ as
152 // possible. To do this, it has to deal with a few basic issues:
153 // 1. PostDelayedTask can delay only at a millisecond granularity. So, 16.666
154 // has to posted as 16 or 17.
155 // 2. A delayed task may come back a bit late (a few ms), or really late
156 // (frames later)
158 // The basic idea with this scheduler here is to keep track of where we *want*
159 // to run in tick_target_. We update this with the exact interval.
161 // Then, when we post our task, we take the floor of (tick_target_ and Now()).
162 // If we started at now=0, and 60FPs (all times in milliseconds):
163 // now=0 target=16.667 PostDelayedTask(16)
165 // When our callback runs, we figure out how far off we were from that goal.
166 // Because of the flooring operation, and assuming our timer runs exactly when
167 // it should, this yields:
168 // now=16 target=16.667
170 // Since we can't post a 0.667 ms task to get to now=16, we just treat this as a
171 // tick. Then, we update target to be 33.333. We now post another task based on
172 // the difference between our target and now:
173 // now=16 tick_target=16.667 new_target=33.333 -->
174 // PostDelayedTask(floor(33.333 - 16)) --> PostDelayedTask(17)
176 // Over time, with no late tasks, this leads to us posting tasks like this:
177 // now=0 tick_target=0 new_target=16.667 -->
178 // tick(), PostDelayedTask(16)
179 // now=16 tick_target=16.667 new_target=33.333 -->
180 // tick(), PostDelayedTask(17)
181 // now=33 tick_target=33.333 new_target=50.000 -->
182 // tick(), PostDelayedTask(17)
183 // now=50 tick_target=50.000 new_target=66.667 -->
184 // tick(), PostDelayedTask(16)
186 // We treat delays in tasks differently depending on the amount of delay we
187 // encounter. Suppose we posted a task with a target=16.667:
188 // Case 1: late but not unrecoverably-so
189 // now=18 tick_target=16.667
191 // Case 2: so late we obviously missed the tick
192 // now=25.0 tick_target=16.667
194 // We treat the first case as a tick anyway, and assume the delay was unusual.
195 // Thus, we compute the new_target based on the old timebase:
196 // now=18 tick_target=16.667 new_target=33.333 -->
197 // tick(), PostDelayedTask(floor(33.333-18)) --> PostDelayedTask(15)
198 // This brings us back to 18+15 = 33, which was where we would have been if the
199 // task hadn't been late.
201 // For the really late delay, we we move to the next logical tick. The timebase
202 // is not reset.
203 // now=37 tick_target=16.667 new_target=50.000 -->
204 // tick(), PostDelayedTask(floor(50.000-37)) --> PostDelayedTask(13)
205 base::TimeTicks DelayBasedTimeSource::NextTickTarget(base::TimeTicks now) {
206 const base::TimeDelta epsilon(base::TimeDelta::FromMicroseconds(1));
207 base::TimeDelta new_interval = next_parameters_.interval;
209 // Integer division rounds towards 0, but we always want to round down the
210 // number of intervals_elapsed, so we need the extra condition here.
211 int intervals_elapsed;
212 if (next_parameters_.tick_target < now) {
213 intervals_elapsed =
214 (now - next_parameters_.tick_target + new_interval - epsilon) /
215 new_interval;
216 } else {
217 intervals_elapsed = (now - next_parameters_.tick_target) / new_interval;
219 base::TimeTicks new_tick_target =
220 next_parameters_.tick_target + new_interval * intervals_elapsed;
221 DCHECK(now <= new_tick_target)
222 << "now = " << now.ToInternalValue()
223 << "; new_tick_target = " << new_tick_target.ToInternalValue()
224 << "; new_interval = " << new_interval.InMicroseconds()
225 << "; tick_target = " << next_parameters_.tick_target.ToInternalValue()
226 << "; intervals_elapsed = " << intervals_elapsed;
228 // Avoid double ticks when:
229 // 1) Turning off the timer and turning it right back on.
230 // 2) Jittery data is passed to SetTimebaseAndInterval().
231 if (new_tick_target - last_tick_time_ <= new_interval / kDoubleTickDivisor)
232 new_tick_target += new_interval;
234 return new_tick_target;
237 void DelayBasedTimeSource::PostNextTickTask(base::TimeTicks now) {
238 base::TimeTicks new_tick_target = NextTickTarget(now);
240 // Post another task *before* the tick and update state
241 base::TimeDelta delay;
242 if (now <= new_tick_target)
243 delay = new_tick_target - now;
244 task_runner_->PostDelayedTask(FROM_HERE,
245 base::Bind(&DelayBasedTimeSource::OnTimerFired,
246 weak_factory_.GetWeakPtr()),
247 delay);
249 next_parameters_.tick_target = new_tick_target;
250 current_parameters_ = next_parameters_;
253 } // namespace cc