Skip to main content

rtci_rtp/
clock_rate.rs

1//! Several clock rates in one RTP session ([RFC 7160]).
2//!
3//! A source that changes payload type may change clock rate with it (PCMU at 8000 Hz to Opus
4//! at 48000 Hz, say). RFC 7160 says what then happens to the SSRC, the RTP timestamp and the
5//! receiver's jitter estimate. This module holds those rules as plain arithmetic: nothing here
6//! reads a clock. Instants are `Duration`s since an epoch the caller chooses.
7//!
8//! * `ClockRateHistory`: section 4.1, whether a clock rate change needs a new SSRC.
9//! * `MultiRateTimestamp`: section 4.2, the timestamp of a sender that keeps one SSRC.
10//! * `interarrival_difference` and `JitterEstimator`: section 4.3, the receiver's jitter.
11//!
12//! [RFC 7160]: https://datatracker.ietf.org/doc/html/rfc7160
13
14use std::time::Duration;
15
16/// `duration * clock_rate`, in timestamp units, rounded to the nearest unit.
17fn ticks(duration: Duration, clock_rate: u32) -> u128 {
18    (duration.as_nanos() * u128::from(clock_rate) + 500_000_000) / 1_000_000_000
19}
20
21/// What a sender that sends RTCP does with its SSRC when the clock rate of its stream changes
22/// (RFC 7160 section 4.1).
23#[derive(Debug, Copy, Clone, PartialEq, Eq)]
24pub enum SsrcForClockRate {
25    /// The clock rate is the one in use: keep the SSRC.
26    Keep,
27    /// A clock rate this stream has not used: a different SSRC is used for it.
28    New,
29    /// A clock rate the stream used before: an RTCP BYE is sent for the SSRC that used it and a
30    /// new SSRC is taken.
31    NewAfterBye,
32}
33
34/// The clock rates one RTP stream has used, for the SSRC rule of RFC 7160 section 4.1: a
35/// different SSRC for each clock rate, and a BYE and a new SSRC when the stream switches back
36/// to a rate it already used.
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct ClockRateHistory {
39    current: Option<u32>,
40    seen: Vec<u32>,
41}
42
43impl ClockRateHistory {
44    /// A stream that has sent nothing yet.
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// The clock rate in use, once a packet was sent.
50    pub fn current(&self) -> Option<u32> {
51        self.current
52    }
53
54    /// The other clock rates seen, most recent last: the ones whose mapping the next compound
55    /// RTCP packet carries in further SR packets after the current rate's (section 4.1).
56    pub fn previous(&self) -> impl Iterator<Item = u32> + '_ {
57        let current = self.current;
58        self.seen
59            .iter()
60            .copied()
61            .filter(move |&rate| Some(rate) != current)
62    }
63
64    /// Records that the next packet is sent with `clock_rate` and says what happens to the
65    /// SSRC. The first packet of a stream keeps the SSRC it was given.
66    pub fn switch_to(&mut self, clock_rate: u32) -> SsrcForClockRate {
67        if self.current == Some(clock_rate) {
68            return SsrcForClockRate::Keep;
69        }
70        let first = self.current.is_none();
71        let seen_before = self.seen.contains(&clock_rate);
72        self.current = Some(clock_rate);
73        if seen_before {
74            // Move it to the end: the most recent.
75            self.seen.retain(|&rate| rate != clock_rate);
76        }
77        self.seen.push(clock_rate);
78        if first {
79            SsrcForClockRate::Keep
80        } else if seen_before {
81            SsrcForClockRate::NewAfterBye
82        } else {
83            SsrcForClockRate::New
84        }
85    }
86}
87
88/// The RTP timestamp of a sender that keeps one SSRC across clock rate changes, which RFC 7160
89/// section 4.2 allows only with RTCP turned off:
90///
91/// ```text
92/// start_offset += (capture_time - capture_start) * previous_clock_rate   (on a change)
93/// capture_start = capture_time                                           (on a change)
94/// timestamp = (capture_time - capture_start) * clock_rate + start_offset
95/// ```
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct MultiRateTimestamp {
98    start_offset: u32,
99    capture_start: Duration,
100    clock_rate: u32,
101}
102
103impl MultiRateTimestamp {
104    /// The state for a stream whose first packet is captured at `capture_time` with
105    /// `clock_rate`. `initial_offset` is the stream's random initial timestamp (RFC 3550
106    /// section 5.1), which the caller draws.
107    pub fn new(initial_offset: u32, capture_time: Duration, clock_rate: u32) -> Self {
108        MultiRateTimestamp {
109            start_offset: initial_offset,
110            capture_start: capture_time,
111            clock_rate,
112        }
113    }
114
115    /// The RTP timestamp of a packet captured at `capture_time` and sent with `clock_rate`.
116    /// A capture time before the last clock rate change is taken as that change's instant.
117    pub fn timestamp(&mut self, capture_time: Duration, clock_rate: u32) -> u32 {
118        let since_start = capture_time.saturating_sub(self.capture_start);
119        if clock_rate != self.clock_rate {
120            // Timestamps wrap: the truncation is the modulo 2^32 arithmetic of RTP.
121            self.start_offset = self
122                .start_offset
123                .wrapping_add(ticks(since_start, self.clock_rate) as u32);
124            self.capture_start = capture_time.max(self.capture_start);
125            self.clock_rate = clock_rate;
126            return self.start_offset;
127        }
128        self.start_offset
129            .wrapping_add(ticks(since_start, clock_rate) as u32)
130    }
131}
132
133/// One received packet, as the jitter calculation needs it.
134#[derive(Debug, Copy, Clone, PartialEq, Eq)]
135pub struct Arrival {
136    /// When the packet arrived.
137    pub arrival_time: Duration,
138    /// Its RTP timestamp.
139    pub timestamp: u32,
140    /// The clock rate of its payload type.
141    pub clock_rate: u32,
142}
143
144/// `D(i,j)` of RFC 7160 section 4.3, in units of packet i's clock:
145///
146/// ```text
147/// D(i,j) = (arrival_time_j * clock_rate_i - timestamp_j)
148///          - (arrival_time_i * clock_rate_i - timestamp_i)
149/// ```
150///
151/// The clock rate of packet `i` (the earlier one) is used for both arrival times, which is
152/// what keeps the difference zero across a clock rate change on a path without jitter.
153pub fn interarrival_difference(i: Arrival, j: Arrival) -> i64 {
154    let arrival = if j.arrival_time >= i.arrival_time {
155        ticks(j.arrival_time - i.arrival_time, i.clock_rate) as i64
156    } else {
157        -(ticks(i.arrival_time - j.arrival_time, i.clock_rate) as i64)
158    };
159    // The timestamp difference is signed and modulo 2^32.
160    let sent = i64::from(j.timestamp.wrapping_sub(i.timestamp) as i32);
161    arrival - sent
162}
163
164/// The interarrival jitter estimator of RFC 3550 section 6.4.1 and Appendix A.8, fed with the
165/// difference of RFC 7160 section 4.3 so that a stream may change clock rate.
166#[derive(Debug, Clone, Default, PartialEq, Eq)]
167pub struct JitterEstimator {
168    last: Option<Arrival>,
169    /// The estimate, scaled by 16 as in Appendix A.8.
170    jitter_q4: u64,
171}
172
173impl JitterEstimator {
174    /// An estimator that has seen no packet.
175    pub fn new() -> Self {
176        Self::default()
177    }
178
179    /// Takes a packet, in the order of arrival, and returns the jitter estimate after it.
180    pub fn update(&mut self, packet: Arrival) -> u32 {
181        if let Some(last) = self.last {
182            let d = interarrival_difference(last, packet).unsigned_abs();
183            // J += (|D| - J) / 16, in the integer form of Appendix A.8.
184            self.jitter_q4 = self.jitter_q4 + d - ((self.jitter_q4 + 8) >> 4);
185        }
186        self.last = Some(packet);
187        self.jitter()
188    }
189
190    /// The jitter estimate, as an RTCP reception report carries it.
191    pub fn jitter(&self) -> u32 {
192        u32::try_from(self.jitter_q4 >> 4).unwrap_or(u32::MAX)
193    }
194}
195
196#[cfg(test)]
197#[path = "clock_rate_test.rs"]
198mod clock_rate_test;