Skip to main content

rtci_interceptor/
fec_session.rs

1//! The SSRCs of a FEC session of its own (RFC 5109 section 14.1), on the wire and in a chain.
2//!
3//! RFC 5109 section 7.2: "The SSRC value SHALL be the same as the SSRC value of the media
4//! stream it protects", and section 14.1: "the FEC and the payload MUST NOT be multiplexed by
5//! SSRC into one single RTP session since they always have the same SSRC". So a separate FEC
6//! stream is a second RTP session, on a transport of its own, in which the media stream's
7//! SSRC names the FEC stream.
8//!
9//! A chain serves every RTP session of a connection and keys what it keeps on the SSRC: the
10//! buffers a NACK is answered from, the members of an RTCP session, the send history of a
11//! congestion controller, the session a stream is in ([`PerRtpSession`](crate::PerRtpSession)).
12//! One SSRC that is two streams cannot pass through it. [`FecSessionSsrcMap`] is the
13//! boundary: inside the chain every SSRC of a FEC session is the wire SSRC XOR a key, and
14//! whoever drives the chain applies the map to each RTP and RTCP packet of a FEC session's
15//! transport, on the way in and on the way out. XOR with one key is its own inverse and maps
16//! distinct SSRCs to distinct SSRCs, so the map needs no table: nothing a peer sends can make
17//! it grow.
18//!
19//! The media stream names its FEC stream's chain SSRC in
20//! [`StreamInfo::fec_session`](crate::StreamInfo::fec_session); the FEC stream is bound as a
21//! stream of its own under that SSRC, in the FEC session.
22
23use rtcp::extended_report::{DLRRReportBlock, ExtendedReport, ReceiverReferenceTimeReportBlock};
24use rtcp::goodbye::Goodbye;
25use rtcp::receiver_report::ReceiverReport;
26use rtcp::sender_report::SenderReport;
27use rtcp::source_description::SourceDescription;
28use rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport;
29use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
30
31/// Maps the SSRCs of a FEC session (RFC 5109 section 14.1) between the wire and the chain; see
32/// the `fec_session` module's source documentation.
33///
34/// # Example
35///
36/// ```
37/// use rtci_interceptor::FecSessionSsrcMap;
38///
39/// let map = FecSessionSsrcMap::new(0x5109_5109);
40/// let media_ssrc = 0x1234_5678;
41/// let in_chain = map.map(media_ssrc);
42/// assert_ne!(in_chain, media_ssrc);
43/// // The same map takes a packet in and out.
44/// assert_eq!(map.map(in_chain), media_ssrc);
45/// ```
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct FecSessionSsrcMap {
48    key: u32,
49}
50
51impl FecSessionSsrcMap {
52    /// A map with `key`. Zero would leave every SSRC as it is, the very collision the map is
53    /// for, so it is replaced by 1.
54    pub fn new(key: u32) -> Self {
55        Self { key: key.max(1) }
56    }
57
58    /// A map with a random key.
59    pub fn random() -> Self {
60        Self::new(rand::random())
61    }
62
63    /// The key.
64    pub fn key(&self) -> u32 {
65        self.key
66    }
67
68    /// The chain's SSRC for a wire SSRC of the FEC session, and the wire SSRC for the chain's.
69    pub fn map(&self, ssrc: u32) -> u32 {
70        ssrc ^ self.key
71    }
72
73    /// Maps the SSRC of an RTP packet of the FEC session. A FEC packet has no CSRC list
74    /// (RFC 5109 section 7.2 uses the fields "according to RFC 3550": a FEC packet is not a
75    /// mixer's), and one that came with entries keeps them as they are.
76    pub fn map_rtp(&self, packet: &mut rtp::Packet) {
77        packet.header.ssrc = self.map(packet.header.ssrc);
78    }
79
80    /// Maps every SSRC of a compound RTCP packet of the FEC session: sender and receiver
81    /// reports with their report blocks, source descriptions, goodbyes, transport-wide and
82    /// RFC 8888 congestion control feedback, and the receiver reference time and DLRR blocks
83    /// of an extended report.
84    ///
85    /// Any other packet is left out of the result: feedback about pictures, bit rates or
86    /// retransmission has no meaning for a FEC stream, and a packet passed on with its SSRCs
87    /// unmapped would name another stream of the connection. An extended report keeps the
88    /// blocks named above and is left out when none remains.
89    pub fn map_rtcp(&self, packets: &[Box<dyn rtcp::Packet>]) -> Vec<Box<dyn rtcp::Packet>> {
90        packets
91            .iter()
92            .filter_map(|packet| self.map_rtcp_packet(packet.as_ref()))
93            .collect()
94    }
95
96    fn map_rtcp_packet(&self, packet: &dyn rtcp::Packet) -> Option<Box<dyn rtcp::Packet>> {
97        let any = packet.as_any();
98        if let Some(report) = any.downcast_ref::<SenderReport>() {
99            let mut report = report.clone();
100            report.ssrc = self.map(report.ssrc);
101            for block in &mut report.reports {
102                block.ssrc = self.map(block.ssrc);
103            }
104            return Some(Box::new(report));
105        }
106        if let Some(report) = any.downcast_ref::<ReceiverReport>() {
107            let mut report = report.clone();
108            report.ssrc = self.map(report.ssrc);
109            for block in &mut report.reports {
110                block.ssrc = self.map(block.ssrc);
111            }
112            return Some(Box::new(report));
113        }
114        if let Some(description) = any.downcast_ref::<SourceDescription>() {
115            let mut description = description.clone();
116            for chunk in &mut description.chunks {
117                chunk.source = self.map(chunk.source);
118            }
119            return Some(Box::new(description));
120        }
121        if let Some(goodbye) = any.downcast_ref::<Goodbye>() {
122            let mut goodbye = goodbye.clone();
123            for source in &mut goodbye.sources {
124                *source = self.map(*source);
125            }
126            return Some(Box::new(goodbye));
127        }
128        if let Some(feedback) = any.downcast_ref::<TransportLayerCc>() {
129            let mut feedback = feedback.clone();
130            feedback.sender_ssrc = self.map(feedback.sender_ssrc);
131            feedback.media_ssrc = self.map(feedback.media_ssrc);
132            return Some(Box::new(feedback));
133        }
134        if let Some(feedback) = any.downcast_ref::<CcFeedbackReport>() {
135            let mut feedback = feedback.clone();
136            feedback.sender_ssrc = self.map(feedback.sender_ssrc);
137            for block in &mut feedback.report_blocks {
138                block.media_ssrc = self.map(block.media_ssrc);
139            }
140            return Some(Box::new(feedback));
141        }
142        if let Some(report) = any.downcast_ref::<ExtendedReport>() {
143            let mut blocks: Vec<Box<dyn rtcp::Packet>> = Vec::new();
144            for block in &report.reports {
145                let any = block.as_any();
146                if any
147                    .downcast_ref::<ReceiverReferenceTimeReportBlock>()
148                    .is_some()
149                {
150                    blocks.push(block.clone());
151                } else if let Some(dlrr) = any.downcast_ref::<DLRRReportBlock>() {
152                    let mut dlrr = dlrr.clone();
153                    for report in &mut dlrr.reports {
154                        report.ssrc = self.map(report.ssrc);
155                    }
156                    blocks.push(Box::new(dlrr));
157                }
158            }
159            if blocks.is_empty() {
160                return None;
161            }
162            return Some(Box::new(ExtendedReport {
163                sender_ssrc: self.map(report.sender_ssrc),
164                reports: blocks,
165            }));
166        }
167        None
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use rtcp::extended_report::DLRRReport;
175    use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
176    use rtcp::reception_report::ReceptionReport;
177    use rtcp::source_description::{SdesType, SourceDescriptionChunk, SourceDescriptionItem};
178    use rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReportBlock;
179
180    const KEY: u32 = 0x5109_0141;
181    const MEDIA: u32 = 0x1111_2222;
182    const PEER: u32 = 0x3333_4444;
183
184    fn downcast<T: Clone + 'static>(packet: &dyn rtcp::Packet) -> T {
185        packet
186            .as_any()
187            .downcast_ref::<T>()
188            .expect("the packet keeps its type")
189            .clone()
190    }
191
192    #[test]
193    fn the_map_is_its_own_inverse_and_never_the_identity() {
194        for key in [0, 1, KEY, u32::MAX] {
195            let map = FecSessionSsrcMap::new(key);
196            for ssrc in [0, 1, MEDIA, PEER, u32::MAX] {
197                assert_ne!(map.map(ssrc), ssrc, "key {key:#x}");
198                assert_eq!(map.map(map.map(ssrc)), ssrc, "key {key:#x}");
199            }
200        }
201        assert_eq!(
202            FecSessionSsrcMap::new(0).key(),
203            1,
204            "a zero key maps nothing"
205        );
206        assert_ne!(FecSessionSsrcMap::random().key(), 0);
207    }
208
209    #[test]
210    fn distinct_ssrcs_stay_distinct() {
211        let map = FecSessionSsrcMap::new(KEY);
212        assert_ne!(map.map(MEDIA), map.map(PEER));
213        assert_eq!(map.map(MEDIA), MEDIA ^ KEY);
214    }
215
216    #[test]
217    fn an_rtp_packet_changes_only_its_ssrc() {
218        let map = FecSessionSsrcMap::new(KEY);
219        let original = rtp::Packet {
220            header: rtp::header::Header {
221                version: 2,
222                payload_type: 100,
223                sequence_number: 7,
224                timestamp: 9,
225                ssrc: MEDIA,
226                ..Default::default()
227            },
228            payload: bytes::Bytes::from_static(&[1, 2, 3]),
229        };
230        let mut packet = original.clone();
231        map.map_rtp(&mut packet);
232        assert_eq!(packet.header.ssrc, MEDIA ^ KEY);
233        packet.header.ssrc = MEDIA;
234        assert_eq!(packet, original);
235    }
236
237    #[test]
238    fn every_ssrc_of_the_reports_of_a_session_is_mapped() {
239        let map = FecSessionSsrcMap::new(KEY);
240        let block = ReceptionReport {
241            ssrc: PEER,
242            fraction_lost: 3,
243            ..Default::default()
244        };
245        let compound: Vec<Box<dyn rtcp::Packet>> = vec![
246            Box::new(SenderReport {
247                ssrc: MEDIA,
248                packet_count: 5,
249                reports: vec![block.clone()],
250                ..Default::default()
251            }),
252            Box::new(ReceiverReport {
253                ssrc: MEDIA,
254                reports: vec![block],
255                ..Default::default()
256            }),
257            Box::new(SourceDescription {
258                chunks: vec![SourceDescriptionChunk {
259                    source: MEDIA,
260                    items: vec![SourceDescriptionItem {
261                        sdes_type: SdesType::SdesCname,
262                        text: bytes::Bytes::from_static(b"cname"),
263                    }],
264                }],
265            }),
266            Box::new(Goodbye {
267                sources: vec![MEDIA, PEER],
268                ..Default::default()
269            }),
270            Box::new(TransportLayerCc {
271                sender_ssrc: PEER,
272                media_ssrc: MEDIA,
273                ..Default::default()
274            }),
275            Box::new(CcFeedbackReport {
276                sender_ssrc: PEER,
277                report_blocks: vec![CcFeedbackReportBlock {
278                    media_ssrc: MEDIA,
279                    ..Default::default()
280                }],
281                report_timestamp: 1,
282            }),
283            Box::new(ExtendedReport {
284                sender_ssrc: PEER,
285                reports: vec![
286                    Box::new(ReceiverReferenceTimeReportBlock { ntp_timestamp: 9 }),
287                    Box::new(DLRRReportBlock {
288                        reports: vec![DLRRReport {
289                            ssrc: MEDIA,
290                            last_rr: 1,
291                            dlrr: 2,
292                        }],
293                    }),
294                ],
295            }),
296        ];
297        let mapped = map.map_rtcp(&compound);
298        assert_eq!(mapped.len(), compound.len());
299
300        let sr: SenderReport = downcast(mapped[0].as_ref());
301        assert_eq!((sr.ssrc, sr.reports[0].ssrc), (MEDIA ^ KEY, PEER ^ KEY));
302        assert_eq!((sr.packet_count, sr.reports[0].fraction_lost), (5, 3));
303        let rr: ReceiverReport = downcast(mapped[1].as_ref());
304        assert_eq!((rr.ssrc, rr.reports[0].ssrc), (MEDIA ^ KEY, PEER ^ KEY));
305        let sdes: SourceDescription = downcast(mapped[2].as_ref());
306        assert_eq!(sdes.chunks[0].source, MEDIA ^ KEY);
307        assert_eq!(&sdes.chunks[0].items[0].text[..], b"cname");
308        let bye: Goodbye = downcast(mapped[3].as_ref());
309        assert_eq!(bye.sources, vec![MEDIA ^ KEY, PEER ^ KEY]);
310        let twcc: TransportLayerCc = downcast(mapped[4].as_ref());
311        assert_eq!(
312            (twcc.sender_ssrc, twcc.media_ssrc),
313            (PEER ^ KEY, MEDIA ^ KEY)
314        );
315        let ccfb: CcFeedbackReport = downcast(mapped[5].as_ref());
316        assert_eq!(
317            (ccfb.sender_ssrc, ccfb.report_blocks[0].media_ssrc),
318            (PEER ^ KEY, MEDIA ^ KEY)
319        );
320        let xr: ExtendedReport = downcast(mapped[6].as_ref());
321        assert_eq!(xr.sender_ssrc, PEER ^ KEY);
322        assert_eq!(xr.reports.len(), 2);
323        let dlrr: DLRRReportBlock = downcast(xr.reports[1].as_ref());
324        assert_eq!(dlrr.reports[0].ssrc, MEDIA ^ KEY);
325
326        // And back: what the chain wrote is what the wire carries.
327        let back = map.map_rtcp(&mapped);
328        assert_eq!(back.len(), compound.len());
329        for (back, original) in back.iter().zip(&compound) {
330            assert!(back.equal(original.as_ref()), "{back} != {original}");
331        }
332    }
333
334    #[test]
335    fn rtcp_with_no_meaning_for_a_fec_stream_is_left_out() {
336        let map = FecSessionSsrcMap::new(KEY);
337        let compound: Vec<Box<dyn rtcp::Packet>> = vec![
338            Box::new(ReceiverReport {
339                ssrc: PEER,
340                ..Default::default()
341            }),
342            Box::new(PictureLossIndication {
343                sender_ssrc: PEER,
344                media_ssrc: MEDIA,
345            }),
346        ];
347        let mapped = map.map_rtcp(&compound);
348        assert_eq!(mapped.len(), 1, "the picture loss indication is dropped");
349        let rr: ReceiverReport = downcast(mapped[0].as_ref());
350        assert_eq!(rr.ssrc, PEER ^ KEY);
351    }
352}