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