Skip to main content

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            read_queue: VecDeque::new(),
107            write_queue: VecDeque::new(),
108        }
109    }
110}
111
112/// The extension a stream negotiated: its id and whether it is the 56-bit variant.
113#[derive(Debug, Clone, Copy)]
114struct Stamped {
115    id: u8,
116    short: bool,
117    first_packet: Option<Instant>,
118    /// The RTP timestamp of the last frame stamped after the initial window, and when.
119    last_frame: Option<(u32, Instant)>,
120}
121
122/// Stamps an RFC 6051 NTP-format timestamp on the packets of local streams that negotiated
123/// `ntp-64` or `ntp-56`; see the `ntp_timestamp` module's source documentation for which packets.
124pub struct NtpTimestampInterceptor {
125    initial_window: Duration,
126    interval: Duration,
127    /// [`NtpTimestampBuilder::with_wall_clock`].
128    wall_clock: Option<SystemInstant>,
129    /// By media SSRC.
130    streams: HashMap<u32, Stamped>,
131    read_queue: VecDeque<TaggedPacket>,
132    write_queue: VecDeque<TaggedPacket>,
133}
134
135impl NtpTimestampInterceptor {
136    /// An interceptor with the default windows.
137    pub fn new() -> Self {
138        NtpTimestampBuilder::new().build()
139    }
140
141    /// Whether the packet of RTP timestamp `timestamp` of `stream` sent at `now` carries it.
142    fn wanted(&self, stream: &mut Stamped, timestamp: u32, now: Instant) -> bool {
143        let first = *stream.first_packet.get_or_insert(now);
144        if now.saturating_duration_since(first) < self.initial_window {
145            return true;
146        }
147        match stream.last_frame {
148            Some((frame, _)) if frame == timestamp => true,
149            Some((_, at)) if now.saturating_duration_since(at) < self.interval => false,
150            _ => {
151                stream.last_frame = Some((timestamp, now));
152                true
153            }
154        }
155    }
156}
157
158impl Default for NtpTimestampInterceptor {
159    fn default() -> Self {
160        Self::new()
161    }
162}
163
164impl Protocol<TaggedPacket, TaggedPacket, ()> for NtpTimestampInterceptor {
165    type Rout = TaggedPacket;
166    type Wout = TaggedPacket;
167    type Eout = ();
168    type Error = Error;
169    type Time = Instant;
170
171    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
172        self.read_queue.push_back(msg);
173        Ok(())
174    }
175
176    fn poll_read(&mut self) -> Option<Self::Rout> {
177        self.read_queue.pop_front()
178    }
179
180    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
181        // A retransmission keeps the header extensions of its first transmission.
182        let retransmission = msg
183            .message
184            .attributes
185            .iter()
186            .any(|attribute| matches!(attribute, Attribute::Retransmission));
187        if let Packet::Rtp(packet) = &mut msg.message.packet
188            && !retransmission
189            && let Some(mut stream) = self.streams.get(&packet.header.ssrc).copied()
190        {
191            if self.wanted(&mut stream, packet.header.timestamp, msg.now) {
192                let ntp = self
193                    .wall_clock
194                    .unwrap_or_else(|| SystemInstant::shared(msg.now))
195                    .ntp(msg.now);
196                let value = if stream.short {
197                    Ntp56Extension::new(ntp).marshal()
198                } else {
199                    Ntp64Extension { ntp_time: ntp }.marshal()
200                };
201                if let Ok(value) = value {
202                    let _ = packet
203                        .header
204                        .set_extension_upgrading(stream.id, value.freeze());
205                }
206            }
207            self.streams.insert(packet.header.ssrc, stream);
208        }
209        self.write_queue.push_back(msg);
210        Ok(())
211    }
212
213    fn poll_write(&mut self) -> Option<Self::Wout> {
214        self.write_queue.pop_front()
215    }
216
217    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
218        Ok(())
219    }
220
221    fn poll_timeout(&mut self) -> Option<Self::Time> {
222        None
223    }
224}
225
226impl Interceptor for NtpTimestampInterceptor {
227    fn bind_local_stream(&mut self, info: &StreamInfo) {
228        let id = |uri: &str| {
229            info.rtp_header_extensions
230                .iter()
231                .find(|ext| ext.uri == uri)
232                .and_then(|ext| u8::try_from(ext.id).ok())
233                .filter(|id| *id != 0)
234        };
235        let negotiated = id(NTP_64_URI)
236            .map(|id| (id, false))
237            .or_else(|| id(NTP_56_URI).map(|id| (id, true)));
238        match negotiated {
239            Some((id, short)) => {
240                self.streams.entry(info.ssrc).or_insert(Stamped {
241                    id,
242                    short,
243                    first_packet: None,
244                    last_frame: None,
245                });
246            }
247            None => {
248                self.streams.remove(&info.ssrc);
249            }
250        }
251    }
252
253    fn unbind_local_stream(&mut self, info: &StreamInfo) {
254        self.streams.remove(&info.ssrc);
255    }
256
257    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
258
259    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
260}