summaryrefslogtreecommitdiff
path: root/chromium/media/base/time_delta_interpolator.cc
blob: a6eb4bfad72aa8b4bc4ae6b6d782191992fe8c80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/base/time_delta_interpolator.h"

#include <stdint.h>

#include <algorithm>

#include "base/check.h"
#include "base/time/tick_clock.h"
#include "media/base/timestamp_constants.h"

namespace media {

TimeDeltaInterpolator::TimeDeltaInterpolator(const base::TickClock* tick_clock)
    : tick_clock_(tick_clock),
      interpolating_(false),
      upper_bound_(kNoTimestamp),
      playback_rate_(0) {
  DCHECK(tick_clock_);
}

TimeDeltaInterpolator::~TimeDeltaInterpolator() = default;

base::TimeDelta TimeDeltaInterpolator::StartInterpolating() {
  DCHECK(!interpolating_);
  reference_ = tick_clock_->NowTicks();
  interpolating_ = true;
  return lower_bound_;
}

base::TimeDelta TimeDeltaInterpolator::StopInterpolating() {
  DCHECK(interpolating_);
  lower_bound_ = GetInterpolatedTime();
  interpolating_ = false;
  return lower_bound_;
}

void TimeDeltaInterpolator::SetPlaybackRate(double playback_rate) {
  lower_bound_ = GetInterpolatedTime();
  reference_ = tick_clock_->NowTicks();
  playback_rate_ = playback_rate;
}

void TimeDeltaInterpolator::SetBounds(base::TimeDelta lower_bound,
                                      base::TimeDelta upper_bound,
                                      base::TimeTicks capture_time) {
  DCHECK(lower_bound <= upper_bound);
  DCHECK(lower_bound != kNoTimestamp);

  lower_bound_ = std::max(base::TimeDelta(), lower_bound);
  upper_bound_ = std::max(base::TimeDelta(), upper_bound);
  reference_ = capture_time;
}

void TimeDeltaInterpolator::SetUpperBound(base::TimeDelta upper_bound) {
  DCHECK(upper_bound != kNoTimestamp);

  lower_bound_ = GetInterpolatedTime();
  reference_ = tick_clock_->NowTicks();
  upper_bound_ = upper_bound;
}

base::TimeDelta TimeDeltaInterpolator::GetInterpolatedTime() {
  if (!interpolating_)
    return lower_bound_;

  int64_t now_us = (tick_clock_->NowTicks() - reference_).InMicroseconds();
  now_us = static_cast<int64_t>(now_us * playback_rate_);
  base::TimeDelta interpolated_time = lower_bound_ + base::Microseconds(now_us);

  if (upper_bound_ == kNoTimestamp)
    return interpolated_time;

  return std::min(interpolated_time, upper_bound_);
}

}  // namespace media