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"
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"
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;
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
)
45 last_tick_time_(base::TimeTicks() - interval
),
46 current_parameters_(interval
, base::TimeTicks()),
47 next_parameters_(interval
, base::TimeTicks()),
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();
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() {
91 last_tick_time_
= current_parameters_
.tick_target
;
93 PostNextTickTask(Now());
97 client_
->OnTimerTick();
100 void DelayBasedTimeSource::SetClient(TimeSourceClient
* client
) {
104 void DelayBasedTimeSource::SetTimebaseAndInterval(base::TimeTicks timebase
,
105 base::TimeDelta interval
) {
106 next_parameters_
.interval
= interval
;
107 next_parameters_
.tick_target
= timebase
;
110 // If we aren't active, there's no need to reset the timer.
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
);
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
);
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
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
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 base::TimeDelta new_interval
= next_parameters_
.interval
;
208 // |interval_offset| is the offset from |now| to the next multiple of
209 // |interval| after |tick_target|, possibly negative if in the past.
210 base::TimeDelta interval_offset
= base::TimeDelta::FromInternalValue(
211 (next_parameters_
.tick_target
- now
).ToInternalValue() %
212 new_interval
.ToInternalValue());
213 // If |now| is exactly on the interval (i.e. offset==0), don't adjust.
214 // Otherwise, if |tick_target| was in the past, adjust forward to the next
216 if (interval_offset
.ToInternalValue() != 0 &&
217 next_parameters_
.tick_target
< now
) {
218 interval_offset
+= new_interval
;
221 base::TimeTicks new_tick_target
= now
+ interval_offset
;
222 DCHECK(now
<= new_tick_target
)
223 << "now = " << now
.ToInternalValue()
224 << "; new_tick_target = " << new_tick_target
.ToInternalValue()
225 << "; new_interval = " << new_interval
.InMicroseconds()
226 << "; tick_target = " << next_parameters_
.tick_target
.ToInternalValue()
227 << "; interval_offset = " << interval_offset
.ToInternalValue();
229 // Avoid double ticks when:
230 // 1) Turning off the timer and turning it right back on.
231 // 2) Jittery data is passed to SetTimebaseAndInterval().
232 if (new_tick_target
- last_tick_time_
<= new_interval
/ kDoubleTickDivisor
)
233 new_tick_target
+= new_interval
;
235 return new_tick_target
;
238 void DelayBasedTimeSource::PostNextTickTask(base::TimeTicks now
) {
239 base::TimeTicks new_tick_target
= NextTickTarget(now
);
241 // Post another task *before* the tick and update state
242 base::TimeDelta delay
;
243 if (now
<= new_tick_target
)
244 delay
= new_tick_target
- now
;
245 task_runner_
->PostDelayedTask(FROM_HERE
,
246 base::Bind(&DelayBasedTimeSource::OnTimerFired
,
247 weak_factory_
.GetWeakPtr()),
250 next_parameters_
.tick_target
= new_tick_target
;
251 current_parameters_
= next_parameters_
;