blob: dedba4d7ec1d65b3d65dabbb8cc89089616a461a [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
11#include "webrtc/modules/rtp_rtcp/source/time_util.h"
12
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) {
19 // Caller ensure x is positive by converting unsigned value into it.
20 // So this Divide doesn't need to handle negative argument case.
21 return (x + y / 2) / y;
22}
23} // namespace
24
25int64_t CompactNtpRttToMs(uint32_t compact_ntp_interval) {
26 // Interval to convert expected to be positive, e.g. rtt or delay.
27 // Because interval can be derived from non-monotonic ntp clock,
28 // it might become negative that is indistinguishable from very large values.
29 // Since very large rtt/delay are less likely than non-monotonic ntp clock,
30 // those values consider to be negative and convert to minimum value of 1ms.
31 if (compact_ntp_interval > 0x80000000)
32 return 1;
33 // Convert to 64bit value to avoid multiplication overflow.
34 int64_t value = static_cast<int64_t>(compact_ntp_interval);
35 // To convert to milliseconds need to divide by 2^16 to get seconds,
36 // then multiply by 1000 to get milliseconds. To avoid float operations,
37 // multiplication and division swapped.
38 int64_t ms = DivideRoundToNearest(value * 1000, 1 << 16);
39 // Rtt value 0 considered too good to be true and increases to 1.
40 return std::max<int64_t>(ms, 1);
41}
42} // namespace webrtc