Skip to main content

rtci_rtcp/payload_feedbacks/
reference_picture_selection_indication.rs

1//! Reference Picture Selection Indication (RPSI, [RFC 4585] ยง6.3.3).
2//!
3//! [RFC 4585]: https://datatracker.ietf.org/doc/html/rfc4585#section-6.3.3
4use crate::{header::*, packet::*, util::*};
5use shared::{
6    error::{Error, Result},
7    marshal::{Marshal, MarshalSize, Unmarshal},
8};
9
10use bytes::{Buf, BufMut, Bytes};
11use std::fmt;
12
13/// The PB octet and the payload type octet that precede the bit string.
14const RPSI_FCI_HEADER_LENGTH: usize = 2;
15const RPSI_PAYLOAD_TYPE_MAX: u8 = 0x7f;
16
17/// Reference Picture Selection Indication (PSFB FMT=3): the receiver names a reference picture
18/// in the codec's own terms. Exactly one indication per packet.
19///
20/// ```text
21///  0                   1                   2                   3
22///  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
23/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
24/// |      PB       |0| Payload Type|    Native RPSI bit string     |
25/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
26/// |   defined per codec          ...                | Padding (0) |
27/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
28/// ```
29#[derive(Debug, PartialEq, Eq, Default, Clone)]
30pub struct ReferencePictureSelectionIndication {
31    /// The source that sends the indication.
32    pub sender_ssrc: u32,
33    /// The media sender it is for.
34    pub media_ssrc: u32,
35    /// The RTP payload type that says how the bit string is to be read, 7 bits.
36    pub payload_type: u8,
37    /// The native RPSI bit string, as the codec defines it, most significant bit first. When
38    /// its length is not a whole number of octets, the last octet's low bits are padding.
39    pub native_rpsi: Bytes,
40    /// How many low bits of the last octet of `native_rpsi` are not part of the bit string,
41    /// 0 to 7. They are sent as zero.
42    pub unused_bits: u8,
43}
44
45impl ReferencePictureSelectionIndication {
46    /// An RPSI for an H.265 stream (RFC 7798 section 8.3): a request that the encoder use the
47    /// picture with `nuh_layer_id` (6 bits) and `pic_order_cnt_val` as its reference. The
48    /// native bit string is "a base16 representation of the 8 bits consisting of the 2 most
49    /// significant bits equal to 0 and 6 bits of nuh_layer_id, ... followed by the 32 bits
50    /// representing the value of the PicOrderCntVal (in network byte order)": ten hexadecimal
51    /// digits. RFC 7798 deprecates RPSI as a positive acknowledgement; this is the request
52    /// form, the only one it allows. A `nuh_layer_id` over 63 is refused.
53    pub fn hevc(
54        sender_ssrc: u32,
55        media_ssrc: u32,
56        payload_type: u8,
57        nuh_layer_id: u8,
58        pic_order_cnt_val: u32,
59    ) -> Result<Self> {
60        if nuh_layer_id > 0x3f {
61            return Err(Error::InvalidHeader);
62        }
63        if payload_type > RPSI_PAYLOAD_TYPE_MAX {
64            return Err(Error::WrongPayloadType);
65        }
66        let mut octets = [0u8; 5];
67        octets[0] = nuh_layer_id;
68        octets[1..].copy_from_slice(&pic_order_cnt_val.to_be_bytes());
69        let hex: String = octets.iter().map(|o| format!("{o:02X}")).collect();
70        Ok(Self {
71            sender_ssrc,
72            media_ssrc,
73            payload_type,
74            native_rpsi: Bytes::from(hex.into_bytes()),
75            unused_bits: 0,
76        })
77    }
78
79    /// The `(nuh_layer_id, PicOrderCntVal)` of an H.265 RPSI's native bit string (RFC 7798
80    /// section 8.3), `None` when it is not ten hexadecimal digits with the two high bits of
81    /// the layer octet zero.
82    pub fn hevc_picture(&self) -> Option<(u8, u32)> {
83        if self.native_rpsi.len() != 10 || self.unused_bits != 0 {
84            return None;
85        }
86        let text = std::str::from_utf8(&self.native_rpsi).ok()?;
87        let layer = u8::from_str_radix(&text[..2], 16).ok()?;
88        let poc = u32::from_str_radix(&text[2..], 16).ok()?;
89        (layer <= 0x3f).then_some((layer, poc))
90    }
91
92    /// An RPSI for a VP8 stream (RFC 7741 section 5.1) or a VP9 stream (RFC 9628 section
93    /// 5.1): the native bit string "is simply the (7- or 15-bit) Picture ID of the received
94    /// frame", as its payload descriptor carried it: 7 bits for a Picture ID below 128 unless
95    /// `extended`, 15 bits otherwise (the descriptor's M bit). The bits are left-aligned in the
96    /// octets, the low bit of the last octet unused. A Picture ID above 15 bits is refused.
97    pub fn picture_id(
98        sender_ssrc: u32,
99        media_ssrc: u32,
100        payload_type: u8,
101        picture_id: u16,
102        extended: bool,
103    ) -> Result<Self> {
104        if picture_id > 0x7fff {
105            return Err(Error::InvalidHeader);
106        }
107        if payload_type > RPSI_PAYLOAD_TYPE_MAX {
108            return Err(Error::WrongPayloadType);
109        }
110        let native_rpsi = if extended || picture_id > 0x7f {
111            Bytes::copy_from_slice(&(picture_id << 1).to_be_bytes())
112        } else {
113            Bytes::copy_from_slice(&[(picture_id as u8) << 1])
114        };
115        Ok(Self {
116            sender_ssrc,
117            media_ssrc,
118            payload_type,
119            native_rpsi,
120            unused_bits: 1,
121        })
122    }
123
124    /// The Picture ID of a VP8 or VP9 RPSI ([`Self::picture_id`]): a native bit string of 7 or
125    /// 15 bits, `None` for any other length.
126    pub fn vp8_vp9_picture_id(&self) -> Option<u16> {
127        match (self.native_rpsi.len(), self.native_rpsi_bits()) {
128            (1, 7) => Some(u16::from(self.native_rpsi[0] >> 1)),
129            (2, 15) => Some(u16::from_be_bytes([self.native_rpsi[0], self.native_rpsi[1]]) >> 1),
130            _ => None,
131        }
132    }
133
134    /// The length of the native bit string in bits.
135    pub fn native_rpsi_bits(&self) -> usize {
136        (self.native_rpsi.len() * 8).saturating_sub(self.unused_bits as usize)
137    }
138
139    fn padding_octets(&self) -> usize {
140        get_padding_size(RPSI_FCI_HEADER_LENGTH + self.native_rpsi.len())
141    }
142}
143
144impl fmt::Display for ReferencePictureSelectionIndication {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        write!(
147            f,
148            "ReferencePictureSelectionIndication {:x} {:x} pt={} {} bits",
149            self.sender_ssrc,
150            self.media_ssrc,
151            self.payload_type,
152            self.native_rpsi_bits()
153        )
154    }
155}
156
157impl Packet for ReferencePictureSelectionIndication {
158    fn header(&self) -> Header {
159        Header {
160            padding: false,
161            count: FORMAT_RPSI,
162            packet_type: PacketType::PayloadSpecificFeedback,
163            length: ((self.marshal_size() / 4) - 1) as u16,
164        }
165    }
166
167    fn destination_ssrc(&self) -> Vec<u32> {
168        vec![self.media_ssrc]
169    }
170
171    fn raw_size(&self) -> usize {
172        HEADER_LENGTH
173            + FEEDBACK_SSRCS_LENGTH
174            + RPSI_FCI_HEADER_LENGTH
175            + self.native_rpsi.len()
176            + self.padding_octets()
177    }
178
179    packet_any!(ReferencePictureSelectionIndication);
180}
181
182impl MarshalSize for ReferencePictureSelectionIndication {
183    fn marshal_size(&self) -> usize {
184        self.raw_size()
185    }
186}
187
188impl Marshal for ReferencePictureSelectionIndication {
189    fn marshal_to(&self, buf: &mut [u8]) -> Result<usize> {
190        if self.payload_type > RPSI_PAYLOAD_TYPE_MAX {
191            return Err(Error::WrongPayloadType);
192        }
193        if self.unused_bits > 7 || (self.native_rpsi.is_empty() && self.unused_bits != 0) {
194            return Err(Error::WrongPadding);
195        }
196
197        let size = self.raw_size();
198        let mut buf = put_feedback_start(
199            buf,
200            PacketType::PayloadSpecificFeedback,
201            FORMAT_RPSI,
202            size,
203            self.sender_ssrc,
204            self.media_ssrc,
205        )?;
206
207        // PB: the number of unused bits that pad the message to a multiple of 32 bits.
208        let padding_octets = self.padding_octets();
209        buf.put_u8(self.unused_bits + 8 * padding_octets as u8);
210        buf.put_u8(self.payload_type);
211        if let Some((last, head)) = self.native_rpsi.split_last() {
212            buf.put_slice(head);
213            // RFC 4585 6.3.3.2: the padding bits are set to 0.
214            buf.put_u8(last & (0xffu8 << self.unused_bits));
215        }
216        buf.put_bytes(0, padding_octets);
217        Ok(size)
218    }
219}
220
221impl Unmarshal for ReferencePictureSelectionIndication {
222    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
223    where
224        Self: Sized,
225        B: Buf,
226    {
227        let (sender_ssrc, media_ssrc, mut fci) =
228            read_feedback(raw_packet, PacketType::PayloadSpecificFeedback, FORMAT_RPSI)?;
229        // One indication: PB, payload type, and the string padded to a word.
230        if fci.len() < 4 {
231            return Err(Error::PacketTooShort);
232        }
233        if !fci.len().is_multiple_of(4) {
234            return Err(Error::WrongPadding);
235        }
236
237        let padding_bits = fci.get_u8() as usize;
238        // The bit before the payload type is ignored on reception.
239        let payload_type = fci.get_u8() & RPSI_PAYLOAD_TYPE_MAX;
240        if padding_bits > fci.len() * 8 {
241            return Err(Error::WrongPadding);
242        }
243
244        let mut native_rpsi = fci.split_to(fci.len() - padding_bits / 8);
245        let unused_bits = (padding_bits % 8) as u8;
246        if unused_bits != 0 {
247            // The padding bits are not part of the string, whatever the sender put there.
248            let mut octets = native_rpsi.to_vec();
249            if let Some(last) = octets.last_mut() {
250                *last &= 0xffu8 << unused_bits;
251            }
252            native_rpsi = Bytes::from(octets);
253        }
254
255        Ok(ReferencePictureSelectionIndication {
256            sender_ssrc,
257            media_ssrc,
258            payload_type,
259            native_rpsi,
260            unused_bits,
261        })
262    }
263}
264
265#[cfg(test)]
266mod hevc_test {
267    use super::*;
268
269    /// RFC 7798 section 8.3: the H.265 native RPSI bit string is the base16 text of the layer
270    /// octet (two zero bits, six of `nuh_layer_id`) and the 32-bit PicOrderCntVal, network
271    /// order; RPSI is a reference picture selection request.
272    #[test]
273    fn an_hevc_rpsi_names_the_layer_and_picture_order_count_in_base16() {
274        let rpsi =
275            ReferencePictureSelectionIndication::hevc(0x0102_0304, 0x0a0b_0c0d, 49, 5, 0x0012_34ab)
276                .unwrap();
277        assert_eq!(&b"05001234AB"[..], &rpsi.native_rpsi[..]);
278        assert_eq!(80, rpsi.native_rpsi_bits());
279        let raw = rpsi.marshal().unwrap();
280        let read = ReferencePictureSelectionIndication::unmarshal(&mut raw.freeze()).unwrap();
281        assert_eq!(Some((5, 0x0012_34ab)), read.hevc_picture());
282        assert_eq!(49, read.payload_type);
283
284        assert!(ReferencePictureSelectionIndication::hevc(1, 2, 49, 64, 0).is_err());
285        let not_hevc = ReferencePictureSelectionIndication {
286            native_rpsi: Bytes::from_static(b"C0000000000"),
287            ..rpsi
288        };
289        assert_eq!(None, not_hevc.hevc_picture());
290    }
291}
292
293#[cfg(test)]
294mod picture_id_test {
295    use super::*;
296
297    /// RFC 7741 section 5.1 and RFC 9628 section 5.1: the VP8 and VP9 native RPSI bit string
298    /// is the 7- or 15-bit Picture ID of the frame, left-aligned, one bit of padding in the
299    /// last octet; it reads back after the wire.
300    #[test]
301    fn a_vp8_or_vp9_rpsi_carries_the_7_or_15_bit_picture_id() {
302        let short = ReferencePictureSelectionIndication::picture_id(1, 2, 96, 0x55, false).unwrap();
303        assert_eq!(&[0xAA][..], &short.native_rpsi[..]);
304        assert_eq!(7, short.native_rpsi_bits());
305        let long = ReferencePictureSelectionIndication::picture_id(1, 2, 96, 0x1234, true).unwrap();
306        assert_eq!(&[0x24, 0x68][..], &long.native_rpsi[..]);
307        assert_eq!(15, long.native_rpsi_bits());
308        // A Picture ID that needs 15 bits takes them whatever `extended` says.
309        let wide = ReferencePictureSelectionIndication::picture_id(1, 2, 96, 0x80, false).unwrap();
310        assert_eq!(15, wide.native_rpsi_bits());
311        for (rpsi, id) in [(short, 0x55), (long, 0x1234), (wide, 0x80)] {
312            let raw = rpsi.marshal().unwrap();
313            let read = ReferencePictureSelectionIndication::unmarshal(&mut raw.freeze()).unwrap();
314            assert_eq!(Some(id), read.vp8_vp9_picture_id());
315        }
316        assert!(ReferencePictureSelectionIndication::picture_id(1, 2, 96, 0x8000, true).is_err());
317    }
318}
319
320#[cfg(test)]
321mod test {
322    use super::*;
323
324    #[test]
325    fn rpsi_round_trips_with_pb_counting_the_padding_bits() {
326        // 13 bits of native string: two octets, three bits unused, no padding octet.
327        let rpsi = ReferencePictureSelectionIndication {
328            sender_ssrc: 0x01020304,
329            media_ssrc: 0x0a0b0c0d,
330            payload_type: 96,
331            native_rpsi: Bytes::from_static(&[0xab, 0xc8]),
332            unused_bits: 3,
333        };
334        let raw = rpsi.marshal().unwrap();
335        assert_eq!(
336            &[
337                0x83, 0xce, 0x00, 0x03, // v=2, FMT=3, PSFB, len=3
338                0x01, 0x02, 0x03, 0x04, // sender
339                0x0a, 0x0b, 0x0c, 0x0d, // media source
340                0x03, 0x60, 0xab, 0xc8, // PB=3, pt 96, 13 bits + 3 padding bits
341            ][..],
342            &raw[..]
343        );
344        assert_eq!(13, rpsi.native_rpsi_bits());
345        assert_eq!(
346            rpsi,
347            ReferencePictureSelectionIndication::unmarshal(&mut raw.freeze()).unwrap()
348        );
349
350        // Three whole octets: three octets of padding, PB = 24.
351        let rpsi = ReferencePictureSelectionIndication {
352            native_rpsi: Bytes::from_static(&[1, 2, 3]),
353            unused_bits: 0,
354            ..rpsi
355        };
356        let raw = rpsi.marshal().unwrap();
357        assert_eq!(&[0x18, 0x60, 1, 2, 3, 0, 0, 0][..], &raw[12..]);
358        assert_eq!(
359            rpsi,
360            ReferencePictureSelectionIndication::unmarshal(&mut raw.freeze()).unwrap()
361        );
362    }
363
364    // RFC 4585 6.3.3.2: padding bits are zero when sent and are not part of the string.
365    #[test]
366    fn padding_bits_are_sent_as_zero_and_ignored_when_received() {
367        let dirty = ReferencePictureSelectionIndication {
368            sender_ssrc: 1,
369            media_ssrc: 2,
370            payload_type: 96,
371            native_rpsi: Bytes::from_static(&[0xff, 0xff]),
372            unused_bits: 4,
373        };
374        let raw = dirty.marshal().unwrap();
375        assert_eq!(&[0x04, 0x60, 0xff, 0xf0][..], &raw[12..]);
376
377        // Padding bits set, and the zero bit before the payload type set.
378        let mut raw = Bytes::from_static(&[
379            0x83, 0xce, 0x00, 0x03, 0, 0, 0, 1, 0, 0, 0, 2, 0x04, 0xe0, 0xff, 0xff,
380        ]);
381        let rpsi = ReferencePictureSelectionIndication::unmarshal(&mut raw).unwrap();
382        assert_eq!(96, rpsi.payload_type);
383        assert_eq!(&[0xff, 0xf0][..], &rpsi.native_rpsi[..]);
384        assert_eq!(4, rpsi.unused_bits);
385    }
386
387    #[test]
388    fn malformed_indications_are_refused() {
389        let bad_pt = ReferencePictureSelectionIndication {
390            payload_type: 128,
391            ..Default::default()
392        };
393        assert_eq!(Err(Error::WrongPayloadType), bad_pt.marshal());
394        let bad_bits = ReferencePictureSelectionIndication {
395            unused_bits: 1,
396            ..Default::default()
397        };
398        assert_eq!(Err(Error::WrongPadding), bad_bits.marshal());
399
400        // No FCI.
401        let mut raw = Bytes::from_static(&[0x83, 0xce, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2]);
402        assert_eq!(
403            Err(Error::PacketTooShort),
404            ReferencePictureSelectionIndication::unmarshal(&mut raw)
405        );
406        // PB claims more padding bits than the message has after its two fixed octets.
407        let mut raw = Bytes::from_static(&[0x83, 0xce, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 17, 96, 0, 0]);
408        assert_eq!(
409            Err(Error::WrongPadding),
410            ReferencePictureSelectionIndication::unmarshal(&mut raw)
411        );
412    }
413}