blob: cf1d984248250129f1a33e7836a16a37e4933f64 [file] [log] [blame]
Danil Chapovalovc1e55c72016-03-09 15:14:35 +01001/*
2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/rtp_rtcp/source/time_util.h"
Danil Chapovalovc1e55c72016-03-09 15:14:35 +010012
13#include <algorithm>
14
15namespace webrtc {
16namespace {
17// TODO(danilchap): Make generic, optimize and move to base.
18inline int64_t DivideRoundToNearest(int64_t x, uint32_t y) {
Danil Chapovalovd4fdc272017-11-09 11:34:32 +010019 // Callers ensure x is positive and x + y / 2 doesn't overflow.
Danil Chapovalovc1e55c72016-03-09 15:14:35 +010020 return (x + y / 2) / y;
21}
22} // namespace
23
Danil Chapovalovd4fdc272017-11-09 11:34:32 +010024uint32_t SaturatedUsToCompactNtp(int64_t us) {
25 constexpr uint32_t kMaxCompactNtp = 0xFFFFFFFF;
26 constexpr int64_t kMicrosecondsInSecond = 1000000;
27 constexpr int kCompactNtpInSecond = 0x10000;
28 if (us <= 0)
29 return 0;
30 if (us >= kMaxCompactNtp * kMicrosecondsInSecond / kCompactNtpInSecond)
31 return kMaxCompactNtp;
32 // To convert to compact ntp need to divide by 1e6 to get seconds,
33 // then multiply by 0x10000 to get the final result.
34 // To avoid float operations, multiplication and division swapped.
35 return DivideRoundToNearest(us * kCompactNtpInSecond, kMicrosecondsInSecond);
36}
37
Danil Chapovalovc1e55c72016-03-09 15:14:35 +010038int64_t CompactNtpRttToMs(uint32_t compact_ntp_interval) {
39 // Interval to convert expected to be positive, e.g. rtt or delay.
40 // Because interval can be derived from non-monotonic ntp clock,
41 // it might become negative that is indistinguishable from very large values.
42 // Since very large rtt/delay are less likely than non-monotonic ntp clock,
43 // those values consider to be negative and convert to minimum value of 1ms.
44 if (compact_ntp_interval > 0x80000000)
45 return 1;
46 // Convert to 64bit value to avoid multiplication overflow.
47 int64_t value = static_cast<int64_t>(compact_ntp_interval);
48 // To convert to milliseconds need to divide by 2^16 to get seconds,
49 // then multiply by 1000 to get milliseconds. To avoid float operations,
50 // multiplication and division swapped.
51 int64_t ms = DivideRoundToNearest(value * 1000, 1 << 16);
52 // Rtt value 0 considered too good to be true and increases to 1.
53 return std::max<int64_t>(ms, 1);
54}
55} // namespace webrtc