rtci_interceptor/ntp_timestamp.rs
1//! Rapid synchronisation (RFC 6051 section 3.3): an NTP-format timestamp in the RTP header
2//! extension `urn:ietf:params:rtp-hdrext:ntp-64` (or `ntp-56`) of the packets of a local
3//! stream that negotiated it, so a receiver can map the stream's RTP timestamps to the
4//! sender's wall clock (and synchronise it with the sender's other streams) before, or
5//! without, an RTCP sender report.
6//!
7//! Which packets carry it: every packet in a stream's first [`NtpTimestampBuilder::with_initial_window`]
8//! (5 seconds by default, longer than the sender's first RTCP report takes, RFC 3550 6.2: half
9//! the minimum interval at most 1.5 times), and from then on the packets of one RTP timestamp
10//! (one frame) every [`NtpTimestampBuilder::with_interval`] (1 second), so a receiver that
11//! joins late or switches to the stream synchronises within about a second. RFC 6051 section
12//! 3.3 lets a sender include it in "any RTP packets" it chooses and asks for it on video random
13//! access points and the audio packets beside them: the engine cannot tell a random access
14//! point in every payload format, and the once-a-second frames stand in for them. Regular SRs
15//! go on whatever this does ("regular RTCP SR packets MUST be sent"). No packet is stamped in
16//! the two seconds around the end of a month, where a positive leap second could fall (RFC 7164
17//! section 5, as the RTCP session's sender reports).
18//!
19//! The timestamp is the instant the packet passes, on the clock the RTCP session's sender
20//! reports take theirs from ([`SystemInstant::shared`], or the anchor
21//! [`NtpTimestampBuilder::with_wall_clock`] gives, which the RTCP session must be given too): the report generator relates a
22//! stream's RTP timestamps to the same instants (the packet's passage), so both describe one
23//! mapping, as section 3.3 requires ("MUST correspond to the same time instant as the RTP
24//! timestamp ... MUST be derived from the same clock used to generate the NTP-format
25//! timestamps included in RTCP SR packets").
26//!
27//! # Where it belongs
28//!
29//! `Slot::Custom(NTP_TIMESTAMP_SLOT)` (1_850): wire-ward of the pacer, so the instant is the
30//! one the packet leaves at; application-ward of the FEC wire-image tap (1_500), so FEC protects
31//! the packet as it leaves.
32
33use crate::stream_info::StreamInfo;
34use crate::{Attribute, Interceptor, Packet, TaggedPacket};
35use rtp::extension::ntp_timestamp_extension::{
36 NTP_56_URI, NTP_64_URI, Ntp56Extension, Ntp64Extension,
37};
38use sansio::Protocol;
39use shared::error::Error;
40use shared::marshal::Marshal;
41use shared::time::{SystemInstant, near_leap_second};
42use std::collections::{HashMap, VecDeque};
43use std::time::{Duration, Instant};
44
45/// Where [`NtpTimestampInterceptor`] sits in the default set: `Slot::Custom(1_850)`.
46pub const NTP_TIMESTAMP_SLOT: usize = 1_850;
47
48/// How long from a stream's first packet every packet carries the timestamp, by default.
49pub const NTP_TIMESTAMP_INITIAL_WINDOW: Duration = Duration::from_secs(5);
50
51/// How often a frame carries the timestamp after the initial window, by default.
52pub const NTP_TIMESTAMP_INTERVAL: Duration = Duration::from_secs(1);
53
54/// Builder for [`NtpTimestampInterceptor`].
55#[derive(Debug, Clone)]
56pub struct NtpTimestampBuilder {
57 initial_window: Duration,
58 interval: Duration,
59 wall_clock: Option<SystemInstant>,
60}
61
62impl Default for NtpTimestampBuilder {
63 fn default() -> Self {
64 Self {
65 initial_window: NTP_TIMESTAMP_INITIAL_WINDOW,
66 interval: NTP_TIMESTAMP_INTERVAL,
67 wall_clock: None,
68 }
69 }
70}
71
72impl NtpTimestampBuilder {
73 /// The defaults: every packet for 5 seconds, then a frame a second.
74 pub fn new() -> Self {
75 Self::default()
76 }
77
78 /// How long from a stream's first packet every packet carries the timestamp.
79 pub fn with_initial_window(mut self, window: Duration) -> Self {
80 self.initial_window = window;
81 self
82 }
83
84 /// How often, after the initial window, the packets of one frame carry it. `Duration::ZERO`
85 /// stamps every packet.
86 pub fn with_interval(mut self, interval: Duration) -> Self {
87 self.interval = interval;
88 self
89 }
90
91 /// The wall-clock anchor the timestamps derive from: the one the RTCP session's sender
92 /// reports use (RFC 6051 section 3.3). Default: the process-wide
93 /// [`SystemInstant::shared`]. Give one per peer connection for reproducible virtual-time
94 /// runs: two runs in one process otherwise map the same instants to NTP times as far apart
95 /// as the real time between them.
96 pub fn with_wall_clock(mut self, anchor: SystemInstant) -> Self {
97 self.wall_clock = Some(anchor);
98 self
99 }
100
101 /// Build the interceptor.
102 pub fn build(self) -> NtpTimestampInterceptor {
103 NtpTimestampInterceptor {
104 initial_window: self.initial_window,
105 interval: self.interval,
106 wall_clock: self.wall_clock,
107 streams: HashMap::new(),
108 first: Default::default(),
109 read_queue: VecDeque::new(),
110 write_queue: VecDeque::new(),
111 }
112 }
113}
114
115/// The extension a stream negotiated: its id and whether it is the 56-bit variant.
116#[derive(Debug, Clone, Copy)]
117struct Stamped {
118 id: u8,
119 short: bool,
120 first_packet: Option<Instant>,
121 /// The RTP timestamp of the last frame stamped after the initial window, and when.
122 last_frame: Option<(u32, Instant)>,
123}
124
125/// Stamps an RFC 6051 NTP-format timestamp on the packets of local streams that negotiated
126/// `ntp-64` or `ntp-56`; see the `ntp_timestamp` module's source documentation for which packets.
127pub struct NtpTimestampInterceptor {
128 initial_window: Duration,
129 interval: Duration,
130 /// [`NtpTimestampBuilder::with_wall_clock`].
131 wall_clock: Option<SystemInstant>,
132 /// By media SSRC.
133 streams: HashMap<u32, Stamped>,
134 /// What each recent packet left with (the extension's value, or none): a packet that
135 /// passes again (a retransmission sent as it was, no RTX negotiated) leaves with the
136 /// same. See [`crate::first_transmission`].
137 first: crate::first_transmission::FirstTransmissions<Option<bytes::Bytes>>,
138 read_queue: VecDeque<TaggedPacket>,
139 write_queue: VecDeque<TaggedPacket>,
140}
141
142impl NtpTimestampInterceptor {
143 /// An interceptor with the default windows.
144 pub fn new() -> Self {
145 NtpTimestampBuilder::new().build()
146 }
147
148 /// Whether the packet of RTP timestamp `timestamp` of `stream` sent at `now` carries it.
149 fn wanted(&self, stream: &mut Stamped, timestamp: u32, now: Instant) -> bool {
150 let first = *stream.first_packet.get_or_insert(now);
151 if now.saturating_duration_since(first) < self.initial_window {
152 return true;
153 }
154 match stream.last_frame {
155 Some((frame, _)) if frame == timestamp => true,
156 Some((_, at)) if now.saturating_duration_since(at) < self.interval => false,
157 _ => {
158 stream.last_frame = Some((timestamp, now));
159 true
160 }
161 }
162 }
163}
164
165impl Default for NtpTimestampInterceptor {
166 fn default() -> Self {
167 Self::new()
168 }
169}
170
171impl Protocol<TaggedPacket, TaggedPacket, ()> for NtpTimestampInterceptor {
172 type Rout = TaggedPacket;
173 type Wout = TaggedPacket;
174 type Eout = ();
175 type Error = Error;
176 type Time = Instant;
177
178 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
179 self.read_queue.push_back(msg);
180 Ok(())
181 }
182
183 fn poll_read(&mut self) -> Option<Self::Rout> {
184 self.read_queue.pop_front()
185 }
186
187 fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
188 // A retransmission keeps the header extensions of its first transmission: an RTX
189 // packet carries the original's (the NACK responder copies them, and this one was
190 // not among them yet), and a packet sent again as it was (no RTX negotiated) leaves
191 // with the timestamp its first transmission was given, or without one as that did.
192 // Anything else would make it a different packet under the SRTP index of the first
193 // transmission, which the SRTP sender refuses (RFC 3711 section 3.3.1).
194 let retransmission = msg
195 .message
196 .attributes
197 .iter()
198 .any(|attribute| matches!(attribute, Attribute::Retransmission));
199 if let Packet::Rtp(packet) = &mut msg.message.packet
200 && let Some(mut stream) = self.streams.get(&packet.header.ssrc).copied()
201 {
202 let (ssrc, sequence_number) = (packet.header.ssrc, packet.header.sequence_number);
203 if retransmission {
204 if let Some(Some(value)) = self.first.of(ssrc, sequence_number) {
205 let _ = packet
206 .header
207 .set_extension_upgrading(stream.id, value.clone());
208 }
209 } else {
210 let mut written = None;
211 let ntp = self
212 .wall_clock
213 .unwrap_or_else(|| SystemInstant::shared(msg.now))
214 .ntp(msg.now);
215 // RFC 7164 section 5: "generating or using NTP timestamps during the entire
216 // last second of a day on which a positive leap second has been scheduled
217 // SHOULD be avoided". In the two seconds around the end of a month (section
218 // 5.1's assumption, as for sender reports) no packet is stamped; the schedule
219 // of the stamped frames is left as it was.
220 if !near_leap_second(ntp)
221 && self.wanted(&mut stream, packet.header.timestamp, msg.now)
222 {
223 let value = if stream.short {
224 Ntp56Extension::new(ntp).marshal()
225 } else {
226 Ntp64Extension { ntp_time: ntp }.marshal()
227 };
228 if let Ok(value) = value {
229 let value = value.freeze();
230 let _ = packet
231 .header
232 .set_extension_upgrading(stream.id, value.clone());
233 written = Some(value);
234 }
235 }
236 self.first.remember(ssrc, sequence_number, written);
237 self.streams.insert(ssrc, stream);
238 }
239 }
240 self.write_queue.push_back(msg);
241 Ok(())
242 }
243
244 fn poll_write(&mut self) -> Option<Self::Wout> {
245 self.write_queue.pop_front()
246 }
247
248 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
249 Ok(())
250 }
251
252 fn poll_timeout(&mut self) -> Option<Self::Time> {
253 None
254 }
255}
256
257impl Interceptor for NtpTimestampInterceptor {
258 fn bind_local_stream(&mut self, info: &StreamInfo) {
259 let id = |uri: &str| {
260 info.rtp_header_extensions
261 .iter()
262 .find(|ext| ext.uri == uri)
263 .and_then(|ext| u8::try_from(ext.id).ok())
264 .filter(|id| *id != 0)
265 };
266 let negotiated = id(NTP_64_URI)
267 .map(|id| (id, false))
268 .or_else(|| id(NTP_56_URI).map(|id| (id, true)));
269 match negotiated {
270 Some((id, short)) => {
271 self.streams.entry(info.ssrc).or_insert(Stamped {
272 id,
273 short,
274 first_packet: None,
275 last_frame: None,
276 });
277 }
278 None => {
279 self.streams.remove(&info.ssrc);
280 }
281 }
282 }
283
284 fn unbind_local_stream(&mut self, info: &StreamInfo) {
285 self.streams.remove(&info.ssrc);
286 self.first.forget(info.ssrc);
287 }
288
289 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
290
291 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
292}