1 // Copyright 2015 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 "media/cast/common/rtp_time.h"
6 
7 #include <limits>
8 #include <sstream>
9 
10 namespace media {
11 namespace cast {
12 
13 namespace {
14 
15 // Returns the base::TimeDelta nearest to the time represented by a tick count
16 // in the given timebase.
TicksToTimeDelta(int64_t ticks,int timebase)17 base::TimeDelta TicksToTimeDelta(int64_t ticks, int timebase) {
18   DCHECK_GT(timebase, 0);
19   const double micros = static_cast<double>(ticks) / timebase *
20                             base::Time::kMicrosecondsPerSecond +
21                                 0.5 /* rounding */;
22   DCHECK_LT(micros, static_cast<double>(std::numeric_limits<int64_t>::max()));
23   return base::TimeDelta::FromMicroseconds(static_cast<int64_t>(micros));
24 }
25 
26 // Returns the tick count in the given timebase nearest to the base::TimeDelta.
TimeDeltaToTicks(base::TimeDelta delta,int timebase)27 int64_t TimeDeltaToTicks(base::TimeDelta delta, int timebase) {
28   DCHECK_GT(timebase, 0);
29   const double ticks = delta.InSecondsF() * timebase + 0.5 /* rounding */;
30   DCHECK_LT(ticks, static_cast<double>(std::numeric_limits<int64_t>::max()));
31   return static_cast<int64_t>(ticks);
32 }
33 
34 }  // namespace
35 
operator <<(std::ostream & out,const RtpTimeDelta rhs)36 std::ostream& operator<<(std::ostream& out, const RtpTimeDelta rhs) {
37   if (rhs.value_ >= 0)
38     out << "RTP+";
39   else
40     out << "RTP";
41   return out << rhs.value_;
42 }
43 
operator <<(std::ostream & out,const RtpTimeTicks rhs)44 std::ostream& operator<<(std::ostream& out, const RtpTimeTicks rhs) {
45   return out << "RTP@" << rhs.value_;
46 }
47 
ToTimeDelta(int rtp_timebase) const48 base::TimeDelta RtpTimeDelta::ToTimeDelta(int rtp_timebase) const {
49   return TicksToTimeDelta(value_, rtp_timebase);
50 }
51 
52 // static
FromTimeDelta(base::TimeDelta delta,int rtp_timebase)53 RtpTimeDelta RtpTimeDelta::FromTimeDelta(base::TimeDelta delta,
54                                          int rtp_timebase) {
55   return RtpTimeDelta(TimeDeltaToTicks(delta, rtp_timebase));
56 }
57 
58 // static
FromTicks(int64_t ticks)59 RtpTimeDelta RtpTimeDelta::FromTicks(int64_t ticks) {
60   return RtpTimeDelta(ticks);
61 }
62 
ToTimeDelta(int rtp_timebase) const63 base::TimeDelta RtpTimeTicks::ToTimeDelta(int rtp_timebase) const {
64   return TicksToTimeDelta(value_, rtp_timebase);
65 }
66 
67 // static
FromTimeDelta(base::TimeDelta delta,int rtp_timebase)68 RtpTimeTicks RtpTimeTicks::FromTimeDelta(base::TimeDelta delta,
69                                          int rtp_timebase) {
70   return RtpTimeTicks(TimeDeltaToTicks(delta, rtp_timebase));
71 }
72 
73 }  // namespace cast
74 }  // namespace media
75