Skip to main content

rtci_interceptor/
wire_image.rs

1//! The packets a stream sent, as they left: what an FEC encoder protects.
2//!
3//! FEC protects the source packets as they are on the wire: the receiver XORs the packets that
4//! arrived, so the sender has to XOR the same bytes (RFC 8627 section 4.1, RFC 5109 section 8).
5//! An encoder is a generator and sits above the pacer, where a media packet is not final yet: the
6//! TWCC sender below it writes the transport-wide sequence number into the packet, adding the
7//! header extension when the packet has none. An encoder that reads the packet at its own slot
8//! protects an image the receiver never sees.
9//!
10//! [`WireImageTap`] sits below everything that edits a departing packet
11//! ([`Slot::FecWireImage`](crate::Slot::FecWireImage)) and copies the packets of the streams an
12//! encoder asked for. The encoder, still at [`Slot::FecEncoder`](crate::Slot::FecEncoder), takes
13//! them from its [`WireImages`] handle the next time the chain polls it, and its repair packets
14//! travel the whole chain: paced, numbered and recorded like any other packet.
15
16use crate::Interceptor;
17use crate::stream_info::StreamInfo;
18use crate::{Packet, TaggedPacket};
19use bytes::Bytes;
20use sansio::Protocol;
21use shared::error::Error;
22use shared::marshal::Marshal;
23use std::collections::{HashMap, HashSet, VecDeque};
24use std::sync::{Arc, Mutex, MutexGuard};
25use std::time::Instant;
26
27/// The most wire images held for an encoder that is not taking them.
28///
29/// An encoder takes them every time the chain is polled, so more than a few is already unusual;
30/// the bound is there so a chain whose encoder was dropped does not grow without limit. The
31/// oldest go first: FEC for packets that left long ago is worth least.
32pub const MAX_HELD_WIRE_IMAGES: usize = 1024;
33
34/// The most wire images of one watched stream kept for its FlexFEC retransmissions
35/// ([`WireImages::retransmit_on`]): as many packets as the NACK responder's send buffer holds
36/// by default, so an image is kept for every packet a NACK can still be answered for.
37pub const MAX_RETRANSMISSION_IMAGES: usize = 1024;
38
39#[derive(Default)]
40struct Shared {
41    watched: HashSet<u32>,
42    images: VecDeque<TaggedPacket>,
43    dropped: u64,
44    /// Repair streams whose FlexFEC retransmissions (R=1) get the wire image of the packet
45    /// they carry.
46    retransmission_streams: HashSet<u32>,
47    /// The latest wire images of each watched stream, by sequence number, for those
48    /// retransmissions (kept only while a repair stream is registered).
49    kept: HashMap<u32, (HashMap<u16, Bytes>, VecDeque<u16>)>,
50}
51
52impl Shared {
53    fn keep(&mut self, packet: &rtp::Packet) {
54        let Ok(image) = packet.marshal() else {
55            return;
56        };
57        let (images, order) = self.kept.entry(packet.header.ssrc).or_default();
58        let sequence_number = packet.header.sequence_number;
59        if images.insert(sequence_number, image.freeze()).is_none() {
60            order.push_back(sequence_number);
61        }
62        while order.len() > MAX_RETRANSMISSION_IMAGES {
63            if let Some(oldest) = order.pop_front() {
64                images.remove(&oldest);
65            }
66        }
67    }
68
69    /// The wire image a FlexFEC retransmission on a registered repair stream is to carry:
70    /// that of the source packet its payload names (RFC 8627 section 4.2.2.3: the FEC header
71    /// of a retransmission is the source packet's RTP header, R=1 F=0, followed by the rest of
72    /// the packet).
73    fn retransmitted_image(&self, packet: &rtp::Packet) -> Option<Bytes> {
74        if !self.retransmission_streams.contains(&packet.header.ssrc) {
75            return None;
76        }
77        let payload = &packet.payload;
78        if payload.len() < 12 || payload[0] & 0xC0 != 0x80 {
79            return None;
80        }
81        let ssrc = u32::from_be_bytes([payload[8], payload[9], payload[10], payload[11]]);
82        let sequence_number = u16::from_be_bytes([payload[2], payload[3]]);
83        self.kept.get(&ssrc)?.0.get(&sequence_number).cloned()
84    }
85}
86
87fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
88    // Nothing is left half-done under this lock, so a panic elsewhere does not spoil the state.
89    shared
90        .lock()
91        .unwrap_or_else(|poisoned| poisoned.into_inner())
92}
93
94/// A tap and the handle that reads it.
95///
96/// Register the tap at [`Slot::FecWireImage`](crate::Slot::FecWireImage); give the handle to the
97/// encoder. The FEC send interceptors build the pair themselves
98/// ([`FlexFec03SendInterceptor::wire_tap`](crate::FlexFec03SendInterceptor::wire_tap)); this is
99/// for an encoder of your own.
100pub fn wire_image_tap() -> (WireImageTap, WireImages) {
101    let shared = Arc::new(Mutex::new(Shared::default()));
102    (
103        WireImageTap {
104            shared: shared.clone(),
105            read_queue: VecDeque::new(),
106            write_queue: VecDeque::new(),
107        },
108        WireImages { shared },
109    )
110}
111
112/// The reading end of a [`WireImageTap`].
113#[derive(Clone)]
114pub struct WireImages {
115    shared: Arc<Mutex<Shared>>,
116}
117
118impl WireImages {
119    /// Start copying the packets `ssrc` sends.
120    pub fn watch(&self, ssrc: u32) {
121        lock(&self.shared).watched.insert(ssrc);
122    }
123
124    /// Stop copying the packets `ssrc` sends. Images already held stay until taken.
125    pub fn unwatch(&self, ssrc: u32) {
126        let mut shared = lock(&self.shared);
127        shared.watched.remove(&ssrc);
128        shared.kept.remove(&ssrc);
129    }
130
131    /// Give every FlexFEC retransmission (R=1, RFC 8627 section 4.2.2.3) that leaves on the
132    /// repair stream `repair_ssrc` the wire image of the source packet it carries: the packet
133    /// as it left, header extensions written below the generator included, which is what the
134    /// repair packets protect and what the receiver XORs them with. A retransmission is made
135    /// above the extension writers (the NACK responder buffers the packet before the TWCC
136    /// sender numbers it); without this its image differs from the one that left, and a
137    /// receiver that rebuilds a neighbour with it rebuilds garbage.
138    pub fn retransmit_on(&self, repair_ssrc: u32) {
139        lock(&self.shared)
140            .retransmission_streams
141            .insert(repair_ssrc);
142    }
143
144    /// Stop rewriting the retransmissions of `repair_ssrc`.
145    pub fn stop_retransmit_on(&self, repair_ssrc: u32) {
146        let mut shared = lock(&self.shared);
147        shared.retransmission_streams.remove(&repair_ssrc);
148        if shared.retransmission_streams.is_empty() {
149            shared.kept.clear();
150        }
151    }
152
153    /// The packets that left since the last call, oldest first, each with the instant it was
154    /// released to the network.
155    pub fn take(&self) -> Vec<TaggedPacket> {
156        lock(&self.shared).images.drain(..).collect()
157    }
158
159    /// How many images were given up because nothing took them.
160    pub fn dropped(&self) -> u64 {
161        lock(&self.shared).dropped
162    }
163}
164
165/// Copies departing RTP packets of the watched streams, as they leave. Changes nothing: every
166/// packet passes through as it came.
167pub struct WireImageTap {
168    shared: Arc<Mutex<Shared>>,
169    read_queue: VecDeque<TaggedPacket>,
170    write_queue: VecDeque<TaggedPacket>,
171}
172
173impl Protocol<TaggedPacket, TaggedPacket, ()> for WireImageTap {
174    type Rout = TaggedPacket;
175    type Wout = TaggedPacket;
176    type Eout = ();
177    type Error = Error;
178    type Time = Instant;
179
180    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
181        self.read_queue.push_back(msg);
182        Ok(())
183    }
184
185    fn poll_read(&mut self) -> Option<Self::Rout> {
186        self.read_queue.pop_front()
187    }
188
189    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
190        let retransmission = msg.message.has(&crate::Attribute::Retransmission);
191        if let Packet::Rtp(rtp_packet) = &mut msg.message.packet {
192            let mut shared = lock(&self.shared);
193            if let Some(image) = shared.retransmitted_image(rtp_packet) {
194                rtp_packet.payload = image;
195            }
196            if shared.watched.contains(&rtp_packet.header.ssrc)
197                && !shared.retransmission_streams.is_empty()
198                && !retransmission
199            {
200                shared.keep(rtp_packet);
201            }
202        }
203        if let Packet::Rtp(rtp_packet) = &msg.message.packet {
204            let mut shared = lock(&self.shared);
205            if shared.watched.contains(&rtp_packet.header.ssrc) {
206                if shared.images.len() >= MAX_HELD_WIRE_IMAGES {
207                    shared.images.pop_front();
208                    shared.dropped += 1;
209                }
210                shared.images.push_back(TaggedPacket {
211                    now: msg.now,
212                    transport: msg.transport,
213                    message: msg.message.clone(),
214                });
215            }
216        }
217        self.write_queue.push_back(msg);
218        Ok(())
219    }
220
221    fn poll_write(&mut self) -> Option<Self::Wout> {
222        self.write_queue.pop_front()
223    }
224
225    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
226        Ok(())
227    }
228
229    fn poll_timeout(&mut self) -> Option<Self::Time> {
230        None
231    }
232}
233
234impl Interceptor for WireImageTap {
235    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
236    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
237    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
238    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use crate::AttributedPacket;
245    use shared::TransportContext;
246
247    fn rtp(ssrc: u32, sequence_number: u16) -> TaggedPacket {
248        TaggedPacket {
249            now: Instant::now(),
250            transport: TransportContext::default(),
251            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
252                header: rtp::header::Header {
253                    version: 2,
254                    ssrc,
255                    sequence_number,
256                    ..Default::default()
257                },
258                payload: vec![1, 2, 3].into(),
259            })),
260        }
261    }
262
263    fn sequence_numbers(images: &[TaggedPacket]) -> Vec<u16> {
264        images
265            .iter()
266            .filter_map(|image| match &image.message.packet {
267                Packet::Rtp(rtp) => Some(rtp.header.sequence_number),
268                Packet::Rtcp(_) => None,
269            })
270            .collect()
271    }
272
273    #[test]
274    fn only_watched_streams_are_copied_and_every_packet_passes_through() {
275        let (mut tap, images) = wire_image_tap();
276        images.watch(1);
277
278        tap.handle_write(rtp(1, 10)).unwrap();
279        tap.handle_write(rtp(2, 20)).unwrap();
280        tap.handle_write(rtp(1, 11)).unwrap();
281
282        let mut passed = Vec::new();
283        while let Some(out) = tap.poll_write() {
284            passed.push(out);
285        }
286        assert_eq!(vec![10, 20, 11], sequence_numbers(&passed));
287        assert_eq!(vec![10, 11], sequence_numbers(&images.take()));
288        assert!(images.take().is_empty(), "taken once");
289    }
290
291    #[test]
292    fn an_unwatched_stream_is_no_longer_copied() {
293        let (mut tap, images) = wire_image_tap();
294        images.watch(1);
295        images.unwatch(1);
296
297        tap.handle_write(rtp(1, 10)).unwrap();
298        assert!(images.take().is_empty());
299    }
300
301    /// RFC 8627 section 4.2.2.3: a FlexFEC retransmission carries the source packet, and the
302    /// receiver XORs repair packets with it as with any source packet it holds. The NACK
303    /// responder makes it from its buffer, above the TWCC sender that writes the
304    /// transport-wide sequence number into the packet; the tap, below it, puts the packet as it
305    /// left into the retransmission. (Without this, an SFrame call's packet rebuilt beside a
306    /// retransmitted one came out corrupt: diagnostic run 46341015789.) Parity packets on the
307    /// repair stream, and packets of a repair stream not registered, pass unchanged.
308    #[test]
309    fn a_flexfec_retransmission_leaves_with_the_wire_image_of_its_packet() {
310        let (mut tap, images) = wire_image_tap();
311        images.watch(1);
312        images.retransmit_on(9);
313        // The source packet as it left: the TWCC sender wrote its extension.
314        let mut left = rtp(1, 10);
315        if let Packet::Rtp(packet) = &mut left.message.packet {
316            packet.header.extension = true;
317            packet.header.extension_profile = 0xBEDE;
318            packet
319                .header
320                .set_extension(3, bytes::Bytes::from_static(&[0, 42]))
321                .unwrap();
322        }
323        let image = match &left.message.packet {
324            Packet::Rtp(packet) => packet.marshal().unwrap().freeze(),
325            Packet::Rtcp(_) => unreachable!(),
326        };
327        tap.handle_write(left).unwrap();
328        // The retransmission as the responder made it: the buffered packet, no extension.
329        let buffered = match &rtp(1, 10).message.packet {
330            Packet::Rtp(packet) => packet.marshal().unwrap().freeze(),
331            Packet::Rtcp(_) => unreachable!(),
332        };
333        assert_ne!(buffered, image);
334        let repair = |payload: bytes::Bytes, ssrc: u32| {
335            let mut packet = rtp(ssrc, 500);
336            if let Packet::Rtp(rtp) = &mut packet.message.packet {
337                rtp.payload = payload;
338            }
339            packet
340        };
341        tap.handle_write(repair(buffered.clone(), 9)).unwrap();
342        // A parity packet (R=0) and an unregistered repair stream are left alone.
343        let mut parity = buffered.to_vec();
344        parity[0] &= 0x3F;
345        tap.handle_write(repair(parity.clone().into(), 9)).unwrap();
346        tap.handle_write(repair(buffered.clone(), 8)).unwrap();
347
348        let payloads: Vec<bytes::Bytes> = std::iter::from_fn(|| tap.poll_write())
349            .skip(1)
350            .map(|out| match out.message.packet {
351                Packet::Rtp(packet) => packet.payload,
352                Packet::Rtcp(_) => unreachable!(),
353            })
354            .collect();
355        assert_eq!(payloads[0], image, "the packet as it left");
356        assert_eq!(payloads[1], bytes::Bytes::from(parity), "parity unchanged");
357        assert_eq!(payloads[2], buffered, "not registered: unchanged");
358    }
359
360    #[test]
361    fn images_nothing_takes_are_bounded() {
362        let (mut tap, images) = wire_image_tap();
363        images.watch(1);
364
365        for sequence_number in 0..(MAX_HELD_WIRE_IMAGES as u16 + 5) {
366            tap.handle_write(rtp(1, sequence_number)).unwrap();
367            while tap.poll_write().is_some() {}
368        }
369
370        let held = images.take();
371        assert_eq!(MAX_HELD_WIRE_IMAGES, held.len());
372        assert_eq!(5, sequence_numbers(&held)[0], "the oldest were given up");
373        assert_eq!(5, images.dropped());
374    }
375}