1use 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
13const RPSI_FCI_HEADER_LENGTH: usize = 2;
15const RPSI_PAYLOAD_TYPE_MAX: u8 = 0x7f;
16
17#[derive(Debug, PartialEq, Eq, Default, Clone)]
30pub struct ReferencePictureSelectionIndication {
31 pub sender_ssrc: u32,
33 pub media_ssrc: u32,
35 pub payload_type: u8,
37 pub native_rpsi: Bytes,
40 pub unused_bits: u8,
43}
44
45impl ReferencePictureSelectionIndication {
46 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 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 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 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 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 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 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 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 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 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 #[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 #[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 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 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, 0x01, 0x02, 0x03, 0x04, 0x0a, 0x0b, 0x0c, 0x0d, 0x03, 0x60, 0xab, 0xc8, ][..],
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 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 #[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 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 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 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}