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