xref: /aosp_15_r20/external/webrtc/system_wrappers/include/rtp_to_ntp_estimator.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2012 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 SYSTEM_WRAPPERS_INCLUDE_RTP_TO_NTP_ESTIMATOR_H_
12 #define SYSTEM_WRAPPERS_INCLUDE_RTP_TO_NTP_ESTIMATOR_H_
13 
14 #include <stdint.h>
15 
16 #include <list>
17 
18 #include "absl/types/optional.h"
19 #include "modules/include/module_common_types_public.h"
20 #include "rtc_base/checks.h"
21 #include "system_wrappers/include/ntp_time.h"
22 
23 namespace webrtc {
24 
25 // Converts an RTP timestamp to the NTP domain.
26 // The class needs to be trained with (at least 2) RTP/NTP timestamp pairs from
27 // RTCP sender reports before the convertion can be done.
28 class RtpToNtpEstimator {
29  public:
30   static constexpr int kMaxInvalidSamples = 3;
31 
32   RtpToNtpEstimator() = default;
33   RtpToNtpEstimator(const RtpToNtpEstimator&) = delete;
34   RtpToNtpEstimator& operator=(const RtpToNtpEstimator&) = delete;
35   ~RtpToNtpEstimator() = default;
36 
37   enum UpdateResult { kInvalidMeasurement, kSameMeasurement, kNewMeasurement };
38   // Updates measurements with RTP/NTP timestamp pair from a RTCP sender report.
39   UpdateResult UpdateMeasurements(NtpTime ntp, uint32_t rtp_timestamp);
40 
41   // Converts an RTP timestamp to the NTP domain.
42   // Returns invalid NtpTime (i.e. NtpTime(0)) on failure.
43   NtpTime Estimate(uint32_t rtp_timestamp) const;
44 
45   // Returns estimated rtp_timestamp frequency, or 0 on failure.
46   double EstimatedFrequencyKhz() const;
47 
48  private:
49   // Estimated parameters from RTP and NTP timestamp pairs in `measurements_`.
50   // Defines linear estimation: NtpTime (in units of 1s/2^32) =
51   //   `Parameters::slope` * rtp_timestamp + `Parameters::offset`.
52   struct Parameters {
53     double slope;
54     double offset;
55   };
56 
57   // RTP and NTP timestamp pair from a RTCP SR report.
58   struct RtcpMeasurement {
59     NtpTime ntp_time;
60     int64_t unwrapped_rtp_timestamp;
61   };
62 
63   void UpdateParameters();
64 
65   int consecutive_invalid_samples_ = 0;
66   std::list<RtcpMeasurement> measurements_;
67   absl::optional<Parameters> params_;
68   mutable TimestampUnwrapper unwrapper_;
69 };
70 }  // namespace webrtc
71 
72 #endif  // SYSTEM_WRAPPERS_INCLUDE_RTP_TO_NTP_ESTIMATOR_H_
73