Shaka Packager SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
audio_timestamp_helper.cc
1 // Copyright (c) 2012 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 "packager/media/base/audio_timestamp_helper.h"
6 
7 #include "packager/base/logging.h"
8 #include "packager/media/base/timestamp.h"
9 
10 namespace shaka {
11 namespace media {
12 
13 AudioTimestampHelper::AudioTimestampHelper(uint32_t timescale,
14  uint32_t samples_per_second)
15  : base_timestamp_(kNoTimestamp), frame_count_(0) {
16  DCHECK_GT(samples_per_second, 0u);
17  double fps = samples_per_second;
18  ticks_per_frame_ = timescale / fps;
19 }
20 
21 void AudioTimestampHelper::SetBaseTimestamp(int64_t base_timestamp) {
22  base_timestamp_ = base_timestamp;
23  frame_count_ = 0;
24 }
25 
26 int64_t AudioTimestampHelper::base_timestamp() const {
27  return base_timestamp_;
28 }
29 
30 void AudioTimestampHelper::AddFrames(int64_t frame_count) {
31  DCHECK_GE(frame_count, 0);
32  DCHECK(base_timestamp_ != kNoTimestamp);
33  frame_count_ += frame_count;
34 }
35 
36 int64_t AudioTimestampHelper::GetTimestamp() const {
37  return ComputeTimestamp(frame_count_);
38 }
39 
40 int64_t AudioTimestampHelper::GetFrameDuration(int64_t frame_count) const {
41  DCHECK_GE(frame_count, 0);
42  int64_t end_timestamp = ComputeTimestamp(frame_count_ + frame_count);
43  return end_timestamp - GetTimestamp();
44 }
45 
46 int64_t AudioTimestampHelper::GetFramesToTarget(int64_t target) const {
47  DCHECK(base_timestamp_ != kNoTimestamp);
48  DCHECK(target >= base_timestamp_);
49 
50  int64_t delta_in_ticks = (target - GetTimestamp());
51  if (delta_in_ticks == 0)
52  return 0;
53 
54  // Compute a timestamp relative to |base_timestamp_| since timestamps
55  // created from |frame_count_| are computed relative to this base.
56  // This ensures that the time to frame computation here is the proper inverse
57  // of the frame to time computation in ComputeTimestamp().
58  int64_t delta_from_base = target - base_timestamp_;
59 
60  // Compute frame count for the time delta. This computation rounds to
61  // the nearest whole number of frames.
62  double threshold = ticks_per_frame_ / 2;
63  int64_t target_frame_count = (delta_from_base + threshold) / ticks_per_frame_;
64  return target_frame_count - frame_count_;
65 }
66 
67 int64_t AudioTimestampHelper::ComputeTimestamp(int64_t frame_count) const {
68  DCHECK_GE(frame_count, 0);
69  DCHECK(base_timestamp_ != kNoTimestamp);
70  double frames_ticks = ticks_per_frame_ * frame_count;
71  return base_timestamp_ + frames_ticks;
72 }
73 
74 } // namespace media
75 } // namespace shaka