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 scoped_refptr
<DelayBasedTimeSource
> DelayBasedTimeSource::Create(
41 base::TimeDelta interval
,
42 base::SingleThreadTaskRunner
* task_runner
) {
43 return make_scoped_refptr(new DelayBasedTimeSource(interval
, task_runner
));
46 DelayBasedTimeSource::DelayBasedTimeSource(
47 base::TimeDelta interval
,
48 base::SingleThreadTaskRunner
* task_runner
)
50 last_tick_time_(base::TimeTicks() - interval
),
51 current_parameters_(interval
, base::TimeTicks()),
52 next_parameters_(interval
, base::TimeTicks()),
54 task_runner_(task_runner
),
56 DCHECK_GT(interval
.ToInternalValue(), 0);
59 DelayBasedTimeSource::~DelayBasedTimeSource() {}
61 base::TimeTicks
DelayBasedTimeSource::SetActive(bool active
) {
62 TRACE_EVENT1("cc", "DelayBasedTimeSource::SetActive", "active", active
);
63 if (active
== active_
)
64 return base::TimeTicks();
68 weak_factory_
.InvalidateWeakPtrs();
69 return base::TimeTicks();
72 PostNextTickTask(Now());
74 // Determine if there was a tick that was missed while not active.
75 base::TimeTicks last_tick_time_if_always_active
=
76 current_parameters_
.tick_target
- current_parameters_
.interval
;
77 base::TimeTicks new_tick_time_threshold
=
78 last_tick_time_
+ current_parameters_
.interval
/ kDoubleTickDivisor
;
79 if (last_tick_time_if_always_active
> new_tick_time_threshold
) {
80 last_tick_time_
= last_tick_time_if_always_active
;
81 return last_tick_time_
;
84 return base::TimeTicks();
87 bool DelayBasedTimeSource::Active() const { return active_
; }
89 base::TimeTicks
DelayBasedTimeSource::LastTickTime() const {
90 return last_tick_time_
;
93 base::TimeTicks
DelayBasedTimeSource::NextTickTime() const {
94 return Active() ? current_parameters_
.tick_target
: base::TimeTicks();
97 void DelayBasedTimeSource::OnTimerFired() {
100 last_tick_time_
= current_parameters_
.tick_target
;
102 PostNextTickTask(Now());
106 client_
->OnTimerTick();
109 void DelayBasedTimeSource::SetClient(TimeSourceClient
* client
) {
113 void DelayBasedTimeSource::SetTimebaseAndInterval(base::TimeTicks timebase
,
114 base::TimeDelta interval
) {
115 DCHECK_GT(interval
.ToInternalValue(), 0);
116 next_parameters_
.interval
= interval
;
117 next_parameters_
.tick_target
= timebase
;
120 // If we aren't active, there's no need to reset the timer.
124 // If the change in interval is larger than the change threshold,
125 // request an immediate reset.
126 double interval_delta
=
127 std::abs((interval
- current_parameters_
.interval
).InSecondsF());
128 double interval_change
= interval_delta
/ interval
.InSecondsF();
129 if (interval_change
> kIntervalChangeThreshold
) {
130 TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::IntervalChanged",
131 TRACE_EVENT_SCOPE_THREAD
);
137 // If the change in phase is greater than the change threshold in either
138 // direction, request an immediate reset. This logic might result in a false
139 // negative if there is a simultaneous small change in the interval and the
140 // fmod just happens to return something near zero. Assuming the timebase
141 // is very recent though, which it should be, we'll still be ok because the
142 // old clock and new clock just happen to line up.
143 double target_delta
=
144 std::abs((timebase
- current_parameters_
.tick_target
).InSecondsF());
145 double phase_change
=
146 fmod(target_delta
, interval
.InSecondsF()) / interval
.InSecondsF();
147 if (phase_change
> kPhaseChangeThreshold
&&
148 phase_change
< (1.0 - kPhaseChangeThreshold
)) {
149 TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::PhaseChanged",
150 TRACE_EVENT_SCOPE_THREAD
);
157 base::TimeTicks
DelayBasedTimeSource::Now() const {
158 return base::TimeTicks::Now();
161 // This code tries to achieve an average tick rate as close to interval_ as
162 // possible. To do this, it has to deal with a few basic issues:
163 // 1. PostDelayedTask can delay only at a millisecond granularity. So, 16.666
164 // has to posted as 16 or 17.
165 // 2. A delayed task may come back a bit late (a few ms), or really late
168 // The basic idea with this scheduler here is to keep track of where we *want*
169 // to run in tick_target_. We update this with the exact interval.
171 // Then, when we post our task, we take the floor of (tick_target_ and Now()).
172 // If we started at now=0, and 60FPs (all times in milliseconds):
173 // now=0 target=16.667 PostDelayedTask(16)
175 // When our callback runs, we figure out how far off we were from that goal.
176 // Because of the flooring operation, and assuming our timer runs exactly when
177 // it should, this yields:
178 // now=16 target=16.667
180 // Since we can't post a 0.667 ms task to get to now=16, we just treat this as a
181 // tick. Then, we update target to be 33.333. We now post another task based on
182 // the difference between our target and now:
183 // now=16 tick_target=16.667 new_target=33.333 -->
184 // PostDelayedTask(floor(33.333 - 16)) --> PostDelayedTask(17)
186 // Over time, with no late tasks, this leads to us posting tasks like this:
187 // now=0 tick_target=0 new_target=16.667 -->
188 // tick(), PostDelayedTask(16)
189 // now=16 tick_target=16.667 new_target=33.333 -->
190 // tick(), PostDelayedTask(17)
191 // now=33 tick_target=33.333 new_target=50.000 -->
192 // tick(), PostDelayedTask(17)
193 // now=50 tick_target=50.000 new_target=66.667 -->
194 // tick(), PostDelayedTask(16)
196 // We treat delays in tasks differently depending on the amount of delay we
197 // encounter. Suppose we posted a task with a target=16.667:
198 // Case 1: late but not unrecoverably-so
199 // now=18 tick_target=16.667
201 // Case 2: so late we obviously missed the tick
202 // now=25.0 tick_target=16.667
204 // We treat the first case as a tick anyway, and assume the delay was unusual.
205 // Thus, we compute the new_target based on the old timebase:
206 // now=18 tick_target=16.667 new_target=33.333 -->
207 // tick(), PostDelayedTask(floor(33.333-18)) --> PostDelayedTask(15)
208 // This brings us back to 18+15 = 33, which was where we would have been if the
209 // task hadn't been late.
211 // For the really late delay, we we move to the next logical tick. The timebase
213 // now=37 tick_target=16.667 new_target=50.000 -->
214 // tick(), PostDelayedTask(floor(50.000-37)) --> PostDelayedTask(13)
215 base::TimeTicks
DelayBasedTimeSource::NextTickTarget(base::TimeTicks now
) {
216 base::TimeTicks new_tick_target
= now
.SnappedToNextTick(
217 next_parameters_
.tick_target
, next_parameters_
.interval
);
218 DCHECK(now
<= new_tick_target
)
219 << "now = " << now
.ToInternalValue()
220 << "; new_tick_target = " << new_tick_target
.ToInternalValue()
221 << "; new_interval = " << next_parameters_
.interval
.InMicroseconds()
222 << "; tick_target = " << next_parameters_
.tick_target
.ToInternalValue();
224 // Avoid double ticks when:
225 // 1) Turning off the timer and turning it right back on.
226 // 2) Jittery data is passed to SetTimebaseAndInterval().
227 if (new_tick_target
- last_tick_time_
<=
228 next_parameters_
.interval
/ kDoubleTickDivisor
)
229 new_tick_target
+= next_parameters_
.interval
;
231 return new_tick_target
;
234 void DelayBasedTimeSource::PostNextTickTask(base::TimeTicks now
) {
235 base::TimeTicks new_tick_target
= NextTickTarget(now
);
237 // Post another task *before* the tick and update state
238 base::TimeDelta delay
;
239 if (now
<= new_tick_target
)
240 delay
= new_tick_target
- now
;
241 task_runner_
->PostDelayedTask(FROM_HERE
,
242 base::Bind(&DelayBasedTimeSource::OnTimerFired
,
243 weak_factory_
.GetWeakPtr()),
246 next_parameters_
.tick_target
= new_tick_target
;
247 current_parameters_
= next_parameters_
;
250 std::string
DelayBasedTimeSource::TypeString() const {
251 return "DelayBasedTimeSource";
254 void DelayBasedTimeSource::AsValueInto(
255 base::trace_event::TracedValue
* state
) const {
256 state
->SetString("type", TypeString());
257 state
->SetDouble("last_tick_time_us", LastTickTime().ToInternalValue());
258 state
->SetDouble("next_tick_time_us", NextTickTime().ToInternalValue());
260 state
->BeginDictionary("current_parameters");
261 state
->SetDouble("interval_us",
262 current_parameters_
.interval
.InMicroseconds());
263 state
->SetDouble("tick_target_us",
264 current_parameters_
.tick_target
.ToInternalValue());
265 state
->EndDictionary();
267 state
->BeginDictionary("next_parameters");
268 state
->SetDouble("interval_us", next_parameters_
.interval
.InMicroseconds());
269 state
->SetDouble("tick_target_us",
270 next_parameters_
.tick_target
.ToInternalValue());
271 state
->EndDictionary();
273 state
->SetBoolean("active", active_
);