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/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/message_loop.h"
13 #include "cc/base/thread.h"
19 // kDoubleTickThreshold prevents ticks from running within the specified
20 // fraction of an interval. This helps account for jitter in the timebase as
21 // well as quick timer reactivation.
22 static const double kDoubleTickThreshold
= 0.25;
24 // kIntervalChangeThreshold is the fraction of the interval that will trigger an
25 // immediate interval change. kPhaseChangeThreshold is the fraction of the
26 // interval that will trigger an immediate phase change. If the changes are
27 // within the thresholds, the change will take place on the next tick. If
28 // either change is outside the thresholds, the next tick will be canceled and
29 // reissued immediately.
30 static const double kIntervalChangeThreshold
= 0.25;
31 static const double kPhaseChangeThreshold
= 0.25;
35 scoped_refptr
<DelayBasedTimeSource
> DelayBasedTimeSource::Create(
36 base::TimeDelta interval
,
38 return make_scoped_refptr(new DelayBasedTimeSource(interval
, thread
));
41 DelayBasedTimeSource::DelayBasedTimeSource(base::TimeDelta interval
,
44 has_tick_target_(false),
45 current_parameters_(interval
, base::TimeTicks()),
46 next_parameters_(interval
, base::TimeTicks()),
47 state_(STATE_INACTIVE
),
49 weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {}
51 DelayBasedTimeSource::~DelayBasedTimeSource() {}
53 void DelayBasedTimeSource::SetActive(bool active
) {
54 TRACE_EVENT1("cc", "DelayBasedTimeSource::SetActive", "active", active
);
56 state_
= STATE_INACTIVE
;
57 weak_factory_
.InvalidateWeakPtrs();
61 if (state_
== STATE_STARTING
|| state_
== STATE_ACTIVE
)
64 if (!has_tick_target_
) {
65 // Becoming active the first time is deferred: we post a 0-delay task.
66 // When it runs, we use that to establish the timebase, become truly
67 // active, and fire the first tick.
68 state_
= STATE_STARTING
;
69 thread_
->PostTask(base::Bind(&DelayBasedTimeSource::OnTimerFired
,
70 weak_factory_
.GetWeakPtr()));
74 state_
= STATE_ACTIVE
;
76 PostNextTickTask(Now());
79 bool DelayBasedTimeSource::Active() const { return state_
!= STATE_INACTIVE
; }
81 base::TimeTicks
DelayBasedTimeSource::LastTickTime() { return last_tick_time_
; }
83 base::TimeTicks
DelayBasedTimeSource::NextTickTime() {
84 return Active() ? current_parameters_
.tick_target
: base::TimeTicks();
87 void DelayBasedTimeSource::OnTimerFired() {
88 DCHECK(state_
!= STATE_INACTIVE
);
90 base::TimeTicks now
= this->Now();
91 last_tick_time_
= now
;
93 if (state_
== STATE_STARTING
) {
94 SetTimebaseAndInterval(now
, current_parameters_
.interval
);
95 state_
= STATE_ACTIVE
;
98 PostNextTickTask(now
);
102 client_
->OnTimerTick();
105 void DelayBasedTimeSource::SetClient(TimeSourceClient
* client
) {
109 void DelayBasedTimeSource::SetTimebaseAndInterval(base::TimeTicks timebase
,
110 base::TimeDelta interval
) {
111 next_parameters_
.interval
= interval
;
112 next_parameters_
.tick_target
= timebase
;
113 has_tick_target_
= true;
115 if (state_
!= STATE_ACTIVE
) {
116 // If we aren't active, there's no need to reset the timer.
120 // If the change in interval is larger than the change threshold,
121 // request an immediate reset.
122 double interval_delta
=
123 std::abs((interval
- current_parameters_
.interval
).InSecondsF());
124 double interval_change
= interval_delta
/ interval
.InSecondsF();
125 if (interval_change
> kIntervalChangeThreshold
) {
131 // If the change in phase is greater than the change threshold in either
132 // direction, request an immediate reset. This logic might result in a false
133 // negative if there is a simultaneous small change in the interval and the
134 // fmod just happens to return something near zero. Assuming the timebase
135 // is very recent though, which it should be, we'll still be ok because the
136 // old clock and new clock just happen to line up.
137 double target_delta
=
138 std::abs((timebase
- current_parameters_
.tick_target
).InSecondsF());
139 double phase_change
=
140 fmod(target_delta
, interval
.InSecondsF()) / interval
.InSecondsF();
141 if (phase_change
> kPhaseChangeThreshold
&&
142 phase_change
< (1.0 - kPhaseChangeThreshold
)) {
149 base::TimeTicks
DelayBasedTimeSource::Now() const {
150 return base::TimeTicks::Now();
153 // This code tries to achieve an average tick rate as close to interval_ as
154 // possible. To do this, it has to deal with a few basic issues:
155 // 1. PostDelayedTask can delay only at a millisecond granularity. So, 16.666
156 // has to posted as 16 or 17.
157 // 2. A delayed task may come back a bit late (a few ms), or really late
160 // The basic idea with this scheduler here is to keep track of where we *want*
161 // to run in tick_target_. We update this with the exact interval.
163 // Then, when we post our task, we take the floor of (tick_target_ and Now()).
164 // If we started at now=0, and 60FPs (all times in milliseconds):
165 // now=0 target=16.667 PostDelayedTask(16)
167 // When our callback runs, we figure out how far off we were from that goal.
168 // Because of the flooring operation, and assuming our timer runs exactly when
169 // it should, this yields:
170 // now=16 target=16.667
172 // Since we can't post a 0.667 ms task to get to now=16, we just treat this as a
173 // tick. Then, we update target to be 33.333. We now post another task based on
174 // the difference between our target and now:
175 // now=16 tick_target=16.667 new_target=33.333 -->
176 // PostDelayedTask(floor(33.333 - 16)) --> PostDelayedTask(17)
178 // Over time, with no late tasks, this leads to us posting tasks like this:
179 // now=0 tick_target=0 new_target=16.667 -->
180 // tick(), PostDelayedTask(16)
181 // now=16 tick_target=16.667 new_target=33.333 -->
182 // tick(), PostDelayedTask(17)
183 // now=33 tick_target=33.333 new_target=50.000 -->
184 // tick(), PostDelayedTask(17)
185 // now=50 tick_target=50.000 new_target=66.667 -->
186 // tick(), PostDelayedTask(16)
188 // We treat delays in tasks differently depending on the amount of delay we
189 // encounter. Suppose we posted a task with a target=16.667:
190 // Case 1: late but not unrecoverably-so
191 // now=18 tick_target=16.667
193 // Case 2: so late we obviously missed the tick
194 // now=25.0 tick_target=16.667
196 // We treat the first case as a tick anyway, and assume the delay was unusual.
197 // Thus, we compute the new_target based on the old timebase:
198 // now=18 tick_target=16.667 new_target=33.333 -->
199 // tick(), PostDelayedTask(floor(33.333-18)) --> PostDelayedTask(15)
200 // This brings us back to 18+15 = 33, which was where we would have been if the
201 // task hadn't been late.
203 // For the really late delay, we we move to the next logical tick. The timebase
205 // now=37 tick_target=16.667 new_target=50.000 -->
206 // tick(), PostDelayedTask(floor(50.000-37)) --> PostDelayedTask(13)
207 base::TimeTicks
DelayBasedTimeSource::NextTickTarget(base::TimeTicks now
) {
208 base::TimeDelta new_interval
= next_parameters_
.interval
;
209 int intervals_elapsed
=
210 static_cast<int>(floor((now
- next_parameters_
.tick_target
).InSecondsF() /
211 new_interval
.InSecondsF()));
212 base::TimeTicks last_effective_tick
=
213 next_parameters_
.tick_target
+ new_interval
* intervals_elapsed
;
214 base::TimeTicks new_tick_target
= last_effective_tick
+ new_interval
;
215 DCHECK(new_tick_target
> now
);
217 // Avoid double ticks when:
218 // 1) Turning off the timer and turning it right back on.
219 // 2) Jittery data is passed to SetTimebaseAndInterval().
220 if (new_tick_target
- last_tick_time_
<=
221 new_interval
/ static_cast<int>(1.0 / kDoubleTickThreshold
))
222 new_tick_target
+= new_interval
;
224 return new_tick_target
;
227 void DelayBasedTimeSource::PostNextTickTask(base::TimeTicks now
) {
228 base::TimeTicks new_tick_target
= NextTickTarget(now
);
230 // Post another task *before* the tick and update state
231 base::TimeDelta delay
= new_tick_target
- now
;
232 DCHECK(delay
.InMillisecondsF() <=
233 next_parameters_
.interval
.InMillisecondsF() *
234 (1.0 + kDoubleTickThreshold
));
235 thread_
->PostDelayedTask(base::Bind(&DelayBasedTimeSource::OnTimerFired
,
236 weak_factory_
.GetWeakPtr()),
239 next_parameters_
.tick_target
= new_tick_target
;
240 current_parameters_
= next_parameters_
;