rtci_interceptor/
ntp_timestamp.rs1use 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
43pub const NTP_TIMESTAMP_SLOT: usize = 1_850;
45
46pub const NTP_TIMESTAMP_INITIAL_WINDOW: Duration = Duration::from_secs(5);
48
49pub const NTP_TIMESTAMP_INTERVAL: Duration = Duration::from_secs(1);
51
52#[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 pub fn new() -> Self {
73 Self::default()
74 }
75
76 pub fn with_initial_window(mut self, window: Duration) -> Self {
78 self.initial_window = window;
79 self
80 }
81
82 pub fn with_interval(mut self, interval: Duration) -> Self {
85 self.interval = interval;
86 self
87 }
88
89 pub fn with_wall_clock(mut self, anchor: SystemInstant) -> Self {
95 self.wall_clock = Some(anchor);
96 self
97 }
98
99 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#[derive(Debug, Clone, Copy)]
114struct Stamped {
115 id: u8,
116 short: bool,
117 first_packet: Option<Instant>,
118 last_frame: Option<(u32, Instant)>,
120}
121
122pub struct NtpTimestampInterceptor {
125 initial_window: Duration,
126 interval: Duration,
127 wall_clock: Option<SystemInstant>,
129 streams: HashMap<u32, Stamped>,
131 read_queue: VecDeque<TaggedPacket>,
132 write_queue: VecDeque<TaggedPacket>,
133}
134
135impl NtpTimestampInterceptor {
136 pub fn new() -> Self {
138 NtpTimestampBuilder::new().build()
139 }
140
141 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 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}