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