| 1 |
#include "rist_time.h" |
| 2 |
|
| 3 |
#include "endian-shim.h" |
| 4 |
#include "rtp.h" |
| 5 |
#include "time-shim.h" |
| 6 |
|
| 7 |
#include <stdint.h> |
| 8 |
|
| 9 |
uint64_t timestampNTP_u64(void) { |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
). |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
timespec_t ts = {0, 0}; |
| 26 |
#if defined(__APPLE__) |
| 27 |
clock_gettime_osx(CLOCK_MONOTONIC_OSX, &ts); |
| 28 |
#else |
| 29 |
clock_gettime(CLOCK_MONOTONIC, &ts); |
| 30 |
#endif |
| 31 |
|
| 32 |
uint64_t t = (uint64_t)(ts.tv_nsec) << 32; |
| 33 |
t /= 1000000000; |
| 34 |
|
| 35 |
|
| 36 |
t |= (uint64_t)((70LL * 365 + 17) * 24 * 60 * 60 + ts.tv_sec) << 32; |
| 37 |
return t; |
| 38 |
} |
| 39 |
|
| 40 |
uint64_t timestampNTP_RTC_u64(void) { |
| 41 |
timespec_t ts = {0, 0}; |
| 42 |
#if defined(__APPLE__) |
| 43 |
clock_gettime_osx(CLOCK_REALTIME_OSX, &ts); |
| 44 |
#else |
| 45 |
clock_gettime(CLOCK_REALTIME, &ts); |
| 46 |
#endif |
| 47 |
|
| 48 |
uint64_t t = (uint64_t)(ts.tv_nsec) << 32; |
| 49 |
t /= 1000000000; |
| 50 |
|
| 51 |
|
| 52 |
t |= (uint64_t)((70LL * 365 + 17) * 24 * 60 * 60 + ts.tv_sec) << 32; |
| 53 |
return t; |
| 54 |
} |
| 55 |
|
| 56 |
uint64_t convertRTPtoNTP(uint8_t ptype, uint32_t time_extension, |
| 57 |
uint32_t i_rtp) { |
| 58 |
uint64_t i_ntp; |
| 59 |
if (ptype == RTP_PTYPE_RIST) { |
| 60 |
|
| 61 |
uint64_t part2 = (uint64_t)i_rtp; |
| 62 |
part2 = part2 << 16; |
| 63 |
|
| 64 |
uint64_t part3 = (uint64_t)(time_extension & 0xffff); |
| 65 |
uint64_t part1 = ((uint64_t)(time_extension & 0xffff0000)) << 32; |
| 66 |
i_ntp = part1 | part2 | part3; |
| 67 |
|
| 68 |
|
| 69 |
} else { |
| 70 |
int32_t clock = get_rtp_ts_clock(ptype); |
| 71 |
if (RIST_UNLIKELY(!clock)) { |
| 72 |
clock = RTP_PTYPE_MPEGTS_CLOCKHZ; |
| 73 |
|
| 74 |
i_rtp = htobe32(timestampRTP_u32(0, timestampNTP_u64())); |
| 75 |
} |
| 76 |
i_ntp = (uint64_t)i_rtp << 32; |
| 77 |
i_ntp /= clock; |
| 78 |
} |
| 79 |
return i_ntp; |
| 80 |
} |
| 81 |
|
| 82 |
uint64_t calculate_rtt_delay(uint64_t request, uint64_t response, |
| 83 |
uint32_t delay) { |
| 84 |
|
| 85 |
if (request > response) |
| 86 |
return 0; |
| 87 |
uint64_t rtt = response - request; |
| 88 |
if (RIST_UNLIKELY(delay)) { |
| 89 |
uint64_t delay_ticks = (((uint64_t)delay) << 32) / 1000000; |
| 90 |
if (delay_ticks > rtt) |
| 91 |
return 0; |
| 92 |
rtt -= delay_ticks; |
| 93 |
} |
| 94 |
return rtt; |
| 95 |
} |