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 sansio::Protocol;
20use shared::error::Error;
21use std::collections::{HashSet, VecDeque};
22use std::sync::{Arc, Mutex, MutexGuard};
23use std::time::Instant;
24
25/// The most wire images held for an encoder that is not taking them.
26///
27/// An encoder takes them every time the chain is polled, so more than a few is already unusual;
28/// the bound is there so a chain whose encoder was dropped does not grow without limit. The
29/// oldest go first: FEC for packets that left long ago is worth least.
30pub const MAX_HELD_WIRE_IMAGES: usize = 1024;
31
32#[derive(Default)]
33struct Shared {
34    watched: HashSet<u32>,
35    images: VecDeque<TaggedPacket>,
36    dropped: u64,
37}
38
39fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
40    // Nothing is left half-done under this lock, so a panic elsewhere does not spoil the state.
41    shared
42        .lock()
43        .unwrap_or_else(|poisoned| poisoned.into_inner())
44}
45
46/// A tap and the handle that reads it.
47///
48/// Register the tap at [`Slot::FecWireImage`](crate::Slot::FecWireImage); give the handle to the
49/// encoder. The FEC send interceptors build the pair themselves
50/// ([`FlexFec03SendInterceptor::wire_tap`](crate::FlexFec03SendInterceptor::wire_tap)); this is
51/// for an encoder of your own.
52pub fn wire_image_tap() -> (WireImageTap, WireImages) {
53    let shared = Arc::new(Mutex::new(Shared::default()));
54    (
55        WireImageTap {
56            shared: shared.clone(),
57            read_queue: VecDeque::new(),
58            write_queue: VecDeque::new(),
59        },
60        WireImages { shared },
61    )
62}
63
64/// The reading end of a [`WireImageTap`].
65#[derive(Clone)]
66pub struct WireImages {
67    shared: Arc<Mutex<Shared>>,
68}
69
70impl WireImages {
71    /// Start copying the packets `ssrc` sends.
72    pub fn watch(&self, ssrc: u32) {
73        lock(&self.shared).watched.insert(ssrc);
74    }
75
76    /// Stop copying the packets `ssrc` sends. Images already held stay until taken.
77    pub fn unwatch(&self, ssrc: u32) {
78        lock(&self.shared).watched.remove(&ssrc);
79    }
80
81    /// The packets that left since the last call, oldest first, each with the instant it was
82    /// released to the network.
83    pub fn take(&self) -> Vec<TaggedPacket> {
84        lock(&self.shared).images.drain(..).collect()
85    }
86
87    /// How many images were given up because nothing took them.
88    pub fn dropped(&self) -> u64 {
89        lock(&self.shared).dropped
90    }
91}
92
93/// Copies departing RTP packets of the watched streams, as they leave. Changes nothing: every
94/// packet passes through as it came.
95pub struct WireImageTap {
96    shared: Arc<Mutex<Shared>>,
97    read_queue: VecDeque<TaggedPacket>,
98    write_queue: VecDeque<TaggedPacket>,
99}
100
101impl Protocol<TaggedPacket, TaggedPacket, ()> for WireImageTap {
102    type Rout = TaggedPacket;
103    type Wout = TaggedPacket;
104    type Eout = ();
105    type Error = Error;
106    type Time = Instant;
107
108    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
109        self.read_queue.push_back(msg);
110        Ok(())
111    }
112
113    fn poll_read(&mut self) -> Option<Self::Rout> {
114        self.read_queue.pop_front()
115    }
116
117    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
118        if let Packet::Rtp(rtp_packet) = &msg.message.packet {
119            let mut shared = lock(&self.shared);
120            if shared.watched.contains(&rtp_packet.header.ssrc) {
121                if shared.images.len() >= MAX_HELD_WIRE_IMAGES {
122                    shared.images.pop_front();
123                    shared.dropped += 1;
124                }
125                shared.images.push_back(TaggedPacket {
126                    now: msg.now,
127                    transport: msg.transport,
128                    message: msg.message.clone(),
129                });
130            }
131        }
132        self.write_queue.push_back(msg);
133        Ok(())
134    }
135
136    fn poll_write(&mut self) -> Option<Self::Wout> {
137        self.write_queue.pop_front()
138    }
139
140    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
141        Ok(())
142    }
143
144    fn poll_timeout(&mut self) -> Option<Self::Time> {
145        None
146    }
147}
148
149impl Interceptor for WireImageTap {
150    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
151    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
152    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
153    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use crate::AttributedPacket;
160    use shared::TransportContext;
161
162    fn rtp(ssrc: u32, sequence_number: u16) -> TaggedPacket {
163        TaggedPacket {
164            now: Instant::now(),
165            transport: TransportContext::default(),
166            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
167                header: rtp::header::Header {
168                    version: 2,
169                    ssrc,
170                    sequence_number,
171                    ..Default::default()
172                },
173                payload: vec![1, 2, 3].into(),
174            })),
175        }
176    }
177
178    fn sequence_numbers(images: &[TaggedPacket]) -> Vec<u16> {
179        images
180            .iter()
181            .filter_map(|image| match &image.message.packet {
182                Packet::Rtp(rtp) => Some(rtp.header.sequence_number),
183                Packet::Rtcp(_) => None,
184            })
185            .collect()
186    }
187
188    #[test]
189    fn only_watched_streams_are_copied_and_every_packet_passes_through() {
190        let (mut tap, images) = wire_image_tap();
191        images.watch(1);
192
193        tap.handle_write(rtp(1, 10)).unwrap();
194        tap.handle_write(rtp(2, 20)).unwrap();
195        tap.handle_write(rtp(1, 11)).unwrap();
196
197        let mut passed = Vec::new();
198        while let Some(out) = tap.poll_write() {
199            passed.push(out);
200        }
201        assert_eq!(vec![10, 20, 11], sequence_numbers(&passed));
202        assert_eq!(vec![10, 11], sequence_numbers(&images.take()));
203        assert!(images.take().is_empty(), "taken once");
204    }
205
206    #[test]
207    fn an_unwatched_stream_is_no_longer_copied() {
208        let (mut tap, images) = wire_image_tap();
209        images.watch(1);
210        images.unwatch(1);
211
212        tap.handle_write(rtp(1, 10)).unwrap();
213        assert!(images.take().is_empty());
214    }
215
216    #[test]
217    fn images_nothing_takes_are_bounded() {
218        let (mut tap, images) = wire_image_tap();
219        images.watch(1);
220
221        for sequence_number in 0..(MAX_HELD_WIRE_IMAGES as u16 + 5) {
222            tap.handle_write(rtp(1, sequence_number)).unwrap();
223            while tap.poll_write().is_some() {}
224        }
225
226        let held = images.take();
227        assert_eq!(MAX_HELD_WIRE_IMAGES, held.len());
228        assert_eq!(5, sequence_numbers(&held)[0], "the oldest were given up");
229        assert_eq!(5, images.dropped());
230    }
231}