Per K | 61fff58 | 2024-05-28 12:09:59 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) 2015 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 | #ifndef MODULES_RTP_RTCP_SOURCE_NTP_TIME_UTIL_H_ |
| 12 | #define MODULES_RTP_RTCP_SOURCE_NTP_TIME_UTIL_H_ |
| 13 | |
| 14 | #include <stdint.h> |
| 15 | |
| 16 | #include "api/units/time_delta.h" |
| 17 | #include "rtc_base/numerics/safe_conversions.h" |
| 18 | #include "system_wrappers/include/ntp_time.h" |
| 19 | |
| 20 | namespace webrtc { |
| 21 | |
| 22 | // Helper function for compact ntp representation: |
| 23 | // RFC 3550, Section 4. Time Format. |
| 24 | // Wallclock time is represented using the timestamp format of |
| 25 | // the Network Time Protocol (NTP). |
| 26 | // ... |
| 27 | // In some fields where a more compact representation is |
| 28 | // appropriate, only the middle 32 bits are used; that is, the low 16 |
| 29 | // bits of the integer part and the high 16 bits of the fractional part. |
| 30 | inline uint32_t CompactNtp(NtpTime ntp) { |
| 31 | return (ntp.seconds() << 16) | (ntp.fractions() >> 16); |
| 32 | } |
| 33 | |
| 34 | // Converts interval to compact ntp (1/2^16 seconds) resolution. |
| 35 | // Negative values converted to 0, Overlarge values converted to max uint32_t. |
| 36 | uint32_t SaturatedToCompactNtp(TimeDelta delta); |
| 37 | |
| 38 | // Convert interval to the NTP time resolution (1/2^32 seconds ~= 0.2 ns). |
| 39 | // For deltas with absolute value larger than 35 minutes result is unspecified. |
| 40 | inline constexpr int64_t ToNtpUnits(TimeDelta delta) { |
| 41 | // For better precision `delta` is taken with best TimeDelta precision (us), |
| 42 | // then multiplaction and conversion to seconds are swapped to avoid float |
| 43 | // arithmetic. |
| 44 | // 2^31 us ~= 35.8 minutes. |
| 45 | return (rtc::saturated_cast<int32_t>(delta.us()) * (int64_t{1} << 32)) / |
| 46 | 1'000'000; |
| 47 | } |
| 48 | |
| 49 | // Converts interval from compact ntp (1/2^16 seconds) resolution to TimeDelta. |
| 50 | // This interval can be up to ~9.1 hours (2^15 seconds). |
| 51 | // Values close to 2^16 seconds are considered negative and are converted to |
| 52 | // minimum value of 1ms. |
| 53 | TimeDelta CompactNtpRttToTimeDelta(uint32_t compact_ntp_interval); |
| 54 | |
| 55 | } // namespace webrtc |
| 56 | #endif // MODULES_RTP_RTCP_SOURCE_NTP_TIME_UTIL_H_ |