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