Skip to main content

rtci_rtcp/payload_feedbacks/
layer_refresh_request.rs

1//! Layer Refresh Request (LRR, RFC 9627 §3).
2//!
3//! A receiver of a scalable stream asks the encoder for a layer refresh point: a picture from
4//! which a temporal or spatial layer can be decoded without the pictures of that layer before
5//! it. VP9 and AV1 (AV1 RTP specification §8.2) use it to switch layers up without a full key
6//! frame.
7use crate::{header::*, packet::*, util::*};
8use shared::{
9    error::{Error, Result},
10    marshal::{Marshal, MarshalSize, Unmarshal},
11};
12
13use bytes::{Buf, BufMut};
14use std::fmt;
15
16const LRR_ENTRY_LENGTH: usize = 12;
17const LRR_PAYLOAD_TYPE_MAX: u8 = 0x7f;
18const LRR_TEMPORAL_ID_MAX: u8 = 0x07;
19
20/// The layers a receiver decodes at the time of the request.
21#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
22pub struct LrrCurrentLayer {
23    /// The current temporal layer ID (CTID), 3 bits.
24    pub temporal_layer_id: u8,
25    /// The current layer ID (CLID), as the codec's payload format maps its layer ID to 8 bits.
26    pub layer_id: u8,
27}
28
29/// One FCI entry of an LRR.
30///
31/// ```text
32///  0                   1                   2                   3
33///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
34/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
35/// |                              SSRC                             |
36/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
37/// | Seq nr.       |C| Payload Type| Reserved                      |
38/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
39/// | RES     | TTID| TLID          | RES     | CTID| CLID          |
40/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
41/// ```
42#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
43pub struct LrrEntry {
44    /// The media sender asked for the refresh.
45    pub ssrc: u32,
46    /// The request's sequence number: it goes up with each new request, a repetition keeps it.
47    pub sequence_number: u8,
48    /// The RTP payload type the layer IDs are to be read with, 7 bits.
49    pub payload_type: u8,
50    /// The target temporal layer ID (TTID), 3 bits.
51    pub target_temporal_layer_id: u8,
52    /// The target layer ID (TLID), as the codec's payload format maps its layer ID to 8 bits.
53    pub target_layer_id: u8,
54    /// The layers decoded now, when the receiver says (the C bit). With it the encoder may
55    /// refresh only the layers between the current and the target one.
56    pub current: Option<LrrCurrentLayer>,
57}
58
59/// The VP9 layer index of an LRR (RFC 9628 section 5.3): the TID in the low three bits of the
60/// temporal field and the SID in the low three bits of the layer field, the reserved bits 0.
61const VP9_SID_MAX: u8 = 0x07;
62/// AV1 uses the VP9 format "with the high order bit of its three-bit SID field set to 0" (AV1
63/// RTP specification section 8.2): a two-bit spatial ID.
64const AV1_SPATIAL_ID_MAX: u8 = 0x03;
65
66impl LrrEntry {
67    /// An entry for a VP9 stream (RFC 9628 section 5.3): target and, when the receiver says,
68    /// current temporal and spatial layer IDs. A TID or SID over 7 is refused.
69    pub fn vp9(
70        ssrc: u32,
71        sequence_number: u8,
72        payload_type: u8,
73        target: (u8, u8),
74        current: Option<(u8, u8)>,
75    ) -> Result<Self> {
76        Self::layered(
77            ssrc,
78            sequence_number,
79            payload_type,
80            target,
81            current,
82            VP9_SID_MAX,
83        )
84    }
85
86    /// An entry for an AV1 stream (AV1 RTP specification section 8.2): `temporal_id` and
87    /// `spatial_id` as the bitstream has them, in the VP9 format with the high bit of the SID
88    /// 0. A spatial ID over 3 or a temporal ID over 7 is refused.
89    pub fn av1(
90        ssrc: u32,
91        sequence_number: u8,
92        payload_type: u8,
93        target: (u8, u8),
94        current: Option<(u8, u8)>,
95    ) -> Result<Self> {
96        Self::layered(
97            ssrc,
98            sequence_number,
99            payload_type,
100            target,
101            current,
102            AV1_SPATIAL_ID_MAX,
103        )
104    }
105
106    fn layered(
107        ssrc: u32,
108        sequence_number: u8,
109        payload_type: u8,
110        (target_temporal, target_spatial): (u8, u8),
111        current: Option<(u8, u8)>,
112        spatial_max: u8,
113    ) -> Result<Self> {
114        let layers = std::iter::once((target_temporal, target_spatial)).chain(current);
115        for (temporal, spatial) in layers {
116            if temporal > LRR_TEMPORAL_ID_MAX || spatial > spatial_max {
117                return Err(Error::InvalidHeader);
118            }
119        }
120        if payload_type > LRR_PAYLOAD_TYPE_MAX {
121            return Err(Error::WrongPayloadType);
122        }
123        Ok(LrrEntry {
124            ssrc,
125            sequence_number,
126            payload_type,
127            target_temporal_layer_id: target_temporal,
128            target_layer_id: target_spatial,
129            current: current.map(|(temporal, spatial)| LrrCurrentLayer {
130                temporal_layer_id: temporal,
131                layer_id: spatial,
132            }),
133        })
134    }
135
136    /// The target spatial ID of a VP9 or AV1 entry: the SID bits of the layer field, the
137    /// reserved bits ignored (RFC 9628 section 5.3).
138    pub fn target_spatial_id(&self) -> u8 {
139        self.target_layer_id & VP9_SID_MAX
140    }
141}
142
143/// Layer Refresh Request (LRR, PSFB FMT=10).
144#[derive(Debug, PartialEq, Eq, Default, Clone)]
145pub struct LayerRefreshRequest {
146    /// The source that makes the request.
147    pub sender_ssrc: u32,
148    /// At least one entry.
149    pub entries: Vec<LrrEntry>,
150}
151
152impl fmt::Display for LayerRefreshRequest {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        write!(f, "LayerRefreshRequest {:x}", self.sender_ssrc)?;
155        for e in &self.entries {
156            write!(
157                f,
158                " ({:x} {} pt={} t={} l={})",
159                e.ssrc,
160                e.sequence_number,
161                e.payload_type,
162                e.target_temporal_layer_id,
163                e.target_layer_id
164            )?;
165        }
166        Ok(())
167    }
168}
169
170impl Packet for LayerRefreshRequest {
171    fn header(&self) -> Header {
172        Header {
173            padding: false,
174            count: FORMAT_LRR,
175            packet_type: PacketType::PayloadSpecificFeedback,
176            length: ((self.marshal_size() / 4) - 1) as u16,
177        }
178    }
179
180    fn destination_ssrc(&self) -> Vec<u32> {
181        self.entries.iter().map(|e| e.ssrc).collect()
182    }
183
184    fn raw_size(&self) -> usize {
185        HEADER_LENGTH + FEEDBACK_SSRCS_LENGTH + self.entries.len() * LRR_ENTRY_LENGTH
186    }
187
188    packet_any!(LayerRefreshRequest);
189}
190
191impl MarshalSize for LayerRefreshRequest {
192    fn marshal_size(&self) -> usize {
193        self.raw_size()
194    }
195}
196
197impl Marshal for LayerRefreshRequest {
198    fn marshal_to(&self, buf: &mut [u8]) -> Result<usize> {
199        // The FCI contains one or more entries.
200        if self.entries.is_empty() {
201            return Err(Error::PacketTooShort);
202        }
203        for e in &self.entries {
204            if e.payload_type > LRR_PAYLOAD_TYPE_MAX {
205                return Err(Error::WrongPayloadType);
206            }
207            if e.target_temporal_layer_id > LRR_TEMPORAL_ID_MAX
208                || e.current
209                    .is_some_and(|c| c.temporal_layer_id > LRR_TEMPORAL_ID_MAX)
210            {
211                return Err(Error::InvalidHeader);
212            }
213        }
214
215        let size = self.raw_size();
216        // As for FIR, the "SSRC of media source" is not used and is 0.
217        let mut buf = put_feedback_start(
218            buf,
219            PacketType::PayloadSpecificFeedback,
220            FORMAT_LRR,
221            size,
222            self.sender_ssrc,
223            0,
224        )?;
225        for e in &self.entries {
226            buf.put_u32(e.ssrc);
227            buf.put_u8(e.sequence_number);
228            buf.put_u8(((e.current.is_some() as u8) << 7) | e.payload_type);
229            buf.put_u16(0); // reserved
230            buf.put_u8(e.target_temporal_layer_id);
231            buf.put_u8(e.target_layer_id);
232            // Without the C bit the current layer fields are zero.
233            let current = e.current.unwrap_or_default();
234            buf.put_u8(current.temporal_layer_id);
235            buf.put_u8(current.layer_id);
236        }
237        Ok(size)
238    }
239}
240
241impl Unmarshal for LayerRefreshRequest {
242    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
243    where
244        Self: Sized,
245        B: Buf,
246    {
247        let (sender_ssrc, _media_ssrc, mut fci) =
248            read_feedback(raw_packet, PacketType::PayloadSpecificFeedback, FORMAT_LRR)?;
249        if fci.is_empty() {
250            return Err(Error::PacketTooShort);
251        }
252        if !fci.len().is_multiple_of(LRR_ENTRY_LENGTH) {
253            return Err(Error::InvalidHeader);
254        }
255
256        let mut entries = Vec::with_capacity(fci.len() / LRR_ENTRY_LENGTH);
257        while fci.has_remaining() {
258            let ssrc = fci.get_u32();
259            let sequence_number = fci.get_u8();
260            let c_and_payload_type = fci.get_u8();
261            fci.advance(2); // reserved, ignored
262            let target_temporal_layer_id = fci.get_u8() & LRR_TEMPORAL_ID_MAX;
263            let target_layer_id = fci.get_u8();
264            let current_temporal_layer_id = fci.get_u8() & LRR_TEMPORAL_ID_MAX;
265            let current_layer_id = fci.get_u8();
266            entries.push(LrrEntry {
267                ssrc,
268                sequence_number,
269                payload_type: c_and_payload_type & LRR_PAYLOAD_TYPE_MAX,
270                target_temporal_layer_id,
271                target_layer_id,
272                // Without the C bit the current layer fields are ignored.
273                current: (c_and_payload_type & 0x80 != 0).then_some(LrrCurrentLayer {
274                    temporal_layer_id: current_temporal_layer_id,
275                    layer_id: current_layer_id,
276                }),
277            });
278        }
279
280        Ok(LayerRefreshRequest {
281            sender_ssrc,
282            entries,
283        })
284    }
285}
286
287#[cfg(test)]
288mod test {
289    use super::*;
290    use bytes::Bytes;
291
292    /// AV1 RTP specification section 8.2: "AV1 streams MUST use the Layer Refresh Request
293    /// format defined for VP9 in Section 5.3 of [VP9], with the high order bit of its
294    /// three-bit SID field set to 0": TID in the low three bits of the temporal octet, SID in
295    /// the low two of the layer octet, the rest zero; a spatial ID that needs the high bit is
296    /// refused for AV1 and allowed for VP9.
297    #[test]
298    fn an_av1_layer_refresh_request_uses_the_vp9_format_with_a_two_bit_sid() {
299        let entry = LrrEntry::av1(0x0a0b_0c0d, 7, 45, (2, 3), Some((1, 1))).unwrap();
300        let lrr = LayerRefreshRequest {
301            sender_ssrc: 0x0102_0304,
302            entries: vec![entry],
303        };
304        let raw = lrr.marshal().unwrap();
305        // The FCI after the 12 octets of the feedback header: SSRC, seq, C|PT, reserved, then
306        // RES|TTID, TLID, RES|CTID, CLID.
307        assert_eq!(
308            &raw[12..24],
309            &[0x0a, 0x0b, 0x0c, 0x0d, 7, 0x80 | 45, 0, 0, 2, 3, 1, 1]
310        );
311        let read = LayerRefreshRequest::unmarshal(&mut raw.freeze()).unwrap();
312        assert_eq!(3, read.entries[0].target_spatial_id());
313        assert_eq!(2, read.entries[0].target_temporal_layer_id);
314
315        assert!(
316            LrrEntry::av1(1, 0, 45, (0, 4), None).is_err(),
317            "SID high bit set"
318        );
319        assert!(LrrEntry::av1(1, 0, 45, (8, 0), None).is_err());
320        assert!(
321            LrrEntry::vp9(1, 0, 98, (0, 4), None).is_ok(),
322            "VP9 has three SID bits"
323        );
324        assert!(LrrEntry::vp9(1, 0, 98, (0, 8), None).is_err());
325    }
326
327    /// RFC 9628 section 5.3: for VP9 the layer ID of an LRR is the spatial layer (SID, three
328    /// bits) and the temporal layer ID the TID: a request for spatial layer 5, temporal layer
329    /// 2, from layer 3 / 1, reads back as such; a SID or TID over 7 is refused.
330    #[test]
331    fn a_vp9_layer_refresh_request_names_the_spatial_and_temporal_layers() {
332        let entry = LrrEntry::vp9(0x0a0b0c0d, 1, 98, (2, 5), Some((1, 3))).unwrap();
333        let lrr = LayerRefreshRequest {
334            sender_ssrc: 1,
335            entries: vec![entry],
336        };
337        let raw = lrr.marshal().unwrap();
338        assert_eq!(&[0x02, 0x05, 0x01, 0x03][..], &raw[20..24]);
339        let read = LayerRefreshRequest::unmarshal(&mut raw.freeze()).unwrap();
340        assert_eq!(5, read.entries[0].target_spatial_id());
341        assert_eq!(2, read.entries[0].target_temporal_layer_id);
342        assert!(LrrEntry::vp9(1, 1, 98, (2, 8), None).is_err());
343        assert!(LrrEntry::vp9(1, 1, 98, (8, 0), None).is_err());
344    }
345
346    #[test]
347    fn lrr_round_trips_with_and_without_the_current_layer() {
348        let lrr = LayerRefreshRequest {
349            sender_ssrc: 0x01020304,
350            entries: vec![
351                LrrEntry {
352                    ssrc: 0x0a0b0c0d,
353                    sequence_number: 3,
354                    payload_type: 98,
355                    target_temporal_layer_id: 2,
356                    target_layer_id: 0x21,
357                    current: Some(LrrCurrentLayer {
358                        temporal_layer_id: 1,
359                        layer_id: 0x10,
360                    }),
361                },
362                LrrEntry {
363                    ssrc: 0x0a0b0c0e,
364                    sequence_number: 4,
365                    payload_type: 98,
366                    target_temporal_layer_id: 0,
367                    target_layer_id: 1,
368                    current: None,
369                },
370            ],
371        };
372        let raw = lrr.marshal().unwrap();
373        assert_eq!(
374            &[
375                0x8a, 0xce, 0x00, 0x08, // v=2, FMT=10, PSFB, len=8
376                0x01, 0x02, 0x03, 0x04, // sender
377                0x00, 0x00, 0x00, 0x00, // media source: not used, zero
378                0x0a, 0x0b, 0x0c, 0x0d, 0x03, 0xe2, 0x00, 0x00, // seq 3, C=1, pt 98
379                0x02, 0x21, 0x01, 0x10, // TTID 2, TLID 0x21, CTID 1, CLID 0x10
380                0x0a, 0x0b, 0x0c, 0x0e, 0x04, 0x62, 0x00, 0x00, // seq 4, C=0, pt 98
381                0x00, 0x01, 0x00, 0x00,
382            ][..],
383            &raw[..]
384        );
385        assert_eq!(
386            lrr,
387            LayerRefreshRequest::unmarshal(&mut raw.freeze()).unwrap()
388        );
389        assert_eq!(vec![0x0a0b0c0d, 0x0a0b0c0e], lrr.destination_ssrc());
390    }
391
392    #[test]
393    fn reserved_bits_and_an_unflagged_current_layer_are_ignored() {
394        let mut raw = Bytes::from_static(&[
395            0x8a, 0xce, 0x00, 0x05, 0, 0, 0, 1, 9, 9, 9, 9, // media ssrc is not used
396            0, 0, 0, 2, 0x07, 0x60, 0xff, 0xff, // C=0, reserved all ones
397            0xfa, 0x05, 0xff, 0xff, // RES ones, TTID 2; CTID / CLID set although C=0
398        ]);
399        let lrr = LayerRefreshRequest::unmarshal(&mut raw).unwrap();
400        assert_eq!(
401            vec![LrrEntry {
402                ssrc: 2,
403                sequence_number: 7,
404                payload_type: 96,
405                target_temporal_layer_id: 2,
406                target_layer_id: 5,
407                current: None,
408            }],
409            lrr.entries
410        );
411    }
412
413    #[test]
414    fn malformed_requests_are_refused() {
415        assert_eq!(
416            Err(Error::PacketTooShort),
417            LayerRefreshRequest::default().marshal()
418        );
419        let bad_tid = LayerRefreshRequest {
420            sender_ssrc: 1,
421            entries: vec![LrrEntry {
422                target_temporal_layer_id: 8,
423                ..Default::default()
424            }],
425        };
426        assert_eq!(Err(Error::InvalidHeader), bad_tid.marshal());
427        let bad_pt = LayerRefreshRequest {
428            sender_ssrc: 1,
429            entries: vec![LrrEntry {
430                payload_type: 128,
431                ..Default::default()
432            }],
433        };
434        assert_eq!(Err(Error::WrongPayloadType), bad_pt.marshal());
435
436        let mut none = Bytes::from_static(&[0x8a, 0xce, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0]);
437        assert_eq!(
438            Err(Error::PacketTooShort),
439            LayerRefreshRequest::unmarshal(&mut none)
440        );
441        let mut short = Bytes::from_static(&[
442            0x8a, 0xce, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 1, 96, 0, 0,
443        ]);
444        assert_eq!(
445            Err(Error::InvalidHeader),
446            LayerRefreshRequest::unmarshal(&mut short)
447        );
448    }
449}