time_delta_interpolator.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2014 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. #include "media/base/time_delta_interpolator.h"
  5. #include <stdint.h>
  6. #include <algorithm>
  7. #include "base/check.h"
  8. #include "base/time/tick_clock.h"
  9. #include "media/base/timestamp_constants.h"
  10. namespace media {
  11. TimeDeltaInterpolator::TimeDeltaInterpolator(const base::TickClock* tick_clock)
  12. : tick_clock_(tick_clock),
  13. interpolating_(false),
  14. upper_bound_(kNoTimestamp),
  15. playback_rate_(0) {
  16. DCHECK(tick_clock_);
  17. }
  18. TimeDeltaInterpolator::~TimeDeltaInterpolator() = default;
  19. base::TimeDelta TimeDeltaInterpolator::StartInterpolating() {
  20. DCHECK(!interpolating_);
  21. reference_ = tick_clock_->NowTicks();
  22. interpolating_ = true;
  23. return lower_bound_;
  24. }
  25. base::TimeDelta TimeDeltaInterpolator::StopInterpolating() {
  26. DCHECK(interpolating_);
  27. lower_bound_ = GetInterpolatedTime();
  28. interpolating_ = false;
  29. return lower_bound_;
  30. }
  31. void TimeDeltaInterpolator::SetPlaybackRate(double playback_rate) {
  32. lower_bound_ = GetInterpolatedTime();
  33. reference_ = tick_clock_->NowTicks();
  34. playback_rate_ = playback_rate;
  35. }
  36. void TimeDeltaInterpolator::SetBounds(base::TimeDelta lower_bound,
  37. base::TimeDelta upper_bound,
  38. base::TimeTicks capture_time) {
  39. DCHECK(lower_bound <= upper_bound);
  40. DCHECK(lower_bound != kNoTimestamp);
  41. lower_bound_ = std::max(base::TimeDelta(), lower_bound);
  42. upper_bound_ = std::max(base::TimeDelta(), upper_bound);
  43. reference_ = capture_time;
  44. }
  45. void TimeDeltaInterpolator::SetUpperBound(base::TimeDelta upper_bound) {
  46. DCHECK(upper_bound != kNoTimestamp);
  47. lower_bound_ = GetInterpolatedTime();
  48. reference_ = tick_clock_->NowTicks();
  49. upper_bound_ = upper_bound;
  50. }
  51. base::TimeDelta TimeDeltaInterpolator::GetInterpolatedTime() {
  52. if (!interpolating_)
  53. return lower_bound_;
  54. int64_t now_us = (tick_clock_->NowTicks() - reference_).InMicroseconds();
  55. now_us = static_cast<int64_t>(now_us * playback_rate_);
  56. base::TimeDelta interpolated_time = lower_bound_ + base::Microseconds(now_us);
  57. if (upper_bound_ == kNoTimestamp)
  58. return interpolated_time;
  59. return std::min(interpolated_time, upper_bound_);
  60. }
  61. } // namespace media