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"
11 #include "base/bind.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/trace_event/trace_event_argument.h"
22 // kDoubleTickDivisor prevents ticks from running within the specified
23 // fraction of an interval. This helps account for jitter in the timebase as
24 // well as quick timer reactivation.
25 static const int kDoubleTickDivisor
= 2;
27 // kIntervalChangeThreshold is the fraction of the interval that will trigger an
28 // immediate interval change. kPhaseChangeThreshold is the fraction of the
29 // interval that will trigger an immediate phase change. If the changes are
30 // within the thresholds, the change will take place on the next tick. If
31 // either change is outside the thresholds, the next tick will be canceled and
32 // reissued immediately.
33 static const double kIntervalChangeThreshold
= 0.25;
34 static const double kPhaseChangeThreshold
= 0.25;
38 // The following methods correspond to the DelayBasedTimeSource that uses
39 // the base::TimeTicks::Now as the timebase.
40 DelayBasedTimeSource::DelayBasedTimeSource(
41 base::TimeDelta interval
,
42 base::SingleThreadTaskRunner
* task_runner
)
45 timebase_(base::TimeTicks()),
47 last_tick_time_(base::TimeTicks() - interval
),
48 next_tick_time_(base::TimeTicks()),
49 task_runner_(task_runner
),
51 DCHECK_GT(interval
, base::TimeDelta());
54 DelayBasedTimeSource::~DelayBasedTimeSource() {}
56 base::TimeTicks
DelayBasedTimeSource::SetActive(bool active
) {
57 TRACE_EVENT1("cc", "DelayBasedTimeSource::SetActive", "active", active
);
59 if (active
== active_
)
60 return base::TimeTicks();
65 next_tick_time_
= base::TimeTicks();
66 tick_closure_
.Cancel();
67 return base::TimeTicks();
72 // Determine if there was a tick that was missed while not active.
73 base::TimeTicks last_tick_time_if_always_active
= next_tick_time_
- interval_
;
74 base::TimeTicks last_tick_time_threshold
=
75 last_tick_time_
+ interval_
/ kDoubleTickDivisor
;
76 if (last_tick_time_if_always_active
> last_tick_time_threshold
) {
77 last_tick_time_
= last_tick_time_if_always_active
;
78 return last_tick_time_
;
81 return base::TimeTicks();
84 base::TimeDelta
DelayBasedTimeSource::Interval() const {
88 bool DelayBasedTimeSource::Active() const { return active_
; }
90 base::TimeTicks
DelayBasedTimeSource::LastTickTime() const {
91 return last_tick_time_
;
94 base::TimeTicks
DelayBasedTimeSource::NextTickTime() const {
95 return next_tick_time_
;
98 void DelayBasedTimeSource::OnTimerTick() {
101 last_tick_time_
= next_tick_time_
;
103 PostNextTickTask(Now());
107 client_
->OnTimerTick();
110 void DelayBasedTimeSource::SetClient(DelayBasedTimeSourceClient
* client
) {
114 void DelayBasedTimeSource::SetTimebaseAndInterval(base::TimeTicks timebase
,
115 base::TimeDelta interval
) {
116 DCHECK_GT(interval
, base::TimeDelta());
118 // If the change in interval is larger than the change threshold,
119 // request an immediate reset.
120 double interval_delta
= std::abs((interval
- interval_
).InSecondsF());
121 // Comparing with next_tick_time_ is the right thing to do because we want to
122 // know if we want to cancel the existing tick task and schedule a new one.
123 // Also next_tick_time_ = timebase_ mod interval_.
124 double timebase_delta
= std::abs((timebase
- next_tick_time_
).InSecondsF());
126 interval_
= interval
;
127 timebase_
= timebase
;
129 // If we aren't active, there's no need to reset the timer.
133 double interval_change
= interval_delta
/ interval
.InSecondsF();
134 if (interval_change
> kIntervalChangeThreshold
) {
135 TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::IntervalChanged",
136 TRACE_EVENT_SCOPE_THREAD
);
137 ResetTickTask(Now());
141 // If the change in phase is greater than the change threshold in either
142 // direction, request an immediate reset. This logic might result in a false
143 // negative if there is a simultaneous small change in the interval and the
144 // fmod just happens to return something near zero. Assuming the timebase
145 // is very recent though, which it should be, we'll still be ok because the
146 // old clock and new clock just happen to line up.
147 double phase_change
=
148 fmod(timebase_delta
, interval
.InSecondsF()) / interval
.InSecondsF();
149 if (phase_change
> kPhaseChangeThreshold
&&
150 phase_change
< (1.0 - kPhaseChangeThreshold
)) {
151 TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::PhaseChanged",
152 TRACE_EVENT_SCOPE_THREAD
);
153 ResetTickTask(Now());
158 base::TimeTicks
DelayBasedTimeSource::Now() const {
159 return base::TimeTicks::Now();
162 // This code tries to achieve an average tick rate as close to interval_ as
163 // possible. To do this, it has to deal with a few basic issues:
164 // 1. PostDelayedTask can delay only at a millisecond granularity. So, 16.666
165 // has to posted as 16 or 17.
166 // 2. A delayed task may come back a bit late (a few ms), or really late
169 // The basic idea with this scheduler here is to keep track of where we *want*
170 // to run in tick_target_. We update this with the exact interval.
172 // Then, when we post our task, we take the floor of (tick_target_ and Now()).
173 // If we started at now=0, and 60FPs (all times in milliseconds):
174 // now=0 target=16.667 PostDelayedTask(16)
176 // When our callback runs, we figure out how far off we were from that goal.
177 // Because of the flooring operation, and assuming our timer runs exactly when
178 // it should, this yields:
179 // now=16 target=16.667
181 // Since we can't post a 0.667 ms task to get to now=16, we just treat this as a
182 // tick. Then, we update target to be 33.333. We now post another task based on
183 // the difference between our target and now:
184 // now=16 tick_target=16.667 new_target=33.333 -->
185 // PostDelayedTask(floor(33.333 - 16)) --> PostDelayedTask(17)
187 // Over time, with no late tasks, this leads to us posting tasks like this:
188 // now=0 tick_target=0 new_target=16.667 -->
189 // tick(), PostDelayedTask(16)
190 // now=16 tick_target=16.667 new_target=33.333 -->
191 // tick(), PostDelayedTask(17)
192 // now=33 tick_target=33.333 new_target=50.000 -->
193 // tick(), PostDelayedTask(17)
194 // now=50 tick_target=50.000 new_target=66.667 -->
195 // tick(), PostDelayedTask(16)
197 // We treat delays in tasks differently depending on the amount of delay we
198 // encounter. Suppose we posted a task with a target=16.667:
199 // Case 1: late but not unrecoverably-so
200 // now=18 tick_target=16.667
202 // Case 2: so late we obviously missed the tick
203 // now=25.0 tick_target=16.667
205 // We treat the first case as a tick anyway, and assume the delay was unusual.
206 // Thus, we compute the new_target based on the old timebase:
207 // now=18 tick_target=16.667 new_target=33.333 -->
208 // tick(), PostDelayedTask(floor(33.333-18)) --> PostDelayedTask(15)
209 // This brings us back to 18+15 = 33, which was where we would have been if the
210 // task hadn't been late.
212 // For the really late delay, we we move to the next logical tick. The timebase
214 // now=37 tick_target=16.667 new_target=50.000 -->
215 // tick(), PostDelayedTask(floor(50.000-37)) --> PostDelayedTask(13)
216 base::TimeTicks
DelayBasedTimeSource::NextTickTarget(
217 base::TimeTicks now
) const {
218 base::TimeTicks next_tick_target
=
219 now
.SnappedToNextTick(timebase_
, interval_
);
220 DCHECK(now
<= next_tick_target
)
221 << "now = " << now
.ToInternalValue()
222 << "; new_tick_target = " << next_tick_target
.ToInternalValue()
223 << "; new_interval = " << interval_
.InMicroseconds()
224 << "; new_timbase = " << timebase_
.ToInternalValue();
226 // Avoid double ticks when:
227 // 1) Turning off the timer and turning it right back on.
228 // 2) Jittery data is passed to SetTimebaseAndInterval().
229 if (next_tick_target
- last_tick_time_
<= interval_
/ kDoubleTickDivisor
)
230 next_tick_target
+= interval_
;
232 return next_tick_target
;
235 void DelayBasedTimeSource::PostNextTickTask(base::TimeTicks now
) {
236 next_tick_time_
= NextTickTarget(now
);
237 DCHECK(next_tick_time_
>= now
);
238 // Post another task *before* the tick and update state
239 base::TimeDelta delay
= next_tick_time_
- now
;
240 task_runner_
->PostDelayedTask(FROM_HERE
, tick_closure_
.callback(), delay
);
243 void DelayBasedTimeSource::ResetTickTask(base::TimeTicks now
) {
244 tick_closure_
.Reset(base::Bind(&DelayBasedTimeSource::OnTimerTick
,
245 weak_factory_
.GetWeakPtr()));
246 PostNextTickTask(now
);
249 std::string
DelayBasedTimeSource::TypeString() const {
250 return "DelayBasedTimeSource";
253 void DelayBasedTimeSource::AsValueInto(
254 base::trace_event::TracedValue
* state
) const {
255 state
->SetString("type", TypeString());
256 state
->SetDouble("last_tick_time_us", LastTickTime().ToInternalValue());
257 state
->SetDouble("next_tick_time_us", NextTickTime().ToInternalValue());
258 state
->SetDouble("interval_us", interval_
.InMicroseconds());
259 state
->SetDouble("timebase_us", timebase_
.ToInternalValue());
260 state
->SetBoolean("active", active_
);