Skip to main content

rtci_interceptor/
keyframe.rs

1//! Lets inbound key-frame requests reach the application.
2
3use crate::Interceptor;
4use crate::stream_info::StreamInfo;
5use crate::{Attribute, Packet, TaggedPacket};
6use rtcp::payload_feedbacks::full_intra_request::{FirEntry, FullIntraRequest};
7use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
8use sansio::Protocol;
9use shared::error::Error;
10use std::collections::{HashMap, VecDeque};
11use std::time::Instant;
12
13/// Marks inbound RTCP that asks for a key frame — a Picture Loss Indication (RFC 4585 §6.3.1) or
14/// a Full Intra Request (RFC 5104 §4.3.1) — [`Attribute::DeliverToApplication`], so it passes the
15/// chain's terminus ([`NoopInterceptor`](crate::NoopInterceptor)) instead of ending there.
16///
17/// # Why
18///
19/// The terminus ends every inbound RTCP packet no interceptor vouches for, which is right for
20/// reports and feedback the chain itself acts on. A key-frame request is the exception: no
21/// interceptor can act on it, because only the encoder can produce a key frame, and the encoder
22/// is the application (or sits behind it). Swallowed, a receiver that lost its reference picture
23/// asks again and again while the sender never hears it, and the picture stays broken until the
24/// next scheduled key frame. So the requests are delivered: the application reads them as
25/// `RTCMessage::RtcpPacket` (the whole compound packet the request arrived in).
26///
27/// # Repeated full intra requests
28///
29/// A FIR is a command with a sequence number (RFC 5104 section 4.3.1): the requester repeats
30/// it, with the same number, until it sees the key frame, and "the encoder ... does not need
31/// to act on a repetition". An FCI entry whose command sequence number is the one last seen
32/// from that requester for that stream is a repetition and is not delivered again; a FIR left
33/// with no entry is taken out of the compound packet. A PLI has no sequence number and is
34/// always delivered.
35///
36/// # Where it goes
37///
38/// [`Slot::KeyFrameRequests`](crate::Slot::KeyFrameRequests), application-ward of every default
39/// interceptor, so each of them has seen the packet first. It only marks packets; it never holds,
40/// drops or generates one, so its position constrains nothing else. Marking an already marked
41/// packet does nothing, so an application interceptor that marks the same packets can stay.
42///
43/// # Example
44///
45/// ```
46/// use rtci_interceptor::{KeyFrameRequestInterceptor, Registry, Slot};
47///
48/// let chain = Registry::new()
49///     .with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
50///     .build();
51/// # let _ = chain;
52/// ```
53#[derive(Default)]
54pub struct KeyFrameRequestInterceptor {
55    /// The last FIR command sequence number seen, by (requester SSRC, target SSRC).
56    fir_commands: HashMap<(u32, u32), u8>,
57    reads: VecDeque<TaggedPacket>,
58    writes: VecDeque<TaggedPacket>,
59}
60
61/// The most (requester, target) pairs whose last FIR command is remembered.
62const MAX_FIR_COMMANDS: usize = 1024;
63
64impl KeyFrameRequestInterceptor {
65    /// An interceptor that delivers inbound PLI and FIR.
66    pub fn new() -> Self {
67        Self::default()
68    }
69}
70
71/// Whether a compound RTCP packet carries a request only the encoder can answer: a PLI or a
72/// FIR, and also an SLI or an RPSI (RFC 4585 sections 6.3.2, 6.3.3; RFC 8834 sections 5.1.3,
73/// 5.1.4: a sender "SHOULD" try to repair the slice, and act on a reference picture
74/// selection), which the encoder needs as much as a key-frame request.
75///
76/// The other codec control messages that only the encoder can act on go with them: a TSTR
77/// (RFC 5104 section 4.3.2.2: "the encoder SHOULD take [it] into account" when it chooses its
78/// trade-off; the TSTN that acknowledges it is the engine's), a VBCM (section 4.3.4, a
79/// payload for the codec) and an LRR (RFC 9627, a layer refresh).
80fn asks_for_key_frame(packets: &[Box<dyn rtcp::Packet>]) -> bool {
81    use rtcp::payload_feedbacks::layer_refresh_request::LayerRefreshRequest;
82    use rtcp::payload_feedbacks::reference_picture_selection_indication::ReferencePictureSelectionIndication;
83    use rtcp::payload_feedbacks::slice_loss_indication::SliceLossIndication;
84    use rtcp::payload_feedbacks::temporal_spatial_tradeoff::TemporalSpatialTradeoffRequest;
85    use rtcp::payload_feedbacks::video_back_channel_message::VideoBackChannelMessage;
86    packets.iter().any(|p| {
87        let p = p.as_any();
88        p.is::<PictureLossIndication>()
89            || p.is::<FullIntraRequest>()
90            || p.is::<SliceLossIndication>()
91            || p.is::<ReferencePictureSelectionIndication>()
92            || p.is::<TemporalSpatialTradeoffRequest>()
93            || p.is::<VideoBackChannelMessage>()
94            || p.is::<LayerRefreshRequest>()
95    })
96}
97
98impl KeyFrameRequestInterceptor {
99    /// Takes the repetitions out of the FIRs of a compound packet (RFC 5104 4.3.1.2): an
100    /// entry is new when its command sequence number differs from the last one this
101    /// requester sent for that stream.
102    fn drop_repeated_firs(&mut self, packets: &mut Vec<Box<dyn rtcp::Packet>>) {
103        if !packets
104            .iter()
105            .any(|packet| packet.as_any().is::<FullIntraRequest>())
106        {
107            return;
108        }
109        let mut kept: Vec<Box<dyn rtcp::Packet>> = Vec::with_capacity(packets.len());
110        for packet in packets.drain(..) {
111            let Some(fir) = packet.as_any().downcast_ref::<FullIntraRequest>() else {
112                kept.push(packet);
113                continue;
114            };
115            if fir.fir.is_empty() {
116                // Nothing to tell a repetition by; the application gets it as it is.
117                kept.push(packet);
118                continue;
119            }
120            let new_commands: Vec<FirEntry> = fir
121                .fir
122                .iter()
123                .filter(|entry| {
124                    let key = (fir.sender_ssrc, entry.ssrc);
125                    if self.fir_commands.get(&key) == Some(&entry.sequence_number) {
126                        return false;
127                    }
128                    if self.fir_commands.len() >= MAX_FIR_COMMANDS
129                        && !self.fir_commands.contains_key(&key)
130                    {
131                        self.fir_commands.clear();
132                    }
133                    self.fir_commands.insert(key, entry.sequence_number);
134                    true
135                })
136                .cloned()
137                .collect();
138            if new_commands.len() == fir.fir.len() {
139                kept.push(packet);
140            } else if !new_commands.is_empty() {
141                kept.push(Box::new(FullIntraRequest {
142                    sender_ssrc: fir.sender_ssrc,
143                    media_ssrc: fir.media_ssrc,
144                    fir: new_commands,
145                }));
146            }
147        }
148        *packets = kept;
149    }
150}
151
152/// The FIR commands an endpoint sends (RFC 5104 section 4.3.1): each new command for a media
153/// sender takes the next command sequence number (modulo 256), a repetition keeps it, and
154/// the "SSRC of media source" field of the packet is zero, the target being in the FCI.
155///
156/// The application decides when a request is new (it needs another key frame) and when it is
157/// repeating one that has not been answered; this keeps the numbers.
158///
159/// ```
160/// use rtci_interceptor::FirCommands;
161///
162/// let mut commands = FirCommands::new();
163/// let first = commands.request(0x1111, 0x2222);
164/// let again = commands.repeat(0x1111, 0x2222).unwrap();
165/// let next = commands.request(0x1111, 0x2222);
166///
167/// assert_eq!(first.fir[0].sequence_number, again.fir[0].sequence_number);
168/// assert_eq!(
169///     first.fir[0].sequence_number.wrapping_add(1),
170///     next.fir[0].sequence_number
171/// );
172/// assert_eq!(0, first.media_ssrc);
173/// ```
174#[derive(Debug, Default, Clone)]
175pub struct FirCommands {
176    /// The sequence number of the last command sent to each media sender.
177    last: HashMap<u32, u8>,
178}
179
180impl FirCommands {
181    /// No command sent yet.
182    pub fn new() -> Self {
183        Self::default()
184    }
185
186    /// A new command for the media sender `media_ssrc`, from `sender_ssrc`.
187    pub fn request(&mut self, sender_ssrc: u32, media_ssrc: u32) -> FullIntraRequest {
188        let sequence_number = match self.last.get(&media_ssrc) {
189            Some(last) => last.wrapping_add(1),
190            None => 0,
191        };
192        self.last.insert(media_ssrc, sequence_number);
193        Self::packet(sender_ssrc, media_ssrc, sequence_number)
194    }
195
196    /// The last command for `media_ssrc` again, or `None` when none was sent.
197    pub fn repeat(&self, sender_ssrc: u32, media_ssrc: u32) -> Option<FullIntraRequest> {
198        self.last
199            .get(&media_ssrc)
200            .map(|&sequence_number| Self::packet(sender_ssrc, media_ssrc, sequence_number))
201    }
202
203    fn packet(sender_ssrc: u32, media_ssrc: u32, sequence_number: u8) -> FullIntraRequest {
204        FullIntraRequest {
205            sender_ssrc,
206            // RFC 5104 4.3.1.2: "SSRC of media source ... SHALL be set to 0".
207            media_ssrc: 0,
208            fir: vec![FirEntry {
209                ssrc: media_ssrc,
210                sequence_number,
211            }],
212        }
213    }
214}
215
216impl Protocol<TaggedPacket, TaggedPacket, ()> for KeyFrameRequestInterceptor {
217    type Rout = TaggedPacket;
218    type Wout = TaggedPacket;
219    type Eout = ();
220    type Error = Error;
221    type Time = Instant;
222
223    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
224        if let Packet::Rtcp(packets) = &mut msg.message.packet
225            && !packets.is_empty()
226        {
227            self.drop_repeated_firs(packets);
228            if packets.is_empty() && msg.message.attributes.is_empty() {
229                // The compound packet was a repeated FIR and nothing else.
230                return Ok(());
231            }
232        }
233        if let Packet::Rtcp(packets) = &msg.message.packet
234            && asks_for_key_frame(packets)
235            && !msg.message.has(&Attribute::DeliverToApplication)
236        {
237            msg.message.attributes.push(Attribute::DeliverToApplication);
238        }
239        self.reads.push_back(msg);
240        Ok(())
241    }
242
243    fn poll_read(&mut self) -> Option<Self::Rout> {
244        self.reads.pop_front()
245    }
246
247    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
248        self.writes.push_back(msg);
249        Ok(())
250    }
251
252    fn poll_write(&mut self) -> Option<Self::Wout> {
253        self.writes.pop_front()
254    }
255}
256
257impl Interceptor for KeyFrameRequestInterceptor {
258    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
259    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
260    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
261    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::{AttributedPacket, Registry, Slot};
268    use rtcp::receiver_report::ReceiverReport;
269    use shared::TransportContext;
270
271    fn rtcp(packets: Vec<Box<dyn rtcp::Packet>>) -> TaggedPacket {
272        TaggedPacket {
273            now: Instant::now(),
274            transport: TransportContext::default(),
275            message: AttributedPacket::new(Packet::Rtcp(packets)),
276        }
277    }
278
279    fn pli() -> Box<dyn rtcp::Packet> {
280        Box::new(PictureLossIndication {
281            sender_ssrc: 1,
282            media_ssrc: 2,
283        })
284    }
285
286    fn fir() -> Box<dyn rtcp::Packet> {
287        Box::new(FullIntraRequest {
288            sender_ssrc: 1,
289            media_ssrc: 2,
290            fir: vec![],
291        })
292    }
293
294    fn rr() -> Box<dyn rtcp::Packet> {
295        Box::new(ReceiverReport {
296            ssrc: 1,
297            ..Default::default()
298        })
299    }
300
301    /// What the application gets from a whole chain: the terminus is appended by `build`.
302    fn delivered(with_interceptor: bool, packets: Vec<Box<dyn rtcp::Packet>>) -> usize {
303        let registry = if with_interceptor {
304            Registry::new().with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
305        } else {
306            Registry::new()
307        };
308        let mut chain = registry.build();
309        chain.handle_read(rtcp(packets)).unwrap();
310        std::iter::from_fn(|| chain.poll_read())
311            .filter(|p| match &p.message.packet {
312                Packet::Rtcp(packets) => !packets.is_empty(),
313                Packet::Rtp(_) => true,
314            })
315            .count()
316    }
317
318    #[test]
319    fn pli_and_fir_reach_the_application() {
320        assert_eq!(delivered(true, vec![pli()]), 1);
321        assert_eq!(delivered(true, vec![fir()]), 1);
322        // In a compound packet beside a report.
323        assert_eq!(delivered(true, vec![rr(), pli()]), 1);
324    }
325
326    /// RFC 4585 sections 6.3.2 and 6.3.3, RFC 8834 sections 5.1.3 and 5.1.4: SLI and RPSI
327    /// reach the application, whose encoder repairs the slice or switches reference.
328    #[test]
329    fn sli_and_rpsi_reach_the_application() {
330        use rtcp::payload_feedbacks::reference_picture_selection_indication::ReferencePictureSelectionIndication;
331        use rtcp::payload_feedbacks::slice_loss_indication::SliceLossIndication;
332        let sli: Box<dyn rtcp::Packet> = Box::new(SliceLossIndication {
333            sender_ssrc: 1,
334            media_ssrc: 2,
335            ..Default::default()
336        });
337        let rpsi: Box<dyn rtcp::Packet> = Box::new(ReferencePictureSelectionIndication {
338            sender_ssrc: 1,
339            media_ssrc: 2,
340            ..Default::default()
341        });
342        assert_eq!(delivered(true, vec![rr(), sli]), 1);
343        assert_eq!(delivered(true, vec![rpsi]), 1);
344    }
345
346    /// RFC 5104 section 4.3.2.2 (the encoder "SHOULD take [a TSTR] into account"), section
347    /// 4.3.4 (a VBCM is a message for the codec) and RFC 9627 (a layer refresh): the requests
348    /// only the encoder can act on reach the application, which owns it; without the
349    /// interceptor the terminus would end them.
350    #[test]
351    fn tstr_vbcm_and_lrr_reach_the_application() {
352        use rtcp::payload_feedbacks::layer_refresh_request::{LayerRefreshRequest, LrrEntry};
353        use rtcp::payload_feedbacks::temporal_spatial_tradeoff::{
354            TemporalSpatialTradeoffRequest, TstEntry,
355        };
356        use rtcp::payload_feedbacks::video_back_channel_message::{
357            VbcmEntry, VideoBackChannelMessage,
358        };
359        let tstr = || -> Box<dyn rtcp::Packet> {
360            Box::new(TemporalSpatialTradeoffRequest {
361                sender_ssrc: 1,
362                entries: vec![TstEntry {
363                    ssrc: 2,
364                    sequence_number: 0,
365                    index: 31,
366                }],
367            })
368        };
369        let vbcm = || -> Box<dyn rtcp::Packet> {
370            Box::new(VideoBackChannelMessage {
371                sender_ssrc: 1,
372                entries: vec![VbcmEntry {
373                    ssrc: 2,
374                    sequence_number: 0,
375                    payload_type: 96,
376                    octet_string: bytes::Bytes::from_static(&[1, 2]),
377                }],
378            })
379        };
380        let lrr = || -> Box<dyn rtcp::Packet> {
381            Box::new(LayerRefreshRequest {
382                sender_ssrc: 1,
383                entries: vec![LrrEntry {
384                    ssrc: 2,
385                    sequence_number: 0,
386                    payload_type: 96,
387                    target_temporal_layer_id: 0,
388                    target_layer_id: 1,
389                    ..Default::default()
390                }],
391            })
392        };
393        for packet in [tstr, vbcm, lrr] {
394            assert_eq!(delivered(true, vec![rr(), packet()]), 1);
395            assert_eq!(delivered(false, vec![rr(), packet()]), 0);
396        }
397    }
398
399    #[test]
400    fn other_rtcp_still_ends_at_the_terminus() {
401        assert_eq!(delivered(true, vec![rr()]), 0);
402    }
403
404    #[test]
405    fn without_it_the_terminus_swallows_them() {
406        assert_eq!(delivered(false, vec![pli()]), 0);
407    }
408
409    fn fir_command(requester: u32, target: u32, sequence_number: u8) -> Box<dyn rtcp::Packet> {
410        Box::new(FullIntraRequest {
411            sender_ssrc: requester,
412            media_ssrc: 0,
413            fir: vec![FirEntry {
414                ssrc: target,
415                sequence_number,
416            }],
417        })
418    }
419
420    /// What the application gets from one chain as `compounds` arrive in turn.
421    fn delivered_in_turn(
422        compounds: Vec<Vec<Box<dyn rtcp::Packet>>>,
423    ) -> Vec<Vec<Box<dyn rtcp::Packet>>> {
424        let mut chain = Registry::new()
425            .with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
426            .build();
427        let mut out = vec![];
428        for compound in compounds {
429            chain.handle_read(rtcp(compound)).unwrap();
430            let mut got = vec![];
431            while let Some(tagged) = chain.poll_read() {
432                if let Packet::Rtcp(packets) = tagged.message.packet {
433                    got.extend(packets);
434                }
435            }
436            out.push(got);
437        }
438        out
439    }
440
441    /// RFC 5104 4.3.1: a FIR repeated with the same command sequence number is one command.
442    #[test]
443    fn a_repeated_fir_is_delivered_once() {
444        let out = delivered_in_turn(vec![
445            vec![fir_command(1, 2, 7)],
446            vec![fir_command(1, 2, 7)],
447            vec![fir_command(1, 2, 7)],
448            // The next command.
449            vec![fir_command(1, 2, 8)],
450        ]);
451        assert_eq!(
452            vec![1, 0, 0, 1],
453            out.iter().map(Vec::len).collect::<Vec<_>>()
454        );
455    }
456
457    /// The sequence numbers are per requester and per target.
458    #[test]
459    fn fir_commands_are_told_apart_by_requester_and_target() {
460        let out = delivered_in_turn(vec![
461            vec![fir_command(1, 2, 7)],
462            vec![fir_command(9, 2, 7)],
463            vec![fir_command(1, 3, 7)],
464            vec![fir_command(1, 2, 7)],
465        ]);
466        assert_eq!(
467            vec![1, 1, 1, 0],
468            out.iter().map(Vec::len).collect::<Vec<_>>()
469        );
470    }
471
472    /// A repetition is taken out of the compound packet; what stands beside it stays, and a
473    /// FIR that repeats one command and gives another keeps the new one.
474    #[test]
475    fn only_the_repeated_entries_are_dropped() {
476        let both: Box<dyn rtcp::Packet> = Box::new(FullIntraRequest {
477            sender_ssrc: 1,
478            media_ssrc: 0,
479            fir: vec![
480                FirEntry {
481                    ssrc: 2,
482                    sequence_number: 7,
483                },
484                FirEntry {
485                    ssrc: 3,
486                    sequence_number: 1,
487                },
488            ],
489        });
490        let out = delivered_in_turn(vec![
491            vec![fir_command(1, 2, 7)],
492            vec![rr(), fir_command(1, 2, 7), pli()],
493            vec![both],
494        ]);
495        // The PLI keeps the second compound packet deliverable, without the FIR.
496        assert_eq!(2, out[1].len());
497        assert!(out[1].iter().all(|p| !p.as_any().is::<FullIntraRequest>()));
498        let fir = out[2][0]
499            .as_any()
500            .downcast_ref::<FullIntraRequest>()
501            .unwrap();
502        assert_eq!(
503            vec![FirEntry {
504                ssrc: 3,
505                sequence_number: 1
506            }],
507            fir.fir
508        );
509    }
510
511    /// RFC 5104 4.3.1.1: the command sequence number goes up by one, modulo 256, per new
512    /// command, and stays for a repetition.
513    #[test]
514    fn fir_command_numbers_count_new_commands_modulo_256() {
515        let mut commands = FirCommands::new();
516        assert!(commands.repeat(1, 2).is_none());
517        let mut last = commands.request(1, 2).fir[0].sequence_number;
518        for _ in 0..300 {
519            assert_eq!(last, commands.repeat(1, 2).unwrap().fir[0].sequence_number);
520            let next = commands.request(1, 2);
521            assert_eq!(last.wrapping_add(1), next.fir[0].sequence_number);
522            assert_eq!(0, next.media_ssrc);
523            assert_eq!(1, next.sender_ssrc);
524            assert_eq!(2, next.fir[0].ssrc);
525            last = next.fir[0].sequence_number;
526        }
527        // Another stream has its own count.
528        assert_eq!(0, commands.request(1, 3).fir[0].sequence_number);
529    }
530
531    #[test]
532    fn marking_is_idempotent() {
533        let mut i = KeyFrameRequestInterceptor::new();
534        let mut msg = rtcp(vec![pli()]);
535        msg.message.attributes.push(Attribute::DeliverToApplication);
536        i.handle_read(msg).unwrap();
537        let out = i.poll_read().unwrap();
538        assert_eq!(
539            out.message
540                .attributes
541                .iter()
542                .filter(|a| matches!(a, Attribute::DeliverToApplication))
543                .count(),
544            1
545        );
546    }
547}