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/// Why an interceptor of this crate asked the application for a key frame itself: the
72/// Picture Loss Indication it puts on the read leg (sender SSRC 0, marked
73/// [`Attribute::DeliverToApplication`]) carries this as [`Attribute::Custom`], so whoever
74/// reads it can tell it from a request the remote peer sent. Read it with
75/// [`AttributedPacket::custom`](crate::AttributedPacket::custom); a PLI or FIR without it came
76/// from the network.
77///
78/// The origin rides with the packet from where it is made, rather than being guessed from the
79/// sender SSRC: an SSRC is a random 32-bit number (RFC 3550 section 8.1), 0 included, so a
80/// remote peer may send a PLI with sender SSRC 0, and that one is still the peer's. The peer connection reads it into
81/// `RTCPeerConnectionEvent::OnKeyFrameRequestOrigin`.
82///
83/// ```
84/// use rtci_interceptor::{Attribute, AttributedPacket, LocalKeyFrameRequest, Packet};
85/// use std::sync::Arc;
86///
87/// let notice = AttributedPacket::new(Packet::Rtcp(vec![]))
88///     .with(Attribute::Custom(Arc::new(LocalKeyFrameRequest::PacerDiscard)));
89/// assert_eq!(
90///     Some(&LocalKeyFrameRequest::PacerDiscard),
91///     notice.custom::<LocalKeyFrameRequest>()
92/// );
93/// ```
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95#[non_exhaustive]
96pub enum LocalKeyFrameRequest {
97    /// The pacer discarded a frame of the stream (`PacerDiscard`, outside a flush): the
98    /// receiver will miss it, and the next picture it can decode is a key frame.
99    PacerDiscard,
100    /// The pacer gave its queue up at a collapse of the target (`PacerFlush`): for every
101    /// video stream, whether it had media queued (then a `PacerDiscard` came first) or not
102    /// (its repairs were dropped all the same).
103    PacerFlush,
104    /// The NACK responder gave the repair of the stream up (a request for a packet too old
105    /// to be useful, or a repair backlog after a fall of the target): what was sent before is
106    /// no longer repaired.
107    RepairGivenUp,
108}
109
110/// Whether a compound RTCP packet carries a request only the encoder can answer: a PLI or a
111/// FIR, and also an SLI or an RPSI (RFC 4585 sections 6.3.2, 6.3.3; RFC 8834 sections 5.1.3,
112/// 5.1.4: a sender "SHOULD" try to repair the slice, and act on a reference picture
113/// selection), which the encoder needs as much as a key-frame request.
114///
115/// The other codec control messages that only the encoder can act on go with them: a TSTR
116/// (RFC 5104 section 4.3.2.2: "the encoder SHOULD take [it] into account" when it chooses its
117/// trade-off; the TSTN that acknowledges it is the engine's), a VBCM (section 4.3.4, a
118/// payload for the codec) and an LRR (RFC 9627, a layer refresh).
119fn asks_for_key_frame(packets: &[Box<dyn rtcp::Packet>]) -> bool {
120    use rtcp::payload_feedbacks::layer_refresh_request::LayerRefreshRequest;
121    use rtcp::payload_feedbacks::reference_picture_selection_indication::ReferencePictureSelectionIndication;
122    use rtcp::payload_feedbacks::slice_loss_indication::SliceLossIndication;
123    use rtcp::payload_feedbacks::temporal_spatial_tradeoff::TemporalSpatialTradeoffRequest;
124    use rtcp::payload_feedbacks::video_back_channel_message::VideoBackChannelMessage;
125    packets.iter().any(|p| {
126        let p = p.as_any();
127        p.is::<PictureLossIndication>()
128            || p.is::<FullIntraRequest>()
129            || p.is::<SliceLossIndication>()
130            || p.is::<ReferencePictureSelectionIndication>()
131            || p.is::<TemporalSpatialTradeoffRequest>()
132            || p.is::<VideoBackChannelMessage>()
133            || p.is::<LayerRefreshRequest>()
134    })
135}
136
137impl KeyFrameRequestInterceptor {
138    /// Takes the repetitions out of the FIRs of a compound packet (RFC 5104 4.3.1.2): an
139    /// entry is new when its command sequence number differs from the last one this
140    /// requester sent for that stream.
141    fn drop_repeated_firs(&mut self, packets: &mut Vec<Box<dyn rtcp::Packet>>) {
142        if !packets
143            .iter()
144            .any(|packet| packet.as_any().is::<FullIntraRequest>())
145        {
146            return;
147        }
148        let mut kept: Vec<Box<dyn rtcp::Packet>> = Vec::with_capacity(packets.len());
149        for packet in packets.drain(..) {
150            let Some(fir) = packet.as_any().downcast_ref::<FullIntraRequest>() else {
151                kept.push(packet);
152                continue;
153            };
154            if fir.fir.is_empty() {
155                // Nothing to tell a repetition by; the application gets it as it is.
156                kept.push(packet);
157                continue;
158            }
159            let new_commands: Vec<FirEntry> = fir
160                .fir
161                .iter()
162                .filter(|entry| {
163                    let key = (fir.sender_ssrc, entry.ssrc);
164                    if self.fir_commands.get(&key) == Some(&entry.sequence_number) {
165                        return false;
166                    }
167                    if self.fir_commands.len() >= MAX_FIR_COMMANDS
168                        && !self.fir_commands.contains_key(&key)
169                    {
170                        self.fir_commands.clear();
171                    }
172                    self.fir_commands.insert(key, entry.sequence_number);
173                    true
174                })
175                .cloned()
176                .collect();
177            if new_commands.len() == fir.fir.len() {
178                kept.push(packet);
179            } else if !new_commands.is_empty() {
180                kept.push(Box::new(FullIntraRequest {
181                    sender_ssrc: fir.sender_ssrc,
182                    media_ssrc: fir.media_ssrc,
183                    fir: new_commands,
184                }));
185            }
186        }
187        *packets = kept;
188    }
189}
190
191/// The FIR commands an endpoint sends (RFC 5104 section 4.3.1): each new command for a media
192/// sender takes the next command sequence number (modulo 256), a repetition keeps it, and
193/// the "SSRC of media source" field of the packet is zero, the target being in the FCI.
194///
195/// The application decides when a request is new (it needs another key frame) and when it is
196/// repeating one that has not been answered; this keeps the numbers.
197///
198/// ```
199/// use rtci_interceptor::FirCommands;
200///
201/// let mut commands = FirCommands::new();
202/// let first = commands.request(0x1111, 0x2222);
203/// let again = commands.repeat(0x1111, 0x2222).unwrap();
204/// let next = commands.request(0x1111, 0x2222);
205///
206/// assert_eq!(first.fir[0].sequence_number, again.fir[0].sequence_number);
207/// assert_eq!(
208///     first.fir[0].sequence_number.wrapping_add(1),
209///     next.fir[0].sequence_number
210/// );
211/// assert_eq!(0, first.media_ssrc);
212/// ```
213#[derive(Debug, Default, Clone)]
214pub struct FirCommands {
215    /// The sequence number of the last command sent to each media sender.
216    last: HashMap<u32, u8>,
217}
218
219impl FirCommands {
220    /// No command sent yet.
221    pub fn new() -> Self {
222        Self::default()
223    }
224
225    /// A new command for the media sender `media_ssrc`, from `sender_ssrc`.
226    pub fn request(&mut self, sender_ssrc: u32, media_ssrc: u32) -> FullIntraRequest {
227        let sequence_number = match self.last.get(&media_ssrc) {
228            Some(last) => last.wrapping_add(1),
229            None => 0,
230        };
231        self.last.insert(media_ssrc, sequence_number);
232        Self::packet(sender_ssrc, media_ssrc, sequence_number)
233    }
234
235    /// The last command for `media_ssrc` again, or `None` when none was sent.
236    pub fn repeat(&self, sender_ssrc: u32, media_ssrc: u32) -> Option<FullIntraRequest> {
237        self.last
238            .get(&media_ssrc)
239            .map(|&sequence_number| Self::packet(sender_ssrc, media_ssrc, sequence_number))
240    }
241
242    fn packet(sender_ssrc: u32, media_ssrc: u32, sequence_number: u8) -> FullIntraRequest {
243        FullIntraRequest {
244            sender_ssrc,
245            // RFC 5104 4.3.1.2: "SSRC of media source ... SHALL be set to 0".
246            media_ssrc: 0,
247            fir: vec![FirEntry {
248                ssrc: media_ssrc,
249                sequence_number,
250            }],
251        }
252    }
253}
254
255impl Protocol<TaggedPacket, TaggedPacket, ()> for KeyFrameRequestInterceptor {
256    type Rout = TaggedPacket;
257    type Wout = TaggedPacket;
258    type Eout = ();
259    type Error = Error;
260    type Time = Instant;
261
262    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
263        if let Packet::Rtcp(packets) = &mut msg.message.packet
264            && !packets.is_empty()
265        {
266            self.drop_repeated_firs(packets);
267            if packets.is_empty() && msg.message.attributes.is_empty() {
268                // The compound packet was a repeated FIR and nothing else.
269                return Ok(());
270            }
271        }
272        if let Packet::Rtcp(packets) = &msg.message.packet
273            && asks_for_key_frame(packets)
274            && !msg.message.has(&Attribute::DeliverToApplication)
275        {
276            msg.message.attributes.push(Attribute::DeliverToApplication);
277        }
278        self.reads.push_back(msg);
279        Ok(())
280    }
281
282    fn poll_read(&mut self) -> Option<Self::Rout> {
283        self.reads.pop_front()
284    }
285
286    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
287        self.writes.push_back(msg);
288        Ok(())
289    }
290
291    fn poll_write(&mut self) -> Option<Self::Wout> {
292        self.writes.pop_front()
293    }
294}
295
296impl Interceptor for KeyFrameRequestInterceptor {
297    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
298    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
299    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
300    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306    use crate::{AttributedPacket, Registry, Slot};
307    use rtcp::receiver_report::ReceiverReport;
308    use shared::TransportContext;
309
310    fn rtcp(packets: Vec<Box<dyn rtcp::Packet>>) -> TaggedPacket {
311        TaggedPacket {
312            now: Instant::now(),
313            transport: TransportContext::default(),
314            message: AttributedPacket::new(Packet::Rtcp(packets)),
315        }
316    }
317
318    fn pli() -> Box<dyn rtcp::Packet> {
319        Box::new(PictureLossIndication {
320            sender_ssrc: 1,
321            media_ssrc: 2,
322        })
323    }
324
325    fn fir() -> Box<dyn rtcp::Packet> {
326        Box::new(FullIntraRequest {
327            sender_ssrc: 1,
328            media_ssrc: 2,
329            fir: vec![],
330        })
331    }
332
333    fn rr() -> Box<dyn rtcp::Packet> {
334        Box::new(ReceiverReport {
335            ssrc: 1,
336            ..Default::default()
337        })
338    }
339
340    /// What the application gets from a whole chain: the terminus is appended by `build`.
341    fn delivered(with_interceptor: bool, packets: Vec<Box<dyn rtcp::Packet>>) -> usize {
342        let registry = if with_interceptor {
343            Registry::new().with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
344        } else {
345            Registry::new()
346        };
347        let mut chain = registry.build();
348        chain.handle_read(rtcp(packets)).unwrap();
349        std::iter::from_fn(|| chain.poll_read())
350            .filter(|p| match &p.message.packet {
351                Packet::Rtcp(packets) => !packets.is_empty(),
352                Packet::Rtp(_) => true,
353            })
354            .count()
355    }
356
357    #[test]
358    fn pli_and_fir_reach_the_application() {
359        assert_eq!(delivered(true, vec![pli()]), 1);
360        assert_eq!(delivered(true, vec![fir()]), 1);
361        // In a compound packet beside a report.
362        assert_eq!(delivered(true, vec![rr(), pli()]), 1);
363    }
364
365    /// RFC 4585 sections 6.3.2 and 6.3.3, RFC 8834 sections 5.1.3 and 5.1.4: SLI and RPSI
366    /// reach the application, whose encoder repairs the slice or switches reference.
367    #[test]
368    fn sli_and_rpsi_reach_the_application() {
369        use rtcp::payload_feedbacks::reference_picture_selection_indication::ReferencePictureSelectionIndication;
370        use rtcp::payload_feedbacks::slice_loss_indication::SliceLossIndication;
371        let sli: Box<dyn rtcp::Packet> = Box::new(SliceLossIndication {
372            sender_ssrc: 1,
373            media_ssrc: 2,
374            ..Default::default()
375        });
376        let rpsi: Box<dyn rtcp::Packet> = Box::new(ReferencePictureSelectionIndication {
377            sender_ssrc: 1,
378            media_ssrc: 2,
379            ..Default::default()
380        });
381        assert_eq!(delivered(true, vec![rr(), sli]), 1);
382        assert_eq!(delivered(true, vec![rpsi]), 1);
383    }
384
385    /// RFC 5104 section 4.3.2.2 (the encoder "SHOULD take [a TSTR] into account"), section
386    /// 4.3.4 (a VBCM is a message for the codec) and RFC 9627 (a layer refresh): the requests
387    /// only the encoder can act on reach the application, which owns it; without the
388    /// interceptor the terminus would end them.
389    #[test]
390    fn tstr_vbcm_and_lrr_reach_the_application() {
391        use rtcp::payload_feedbacks::layer_refresh_request::{LayerRefreshRequest, LrrEntry};
392        use rtcp::payload_feedbacks::temporal_spatial_tradeoff::{
393            TemporalSpatialTradeoffRequest, TstEntry,
394        };
395        use rtcp::payload_feedbacks::video_back_channel_message::{
396            VbcmEntry, VideoBackChannelMessage,
397        };
398        let tstr = || -> Box<dyn rtcp::Packet> {
399            Box::new(TemporalSpatialTradeoffRequest {
400                sender_ssrc: 1,
401                entries: vec![TstEntry {
402                    ssrc: 2,
403                    sequence_number: 0,
404                    index: 31,
405                }],
406            })
407        };
408        let vbcm = || -> Box<dyn rtcp::Packet> {
409            Box::new(VideoBackChannelMessage {
410                sender_ssrc: 1,
411                entries: vec![VbcmEntry {
412                    ssrc: 2,
413                    sequence_number: 0,
414                    payload_type: 96,
415                    octet_string: bytes::Bytes::from_static(&[1, 2]),
416                }],
417            })
418        };
419        let lrr = || -> Box<dyn rtcp::Packet> {
420            Box::new(LayerRefreshRequest {
421                sender_ssrc: 1,
422                entries: vec![LrrEntry {
423                    ssrc: 2,
424                    sequence_number: 0,
425                    payload_type: 96,
426                    target_temporal_layer_id: 0,
427                    target_layer_id: 1,
428                    ..Default::default()
429                }],
430            })
431        };
432        for packet in [tstr, vbcm, lrr] {
433            assert_eq!(delivered(true, vec![rr(), packet()]), 1);
434            assert_eq!(delivered(false, vec![rr(), packet()]), 0);
435        }
436    }
437
438    #[test]
439    fn other_rtcp_still_ends_at_the_terminus() {
440        assert_eq!(delivered(true, vec![rr()]), 0);
441    }
442
443    #[test]
444    fn without_it_the_terminus_swallows_them() {
445        assert_eq!(delivered(false, vec![pli()]), 0);
446    }
447
448    fn fir_command(requester: u32, target: u32, sequence_number: u8) -> Box<dyn rtcp::Packet> {
449        Box::new(FullIntraRequest {
450            sender_ssrc: requester,
451            media_ssrc: 0,
452            fir: vec![FirEntry {
453                ssrc: target,
454                sequence_number,
455            }],
456        })
457    }
458
459    /// What the application gets from one chain as `compounds` arrive in turn.
460    fn delivered_in_turn(
461        compounds: Vec<Vec<Box<dyn rtcp::Packet>>>,
462    ) -> Vec<Vec<Box<dyn rtcp::Packet>>> {
463        let mut chain = Registry::new()
464            .with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
465            .build();
466        let mut out = vec![];
467        for compound in compounds {
468            chain.handle_read(rtcp(compound)).unwrap();
469            let mut got = vec![];
470            while let Some(tagged) = chain.poll_read() {
471                if let Packet::Rtcp(packets) = tagged.message.packet {
472                    got.extend(packets);
473                }
474            }
475            out.push(got);
476        }
477        out
478    }
479
480    /// RFC 5104 4.3.1: a FIR repeated with the same command sequence number is one command.
481    #[test]
482    fn a_repeated_fir_is_delivered_once() {
483        let out = delivered_in_turn(vec![
484            vec![fir_command(1, 2, 7)],
485            vec![fir_command(1, 2, 7)],
486            vec![fir_command(1, 2, 7)],
487            // The next command.
488            vec![fir_command(1, 2, 8)],
489        ]);
490        assert_eq!(
491            vec![1, 0, 0, 1],
492            out.iter().map(Vec::len).collect::<Vec<_>>()
493        );
494    }
495
496    /// The sequence numbers are per requester and per target.
497    #[test]
498    fn fir_commands_are_told_apart_by_requester_and_target() {
499        let out = delivered_in_turn(vec![
500            vec![fir_command(1, 2, 7)],
501            vec![fir_command(9, 2, 7)],
502            vec![fir_command(1, 3, 7)],
503            vec![fir_command(1, 2, 7)],
504        ]);
505        assert_eq!(
506            vec![1, 1, 1, 0],
507            out.iter().map(Vec::len).collect::<Vec<_>>()
508        );
509    }
510
511    /// A repetition is taken out of the compound packet; what stands beside it stays, and a
512    /// FIR that repeats one command and gives another keeps the new one.
513    #[test]
514    fn only_the_repeated_entries_are_dropped() {
515        let both: Box<dyn rtcp::Packet> = Box::new(FullIntraRequest {
516            sender_ssrc: 1,
517            media_ssrc: 0,
518            fir: vec![
519                FirEntry {
520                    ssrc: 2,
521                    sequence_number: 7,
522                },
523                FirEntry {
524                    ssrc: 3,
525                    sequence_number: 1,
526                },
527            ],
528        });
529        let out = delivered_in_turn(vec![
530            vec![fir_command(1, 2, 7)],
531            vec![rr(), fir_command(1, 2, 7), pli()],
532            vec![both],
533        ]);
534        // The PLI keeps the second compound packet deliverable, without the FIR.
535        assert_eq!(2, out[1].len());
536        assert!(out[1].iter().all(|p| !p.as_any().is::<FullIntraRequest>()));
537        let fir = out[2][0]
538            .as_any()
539            .downcast_ref::<FullIntraRequest>()
540            .unwrap();
541        assert_eq!(
542            vec![FirEntry {
543                ssrc: 3,
544                sequence_number: 1
545            }],
546            fir.fir
547        );
548    }
549
550    /// RFC 5104 4.3.1.1: the command sequence number goes up by one, modulo 256, per new
551    /// command, and stays for a repetition.
552    #[test]
553    fn fir_command_numbers_count_new_commands_modulo_256() {
554        let mut commands = FirCommands::new();
555        assert!(commands.repeat(1, 2).is_none());
556        let mut last = commands.request(1, 2).fir[0].sequence_number;
557        for _ in 0..300 {
558            assert_eq!(last, commands.repeat(1, 2).unwrap().fir[0].sequence_number);
559            let next = commands.request(1, 2);
560            assert_eq!(last.wrapping_add(1), next.fir[0].sequence_number);
561            assert_eq!(0, next.media_ssrc);
562            assert_eq!(1, next.sender_ssrc);
563            assert_eq!(2, next.fir[0].ssrc);
564            last = next.fir[0].sequence_number;
565        }
566        // Another stream has its own count.
567        assert_eq!(0, commands.request(1, 3).fir[0].sequence_number);
568    }
569
570    #[test]
571    fn marking_is_idempotent() {
572        let mut i = KeyFrameRequestInterceptor::new();
573        let mut msg = rtcp(vec![pli()]);
574        msg.message.attributes.push(Attribute::DeliverToApplication);
575        i.handle_read(msg).unwrap();
576        let out = i.poll_read().unwrap();
577        assert_eq!(
578            out.message
579                .attributes
580                .iter()
581                .filter(|a| matches!(a, Attribute::DeliverToApplication))
582                .count(),
583            1
584        );
585    }
586}