Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / cc / scheduler / delay_based_time_source.cc
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.
4
5 #include "cc/scheduler/delay_based_time_source.h"
6
7 #include <algorithm>
8 #include <cmath>
9
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"
15
16 namespace cc {
17
18 namespace {
19
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;
24
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;
33
34 }  // namespace
35
36 // The following methods correspond to the DelayBasedTimeSource that uses
37 // the base::TimeTicks::HighResNow as the timebase.
38 scoped_refptr<DelayBasedTimeSourceHighRes> DelayBasedTimeSourceHighRes::Create(
39     base::TimeDelta interval,
40     base::SingleThreadTaskRunner* task_runner) {
41   return make_scoped_refptr(
42       new DelayBasedTimeSourceHighRes(interval, task_runner));
43 }
44
45 DelayBasedTimeSourceHighRes::DelayBasedTimeSourceHighRes(
46     base::TimeDelta interval,
47     base::SingleThreadTaskRunner* task_runner)
48     : DelayBasedTimeSource(interval, task_runner) {
49 }
50
51 DelayBasedTimeSourceHighRes::~DelayBasedTimeSourceHighRes() {}
52
53 base::TimeTicks DelayBasedTimeSourceHighRes::Now() const {
54   return base::TimeTicks::HighResNow();
55 }
56
57 // The following methods correspond to the DelayBasedTimeSource that uses
58 // the base::TimeTicks::Now as the timebase.
59 scoped_refptr<DelayBasedTimeSource> DelayBasedTimeSource::Create(
60     base::TimeDelta interval,
61     base::SingleThreadTaskRunner* task_runner) {
62   return make_scoped_refptr(new DelayBasedTimeSource(interval, task_runner));
63 }
64
65 DelayBasedTimeSource::DelayBasedTimeSource(
66     base::TimeDelta interval,
67     base::SingleThreadTaskRunner* task_runner)
68     : client_(NULL),
69       last_tick_time_(base::TimeTicks() - interval),
70       current_parameters_(interval, base::TimeTicks()),
71       next_parameters_(interval, base::TimeTicks()),
72       active_(false),
73       task_runner_(task_runner),
74       weak_factory_(this) {
75   DCHECK_GT(interval.ToInternalValue(), 0);
76 }
77
78 DelayBasedTimeSource::~DelayBasedTimeSource() {}
79
80 base::TimeTicks DelayBasedTimeSource::SetActive(bool active) {
81   TRACE_EVENT1("cc", "DelayBasedTimeSource::SetActive", "active", active);
82   if (active == active_)
83     return base::TimeTicks();
84   active_ = active;
85
86   if (!active_) {
87     weak_factory_.InvalidateWeakPtrs();
88     return base::TimeTicks();
89   }
90
91   PostNextTickTask(Now());
92
93   // Determine if there was a tick that was missed while not active.
94   base::TimeTicks last_tick_time_if_always_active =
95     current_parameters_.tick_target - current_parameters_.interval;
96   base::TimeTicks new_tick_time_threshold =
97     last_tick_time_ + current_parameters_.interval / kDoubleTickDivisor;
98   if (last_tick_time_if_always_active >  new_tick_time_threshold) {
99     last_tick_time_ = last_tick_time_if_always_active;
100     return last_tick_time_;
101   }
102
103   return base::TimeTicks();
104 }
105
106 bool DelayBasedTimeSource::Active() const { return active_; }
107
108 base::TimeTicks DelayBasedTimeSource::LastTickTime() { return last_tick_time_; }
109
110 base::TimeTicks DelayBasedTimeSource::NextTickTime() {
111   return Active() ? current_parameters_.tick_target : base::TimeTicks();
112 }
113
114 void DelayBasedTimeSource::OnTimerFired() {
115   DCHECK(active_);
116
117   last_tick_time_ = current_parameters_.tick_target;
118
119   PostNextTickTask(Now());
120
121   // Fire the tick.
122   if (client_)
123     client_->OnTimerTick();
124 }
125
126 void DelayBasedTimeSource::SetClient(TimeSourceClient* client) {
127   client_ = client;
128 }
129
130 void DelayBasedTimeSource::SetTimebaseAndInterval(base::TimeTicks timebase,
131                                                   base::TimeDelta interval) {
132   DCHECK_GT(interval.ToInternalValue(), 0);
133   next_parameters_.interval = interval;
134   next_parameters_.tick_target = timebase;
135
136   if (!active_) {
137     // If we aren't active, there's no need to reset the timer.
138     return;
139   }
140
141   // If the change in interval is larger than the change threshold,
142   // request an immediate reset.
143   double interval_delta =
144       std::abs((interval - current_parameters_.interval).InSecondsF());
145   double interval_change = interval_delta / interval.InSecondsF();
146   if (interval_change > kIntervalChangeThreshold) {
147     TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::IntervalChanged",
148                          TRACE_EVENT_SCOPE_THREAD);
149     SetActive(false);
150     SetActive(true);
151     return;
152   }
153
154   // If the change in phase is greater than the change threshold in either
155   // direction, request an immediate reset. This logic might result in a false
156   // negative if there is a simultaneous small change in the interval and the
157   // fmod just happens to return something near zero. Assuming the timebase
158   // is very recent though, which it should be, we'll still be ok because the
159   // old clock and new clock just happen to line up.
160   double target_delta =
161       std::abs((timebase - current_parameters_.tick_target).InSecondsF());
162   double phase_change =
163       fmod(target_delta, interval.InSecondsF()) / interval.InSecondsF();
164   if (phase_change > kPhaseChangeThreshold &&
165       phase_change < (1.0 - kPhaseChangeThreshold)) {
166     TRACE_EVENT_INSTANT0("cc", "DelayBasedTimeSource::PhaseChanged",
167                          TRACE_EVENT_SCOPE_THREAD);
168     SetActive(false);
169     SetActive(true);
170     return;
171   }
172 }
173
174 base::TimeTicks DelayBasedTimeSource::Now() const {
175   return base::TimeTicks::Now();
176 }
177
178 // This code tries to achieve an average tick rate as close to interval_ as
179 // possible.  To do this, it has to deal with a few basic issues:
180 //   1. PostDelayedTask can delay only at a millisecond granularity. So, 16.666
181 //   has to posted as 16 or 17.
182 //   2. A delayed task may come back a bit late (a few ms), or really late
183 //   (frames later)
184 //
185 // The basic idea with this scheduler here is to keep track of where we *want*
186 // to run in tick_target_. We update this with the exact interval.
187 //
188 // Then, when we post our task, we take the floor of (tick_target_ and Now()).
189 // If we started at now=0, and 60FPs (all times in milliseconds):
190 //      now=0    target=16.667   PostDelayedTask(16)
191 //
192 // When our callback runs, we figure out how far off we were from that goal.
193 // Because of the flooring operation, and assuming our timer runs exactly when
194 // it should, this yields:
195 //      now=16   target=16.667
196 //
197 // Since we can't post a 0.667 ms task to get to now=16, we just treat this as a
198 // tick. Then, we update target to be 33.333. We now post another task based on
199 // the difference between our target and now:
200 //      now=16   tick_target=16.667  new_target=33.333   -->
201 //          PostDelayedTask(floor(33.333 - 16)) --> PostDelayedTask(17)
202 //
203 // Over time, with no late tasks, this leads to us posting tasks like this:
204 //      now=0    tick_target=0       new_target=16.667   -->
205 //          tick(), PostDelayedTask(16)
206 //      now=16   tick_target=16.667  new_target=33.333   -->
207 //          tick(), PostDelayedTask(17)
208 //      now=33   tick_target=33.333  new_target=50.000   -->
209 //          tick(), PostDelayedTask(17)
210 //      now=50   tick_target=50.000  new_target=66.667   -->
211 //          tick(), PostDelayedTask(16)
212 //
213 // We treat delays in tasks differently depending on the amount of delay we
214 // encounter. Suppose we posted a task with a target=16.667:
215 //   Case 1: late but not unrecoverably-so
216 //      now=18 tick_target=16.667
217 //
218 //   Case 2: so late we obviously missed the tick
219 //      now=25.0 tick_target=16.667
220 //
221 // We treat the first case as a tick anyway, and assume the delay was unusual.
222 // Thus, we compute the new_target based on the old timebase:
223 //      now=18   tick_target=16.667  new_target=33.333   -->
224 //          tick(), PostDelayedTask(floor(33.333-18)) --> PostDelayedTask(15)
225 // This brings us back to 18+15 = 33, which was where we would have been if the
226 // task hadn't been late.
227 //
228 // For the really late delay, we we move to the next logical tick. The timebase
229 // is not reset.
230 //      now=37   tick_target=16.667  new_target=50.000  -->
231 //          tick(), PostDelayedTask(floor(50.000-37)) --> PostDelayedTask(13)
232 base::TimeTicks DelayBasedTimeSource::NextTickTarget(base::TimeTicks now) {
233   base::TimeDelta new_interval = next_parameters_.interval;
234
235   // |interval_offset| is the offset from |now| to the next multiple of
236   // |interval| after |tick_target|, possibly negative if in the past.
237   base::TimeDelta interval_offset = base::TimeDelta::FromInternalValue(
238       (next_parameters_.tick_target - now).ToInternalValue() %
239       new_interval.ToInternalValue());
240   // If |now| is exactly on the interval (i.e. offset==0), don't adjust.
241   // Otherwise, if |tick_target| was in the past, adjust forward to the next
242   // tick after |now|.
243   if (interval_offset.ToInternalValue() != 0 &&
244       next_parameters_.tick_target < now) {
245     interval_offset += new_interval;
246   }
247
248   base::TimeTicks new_tick_target = now + interval_offset;
249   DCHECK(now <= new_tick_target)
250       << "now = " << now.ToInternalValue()
251       << "; new_tick_target = " << new_tick_target.ToInternalValue()
252       << "; new_interval = " << new_interval.InMicroseconds()
253       << "; tick_target = " << next_parameters_.tick_target.ToInternalValue()
254       << "; interval_offset = " << interval_offset.ToInternalValue();
255
256   // Avoid double ticks when:
257   // 1) Turning off the timer and turning it right back on.
258   // 2) Jittery data is passed to SetTimebaseAndInterval().
259   if (new_tick_target - last_tick_time_ <= new_interval / kDoubleTickDivisor)
260     new_tick_target += new_interval;
261
262   return new_tick_target;
263 }
264
265 void DelayBasedTimeSource::PostNextTickTask(base::TimeTicks now) {
266   base::TimeTicks new_tick_target = NextTickTarget(now);
267
268   // Post another task *before* the tick and update state
269   base::TimeDelta delay;
270   if (now <= new_tick_target)
271     delay = new_tick_target - now;
272   task_runner_->PostDelayedTask(FROM_HERE,
273                                 base::Bind(&DelayBasedTimeSource::OnTimerFired,
274                                            weak_factory_.GetWeakPtr()),
275                                 delay);
276
277   next_parameters_.tick_target = new_tick_target;
278   current_parameters_ = next_parameters_;
279 }
280
281 }  // namespace cc