1 /* 2 * Copyright (c) 2014 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_INCLUDE_REMOTE_NTP_TIME_ESTIMATOR_H_ 12 #define MODULES_RTP_RTCP_INCLUDE_REMOTE_NTP_TIME_ESTIMATOR_H_ 13 14 #include <stdint.h> 15 16 #include "absl/types/optional.h" 17 #include "api/units/time_delta.h" 18 #include "api/units/timestamp.h" 19 #include "rtc_base/numerics/moving_percentile_filter.h" 20 #include "system_wrappers/include/rtp_to_ntp_estimator.h" 21 22 namespace webrtc { 23 24 class Clock; 25 26 // RemoteNtpTimeEstimator can be used to estimate a given RTP timestamp's NTP 27 // time in local timebase. 28 // Note that it needs to be trained with at least 2 RTCP SR (by calling 29 // `UpdateRtcpTimestamp`) before it can be used. 30 class RemoteNtpTimeEstimator { 31 public: 32 explicit RemoteNtpTimeEstimator(Clock* clock); 33 RemoteNtpTimeEstimator(const RemoteNtpTimeEstimator&) = delete; 34 RemoteNtpTimeEstimator& operator=(const RemoteNtpTimeEstimator&) = delete; 35 ~RemoteNtpTimeEstimator() = default; 36 37 // Updates the estimator with round trip time `rtt` and 38 // new NTP time <-> RTP timestamp mapping from an RTCP sender report. 39 bool UpdateRtcpTimestamp(TimeDelta rtt, 40 NtpTime sender_send_time, 41 uint32_t rtp_timestamp); 42 43 // Estimates the NTP timestamp in local timebase from `rtp_timestamp`. 44 // Returns the NTP timestamp in ms when success. -1 if failed. Estimate(uint32_t rtp_timestamp)45 int64_t Estimate(uint32_t rtp_timestamp) { 46 NtpTime ntp_time = EstimateNtp(rtp_timestamp); 47 if (!ntp_time.Valid()) { 48 return -1; 49 } 50 return ntp_time.ToMs(); 51 } 52 53 // Estimates the NTP timestamp in local timebase from `rtp_timestamp`. 54 // Returns invalid NtpTime (i.e. NtpTime(0)) on failure. 55 NtpTime EstimateNtp(uint32_t rtp_timestamp); 56 57 // Estimates the offset between the remote clock and the 58 // local one. This is equal to local NTP clock - remote NTP clock. 59 // The offset is returned in ntp time resolution, i.e. 1/2^32 sec ~= 0.2 ns. 60 // Returns nullopt on failure. 61 absl::optional<int64_t> EstimateRemoteToLocalClockOffset(); 62 63 private: 64 Clock* clock_; 65 // Offset is measured with the same precision as NtpTime: in 1/2^32 seconds ~= 66 // 0.2 ns. 67 MovingMedianFilter<int64_t> ntp_clocks_offset_estimator_; 68 RtpToNtpEstimator rtp_to_ntp_; 69 Timestamp last_timing_log_ = Timestamp::MinusInfinity(); 70 }; 71 72 } // namespace webrtc 73 74 #endif // MODULES_RTP_RTCP_INCLUDE_REMOTE_NTP_TIME_ESTIMATOR_H_ 75