1use std::error::Error;
2use std::fmt;
3
4use crate::rtp_::{extend_u7, extend_u8, extend_u15};
5
6use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer};
7
8pub const VP8_HEADER_SIZE: usize = 1;
9
10const PICTURE_ID_SHORT_MAX: u16 = 0x7f; const PICTURE_ID_MAX: u16 = 0x7fff; const PICTURE_ID_SHORT_MASK: u8 = PICTURE_ID_SHORT_MAX as u8;
13const KEY_IDX_MASK: u8 = 0x1f; const VP8_PATCH_BYTES: usize = 4; #[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct Vp8Patch {
23 len: u8,
24 offsets: [u8; VP8_PATCH_BYTES],
25 bytes: [u8; VP8_PATCH_BYTES],
26}
27
28impl Vp8Patch {
29 fn new() -> Self {
30 Self {
31 len: 0,
32 offsets: [0; VP8_PATCH_BYTES],
33 bytes: [0; VP8_PATCH_BYTES],
34 }
35 }
36
37 fn push(&mut self, offset: usize, byte: u8) {
38 let index = usize::from(self.len);
39 debug_assert!(index < self.offsets.len());
40 debug_assert!(offset <= usize::from(u8::MAX));
41
42 self.offsets[index] = offset as u8;
43 self.bytes[index] = byte;
44 self.len += 1;
45 }
46
47 pub(crate) fn copy_to(&self, payload: &[u8], dst: &mut [u8]) {
53 assert_eq!(payload.len(), dst.len());
54
55 dst.copy_from_slice(payload);
56
57 for i in 0..usize::from(self.len) {
58 dst[usize::from(self.offsets[i])] = self.bytes[i];
59 }
60 }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum Vp8DescriptorError {
67 ShortPayload,
69 MalformedDescriptor,
71}
72
73impl fmt::Display for Vp8DescriptorError {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 Self::ShortPayload => write!(f, "VP8 payload is too short"),
77 Self::MalformedDescriptor => write!(f, "VP8 payload descriptor is malformed"),
78 }
79 }
80}
81
82impl Error for Vp8DescriptorError {}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum Vp8PatchError {
88 PictureIdMissing,
90 PictureIdTooLarge,
92 Tl0PicIdxMissing,
94 KeyIdxMissing,
96 KeyIdxTooLarge,
98}
99
100impl fmt::Display for Vp8PatchError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 match self {
103 Self::PictureIdMissing => write!(f, "VP8 payload descriptor has no PictureID"),
104 Self::PictureIdTooLarge => write!(f, "VP8 PictureID does not fit descriptor width"),
105 Self::Tl0PicIdxMissing => write!(f, "VP8 payload descriptor has no TL0PICIDX"),
106 Self::KeyIdxMissing => write!(f, "VP8 payload descriptor has no KEYIDX"),
107 Self::KeyIdxTooLarge => write!(f, "VP8 KEYIDX must fit in 5 bits"),
108 }
109 }
110}
111
112impl Error for Vp8PatchError {}
113
114#[derive(Clone, Copy, Debug)]
116pub struct Vp8PatchBuilder {
117 descriptor: Vp8Descriptor,
118 picture_id: Option<u16>,
119 tl0_pic_idx: Option<u8>,
120 key_idx: Option<u8>,
121}
122
123impl Vp8PatchBuilder {
124 pub fn picture_id(mut self, picture_id: u16) -> Self {
133 self.picture_id = Some(picture_id);
134 self
135 }
136
137 pub fn tl0_pic_idx(mut self, tl0_pic_idx: u8) -> Self {
142 self.tl0_pic_idx = Some(tl0_pic_idx);
143 self
144 }
145
146 pub fn key_idx(mut self, key_idx: u8) -> Self {
154 self.key_idx = Some(key_idx);
155 self
156 }
157
158 pub fn build(self) -> Result<Vp8Patch, Vp8PatchError> {
169 let mut patch = Vp8Patch::new();
170
171 if let Some(picture_id) = self.picture_id {
172 let Some(parsed) = self.descriptor.picture_id else {
173 return Err(Vp8PatchError::PictureIdMissing);
174 };
175 if picture_id > PICTURE_ID_MAX {
176 return Err(Vp8PatchError::PictureIdTooLarge);
177 }
178 if !parsed.is_15_bit && picture_id > PICTURE_ID_SHORT_MAX {
179 return Err(Vp8PatchError::PictureIdTooLarge);
180 }
181 if parsed.is_15_bit {
182 patch.push(
183 parsed.offset,
184 0x80 | ((picture_id >> 8) as u8 & PICTURE_ID_SHORT_MASK),
185 );
186 patch.push(parsed.offset + 1, picture_id as u8);
187 } else {
188 patch.push(parsed.offset, picture_id as u8);
189 }
190 }
191
192 if let Some(tl0_pic_idx) = self.tl0_pic_idx {
193 let Some(parsed) = self.descriptor.tl0_pic_idx else {
194 return Err(Vp8PatchError::Tl0PicIdxMissing);
195 };
196 patch.push(parsed.offset, tl0_pic_idx);
197 }
198
199 if let Some(key_idx) = self.key_idx {
200 let Some(parsed) = self.descriptor.key_idx else {
201 return Err(Vp8PatchError::KeyIdxMissing);
202 };
203 if key_idx > KEY_IDX_MASK {
204 return Err(Vp8PatchError::KeyIdxTooLarge);
205 }
206 patch.push(parsed.offset, (parsed.value & !KEY_IDX_MASK) | key_idx);
207 }
208
209 Ok(patch)
210 }
211}
212
213#[derive(Clone, Copy, Debug)]
219pub struct Vp8Descriptor {
220 payload_offset: usize,
221 picture_id: Option<Vp8PictureId>,
222 tl0_pic_idx: Option<Vp8Field>,
223 key_idx: Option<Vp8Field>,
224}
225
226#[derive(Clone, Copy, Debug)]
227struct Vp8Field {
228 value: u8,
229 offset: usize,
230}
231
232#[derive(Clone, Copy, Debug)]
233struct Vp8PictureId {
234 value: u16,
235 offset: usize,
236 is_15_bit: bool,
237}
238
239impl Vp8Descriptor {
240 pub fn parse(payload: &[u8]) -> Result<Self, Vp8DescriptorError> {
251 let Some(required) = payload.first() else {
252 return Err(Vp8DescriptorError::ShortPayload);
253 };
254
255 let mut descriptor = Self {
256 payload_offset: 1,
257 picture_id: None,
258 tl0_pic_idx: None,
259 key_idx: None,
260 };
261
262 if required & 0x80 != 0 {
263 let extension = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?;
264 let has_picture_id = extension & 0x80 != 0;
265 let has_tl0_pic_idx = extension & 0x40 != 0;
266 let has_tid = extension & 0x20 != 0;
267 let has_key_idx = extension & 0x10 != 0;
268
269 if has_tl0_pic_idx && !has_tid {
270 return Err(Vp8DescriptorError::MalformedDescriptor);
271 }
272
273 if has_picture_id {
274 let picture_id_offset = descriptor.payload_offset;
275 let picture_id = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?;
276 let is_15_bit = picture_id & 0x80 != 0;
277 let value = if is_15_bit {
278 let picture_id_low =
279 read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?;
280 (u16::from(picture_id & PICTURE_ID_SHORT_MASK) << 8) | u16::from(picture_id_low)
281 } else {
282 u16::from(picture_id & PICTURE_ID_SHORT_MASK)
283 };
284 descriptor.picture_id = Some(Vp8PictureId {
285 value,
286 offset: picture_id_offset,
287 is_15_bit,
288 });
289 }
290
291 if has_tl0_pic_idx {
292 let offset = descriptor.payload_offset;
293 let value = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?;
294 descriptor.tl0_pic_idx = Some(Vp8Field { value, offset });
295 }
296
297 if has_tid || has_key_idx {
298 let offset = descriptor.payload_offset;
299 let value = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?;
300 if has_key_idx {
301 descriptor.key_idx = Some(Vp8Field { value, offset });
302 }
303 }
304 }
305
306 if descriptor.payload_offset >= payload.len() {
307 return Err(Vp8DescriptorError::ShortPayload);
308 }
309
310 Ok(descriptor)
311 }
312
313 pub const fn picture_id(&self) -> Option<u16> {
315 match self.picture_id {
316 Some(picture_id) => Some(picture_id.value),
317 None => None,
318 }
319 }
320
321 pub const fn tl0_pic_idx(&self) -> Option<u8> {
323 match self.tl0_pic_idx {
324 Some(tl0_pic_idx) => Some(tl0_pic_idx.value),
325 None => None,
326 }
327 }
328
329 pub const fn key_idx(&self) -> Option<u8> {
331 match self.key_idx {
332 Some(key_idx) => Some(key_idx.value & KEY_IDX_MASK),
333 None => None,
334 }
335 }
336
337 pub fn starts_keyframe(&self, payload: &[u8]) -> bool {
342 let Some(required) = payload.first() else {
343 return false;
344 };
345
346 if required & 0x10 == 0 || required & 0x07 != 0 {
347 return false;
348 }
349
350 payload
351 .get(self.payload_offset)
352 .is_some_and(|header| header & 0x01 == 0)
353 }
354
355 pub fn patch(&self) -> Vp8PatchBuilder {
357 Vp8PatchBuilder {
358 descriptor: *self,
359 picture_id: None,
360 tl0_pic_idx: None,
361 key_idx: None,
362 }
363 }
364}
365
366fn read_vp8_descriptor_byte(payload: &[u8], offset: &mut usize) -> Result<u8, Vp8DescriptorError> {
367 let byte = payload
368 .get(*offset)
369 .ok_or(Vp8DescriptorError::ShortPayload)?;
370 *offset += 1;
371 Ok(*byte)
372}
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376pub struct Vp8CodecExtra {
377 pub discardable: bool,
380 pub sync: bool,
382 pub layer_index: u8,
384 pub picture_id: Option<u64>,
386 pub tl0_picture_id: Option<u64>,
388 pub is_keyframe: bool,
394}
395
396pub fn detect_vp8_keyframe(payload: &[u8]) -> bool {
404 if payload.is_empty() {
405 return false;
406 }
407 let b0 = payload[0];
408 let s = (b0 & 0x10) >> 4; let pid = b0 & 0x07; if s != 1 || pid != 0 {
412 return false;
413 }
414 let x = (b0 & 0x80) >> 7; let mut idx = 1;
416 if x == 1 {
417 if idx >= payload.len() {
418 return false;
419 }
420 let ext = payload[idx];
421 idx += 1;
422 let i = (ext & 0x80) >> 7; let l = (ext & 0x40) >> 6; let t = (ext & 0x20) >> 5; let k = (ext & 0x10) >> 4; if i == 1 {
427 if idx >= payload.len() {
428 return false;
429 }
430 if payload[idx] & 0x80 != 0 {
431 idx += 2; } else {
433 idx += 1; }
435 }
436 if l == 1 {
437 idx += 1; }
439 if t == 1 || k == 1 {
440 idx += 1; }
442 }
443 if idx >= payload.len() {
444 return false;
445 }
446 payload[idx] & 0x01 == 0
449}
450
451#[derive(Default, Debug, Copy, Clone)]
458pub struct Vp8Packetizer {
459 enable_picture_id: bool,
460 picture_id: u16,
461}
462
463impl Packetizer for Vp8Packetizer {
464 fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result<Vec<Vec<u8>>, PacketError> {
466 if payload.is_empty() || mtu == 0 {
467 return Ok(vec![]);
468 }
469
470 let using_header_size = if self.enable_picture_id {
491 if self.picture_id == 0 || self.picture_id < 128 {
492 VP8_HEADER_SIZE + 2
493 } else {
494 VP8_HEADER_SIZE + 3
495 }
496 } else {
497 VP8_HEADER_SIZE
498 };
499
500 let max_fragment_size = mtu as isize - using_header_size as isize;
501 let mut payload_data_remaining = payload.len() as isize;
502 let mut payload_data_index: usize = 0;
503 let mut payloads = vec![];
504
505 if std::cmp::min(max_fragment_size, payload_data_remaining) <= 0 {
507 return Ok(payloads);
508 }
509
510 let mut first = true;
511 while payload_data_remaining > 0 {
512 let current_fragment_size =
513 std::cmp::min(max_fragment_size, payload_data_remaining) as usize;
514 let mut out = Vec::with_capacity(using_header_size + current_fragment_size);
515 let mut buf = [0u8; 4];
516 if first {
517 buf[0] = 0x10;
518 first = false;
519 }
520
521 if self.enable_picture_id {
522 if using_header_size == VP8_HEADER_SIZE + 2 {
523 buf[0] |= 0x80;
524 buf[1] |= 0x80;
525 buf[2] |= (self.picture_id & u16::from(PICTURE_ID_SHORT_MASK)) as u8;
526 } else if using_header_size == VP8_HEADER_SIZE + 3 {
527 buf[0] |= 0x80;
528 buf[1] |= 0x80;
529 buf[2] |=
530 0x80 | ((self.picture_id >> 8) & u16::from(PICTURE_ID_SHORT_MASK)) as u8;
531 buf[3] |= (self.picture_id & 0xFF) as u8;
532 }
533 }
534
535 out.extend_from_slice(&buf[..using_header_size]);
536
537 out.extend_from_slice(
538 &payload[payload_data_index..payload_data_index + current_fragment_size],
539 );
540 payloads.push(out);
541
542 payload_data_remaining -= current_fragment_size as isize;
543 payload_data_index += current_fragment_size;
544 }
545
546 self.picture_id += 1;
547 self.picture_id &= PICTURE_ID_MAX;
548
549 Ok(payloads)
550 }
551
552 fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool {
553 last
554 }
555}
556
557#[derive(PartialEq, Eq, Debug, Default, Clone)]
564pub struct Vp8Depacketizer {
565 pub x: u8,
568 pub n: u8,
570 pub s: u8,
572 pub pid: u8,
574
575 pub i: u8,
578 pub l: u8,
580 pub t: u8,
582 pub k: u8,
584
585 pub picture_id: u16,
588 pub extended_pid: Option<u64>,
590
591 pub tl0_pic_idx: u8,
593 pub extended_tl0_pic_idx: Option<u64>,
595 pub tid: u8,
597 pub y: u8,
599 pub key_idx: u8,
601
602 pub p: u8,
606}
607
608impl Depacketizer for Vp8Depacketizer {
609 fn out_size_hint(&self, packets_size: usize) -> Option<usize> {
610 Some(packets_size)
611 }
612
613 fn depacketize(
616 &mut self,
617 packet: &[u8],
618 out: &mut Vec<u8>,
619 extra: &mut CodecExtra,
620 ) -> Result<(), PacketError> {
621 let payload_len = packet.len();
622 let mut reader = (packet, 0);
641 let mut payload_index = 0;
642
643 let mut b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
644 payload_index += 1;
645
646 self.x = (b & 0x80) >> 7;
647 self.n = (b & 0x20) >> 5;
648 self.s = (b & 0x10) >> 4;
649 self.pid = b & 0x07;
650
651 let (i, l, t, k) = if self.x == 1 {
652 b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
653 payload_index += 1;
654 let i = (b & 0x80) >> 7;
655 let l = (b & 0x40) >> 6;
656 let t = (b & 0x20) >> 5;
657 let k = (b & 0x10) >> 4;
658
659 if l == 1 && t == 0 {
660 return Err(PacketError::ErrVP8CorruptedPacket);
661 }
662
663 (i, l, t, k)
664 } else {
665 (0, 0, 0, 0)
666 };
667 self.i = i;
668 self.l = l;
669 self.t = t;
670 self.k = k;
671
672 if self.i == 1 {
673 b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
674 payload_index += 1;
675 let previous_picture_id = u64::from(self.picture_id);
676 let previous = self.extended_pid.map(|_| previous_picture_id);
677 let next = if b & 0x80 > 0 {
679 let x = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
681 self.picture_id = (((b & PICTURE_ID_SHORT_MASK) as u16) << 8) | (x as u16);
682 payload_index += 1;
683 extend_u15(previous, self.picture_id)
684 } else {
685 self.picture_id = b as u16;
686 extend_u7(previous, b)
687 };
688
689 self.extended_pid = Some(match self.extended_pid {
693 Some(previous) => previous.wrapping_add(next.wrapping_sub(previous_picture_id)),
694 None => next,
695 });
696 }
697
698 if payload_index >= payload_len {
699 return Err(PacketError::ErrShortPacket);
700 }
701
702 if self.l == 1 {
703 self.tl0_pic_idx = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
704 self.extended_tl0_pic_idx =
705 Some(extend_u8(self.extended_tl0_pic_idx, self.tl0_pic_idx));
706 payload_index += 1;
707 }
708
709 if payload_index >= payload_len {
710 return Err(PacketError::ErrShortPacket);
711 }
712
713 if self.t == 1 || self.k == 1 {
714 let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
715 if self.t == 1 {
716 self.tid = b >> 6;
717 self.y = (b >> 5) & 0x1;
718 }
719 if self.k == 1 {
720 self.key_idx = b & KEY_IDX_MASK;
721 }
722 payload_index += 1;
723 }
724
725 if payload_index >= packet.len() {
726 return Err(PacketError::ErrShortPacket);
727 }
728
729 out.extend_from_slice(&packet[payload_index..]);
730
731 self.p = if self.s == 1 && self.pid == 0 {
754 b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
755 payload_index += 1;
756 b & 1
757 } else {
758 1
759 };
760
761 let is_keyframe = if let CodecExtra::Vp8(e) = extra {
762 e.is_keyframe | (self.p == 0)
763 } else {
764 self.p == 0
765 };
766
767 *extra = CodecExtra::Vp8(Vp8CodecExtra {
768 discardable: self.n == 1,
769 sync: self.y == 1,
770 layer_index: self.tid,
771 picture_id: if self.i == 1 { self.extended_pid } else { None },
772 tl0_picture_id: if self.l == 1 {
773 self.extended_tl0_pic_idx
774 } else {
775 None
776 },
777 is_keyframe,
778 });
779
780 let _ = payload_index;
781
782 Ok(())
783 }
784
785 fn is_partition_head(&self, payload: &[u8]) -> bool {
787 if payload.is_empty() {
788 false
789 } else {
790 (payload[0] & 0x10) != 0
791 }
792 }
793
794 fn is_partition_tail(&self, marker: bool, _payload: &[u8]) -> bool {
795 marker
796 }
797}
798
799#[cfg(test)]
800mod test {
801 use super::*;
802
803 #[test]
804 fn test_vp8_unmarshal() -> Result<(), PacketError> {
805 let mut pck = Vp8Depacketizer::default();
806 let mut extra = CodecExtra::None;
807
808 let empty_bytes = &[];
810 let mut payload = Vec::new();
811 let result = pck.depacketize(empty_bytes, &mut payload, &mut extra);
812 assert!(result.is_err(), "Result should be err in case of error");
813
814 let small_bytes = &[0x00, 0x11, 0x22];
816 let mut payload = Vec::new();
817 pck.depacketize(small_bytes, &mut payload, &mut extra)
818 .expect("Small packet");
819 assert_eq!(payload, [0x11, 0x22]);
820
821 let small_bytes = &[0x00];
823 let mut payload = Vec::new();
824 let result = pck.depacketize(small_bytes, &mut payload, &mut extra);
825 assert!(result.is_err(), "Result should be err in case of error");
826
827 let raw_bytes = &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x90];
829 let mut payload = Vec::new();
830 pck.depacketize(raw_bytes, &mut payload, &mut extra)
831 .expect("Normal packet");
832 assert!(!payload.is_empty(), "Payload must be not empty");
833
834 let raw_bytes = &[0x80, 0x00, 0x00, 0x00];
836 let mut payload = Vec::new();
837 pck.depacketize(raw_bytes, &mut payload, &mut extra)
838 .expect("Only X");
839 assert!(!payload.is_empty(), "Payload must be not empty");
840 assert_eq!(pck.x, 1, "X must be 1");
841 assert_eq!(pck.i, 0, "I must be 0");
842 assert_eq!(pck.l, 0, "L must be 0");
843 assert_eq!(pck.t, 0, "T must be 0");
844 assert_eq!(pck.k, 0, "K must be 0");
845 assert_eq!(pck.p, 1, "P must be 1");
846
847 let raw_bytes = &[0x80, 0x80, 0x81, 0x00, 0x00];
849 let mut payload = Vec::new();
850 pck.depacketize(raw_bytes, &mut payload, &mut extra)
851 .expect("X and I, PID 16bits");
852 assert!(!payload.is_empty(), "Payload must be not empty");
853 assert_eq!(pck.x, 1, "X must be 1");
854 assert_eq!(pck.i, 1, "I must be 1");
855 assert_eq!(pck.l, 0, "L must be 0");
856 assert_eq!(pck.t, 0, "T must be 0");
857 assert_eq!(pck.k, 0, "K must be 0");
858 assert_eq!(pck.p, 1, "P must be 1");
859
860 let raw_bytes = &[0x80, 0x40, 0x00, 0x00];
862 let mut payload = Vec::new();
863 assert_eq!(
864 pck.depacketize(raw_bytes, &mut payload, &mut extra),
865 Err(PacketError::ErrVP8CorruptedPacket)
866 );
867
868 let raw_bytes = &[0x00, 0x11, 0x22];
869 let mut payload = Vec::new();
870 pck.depacketize(raw_bytes, &mut payload, &mut extra)
871 .expect("valid packet after malformed descriptor");
872 assert_eq!(payload, [0x11, 0x22]);
873
874 let raw_bytes = &[0x80, 0x20, 0x00, 0x00];
876 let mut payload = Vec::new();
877 pck.depacketize(raw_bytes, &mut payload, &mut extra)
878 .expect("X and T");
879 assert!(!payload.is_empty(), "Payload must be not empty");
880 assert_eq!(pck.x, 1, "X must be 1");
881 assert_eq!(pck.i, 0, "I must be 0");
882 assert_eq!(pck.l, 0, "L must be 0");
883 assert_eq!(pck.t, 1, "T must be 1");
884 assert_eq!(pck.k, 0, "K must be 0");
885 assert_eq!(pck.p, 1, "P must be 1");
886
887 let raw_bytes = &[0x80, 0x10, 0x00, 0x00];
889 let mut payload = Vec::new();
890 pck.depacketize(raw_bytes, &mut payload, &mut extra)
891 .expect("X and K");
892 assert!(!payload.is_empty(), "Payload must be not empty");
893 assert_eq!(pck.x, 1, "X must be 1");
894 assert_eq!(pck.i, 0, "I must be 0");
895 assert_eq!(pck.l, 0, "L must be 0");
896 assert_eq!(pck.t, 0, "T must be 0");
897 assert_eq!(pck.k, 1, "K must be 1");
898 assert_eq!(pck.p, 1, "P must be 1");
899
900 let raw_bytes = &[0xff, 0xff, 0x00, 0x00, 0x00, 0x00];
902 let mut payload = Vec::new();
903 pck.depacketize(raw_bytes, &mut payload, &mut extra)
904 .expect("all flags and 8bit picture_id");
905 assert!(!payload.is_empty(), "Payload must be not empty");
906 assert_eq!(pck.x, 1, "X must be 1");
907 assert_eq!(pck.i, 1, "I must be 1");
908 assert_eq!(pck.l, 1, "L must be 1");
909 assert_eq!(pck.t, 1, "T must be 1");
910 assert_eq!(pck.k, 1, "K must be 1");
911 assert_eq!(pck.p, 1, "P must be 1");
912
913 let raw_bytes = &[0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00];
915 let mut payload = Vec::new();
916 pck.depacketize(raw_bytes, &mut payload, &mut extra)
917 .expect("all flags and 16bit picture_id");
918 assert!(!payload.is_empty(), "Payload must be not empty");
919 assert_eq!(pck.x, 1, "X must be 1");
920 assert_eq!(pck.i, 1, "I must be 1");
921 assert_eq!(pck.l, 1, "L must be 1");
922 assert_eq!(pck.t, 1, "T must be 1");
923 assert_eq!(pck.k, 1, "K must be 1");
924 assert_eq!(pck.p, 1, "P must be 1");
925
926 let raw_bytes = &[0x90, 0x80, 0x11, 0x10, 0x00, 0x00, 0x00];
928 let mut payload = Vec::new();
929 pck.depacketize(raw_bytes, &mut payload, &mut extra)
930 .expect("all flags and 16bit picture_id");
931 assert!(!payload.is_empty(), "Payload must be not empty");
932 assert_eq!(pck.x, 1, "X must be 1");
933 assert_eq!(pck.i, 1, "I must be 1");
934 assert_eq!(pck.l, 0, "L must be 0");
935 assert_eq!(pck.t, 0, "T must be 0");
936 assert_eq!(pck.k, 0, "K must be 0");
937 assert_eq!(pck.p, 0, "P must be 0");
938
939 Ok(())
940 }
941
942 #[test]
943 fn test_vp8_payload() -> Result<(), PacketError> {
944 let tests: Vec<(&str, Vp8Packetizer, usize, Vec<&[u8]>, Vec<Vec<&[u8]>>)> = vec![
945 (
946 "WithoutPictureID",
947 Vp8Packetizer::default(),
948 2,
949 vec![&[0x90, 0x90, 0x90], &[0x91, 0x91]],
950 vec![
951 vec![&[0x10, 0x90], &[0x00, 0x90], &[0x00, 0x90]],
952 vec![&[0x10, 0x91], &[0x00, 0x91]],
953 ],
954 ),
955 (
956 "WithPictureID_1byte",
957 Vp8Packetizer {
958 enable_picture_id: true,
959 picture_id: 0x20,
960 },
961 5,
962 vec![&[0x90, 0x90, 0x90], &[0x91, 0x91]],
963 vec![
964 vec![&[0x90, 0x80, 0x20, 0x90, 0x90], &[0x80, 0x80, 0x20, 0x90]],
965 vec![&[0x90, 0x80, 0x21, 0x91, 0x91]],
966 ],
967 ),
968 (
969 "WithPictureID_2bytes",
970 Vp8Packetizer {
971 enable_picture_id: true,
972 picture_id: 0x120,
973 },
974 6,
975 vec![&[0x90, 0x90, 0x90], &[0x91, 0x91]],
976 vec![
977 vec![
978 &[0x90, 0x80, 0x81, 0x20, 0x90, 0x90],
979 &[0x80, 0x80, 0x81, 0x20, 0x90],
980 ],
981 vec![&[0x90, 0x80, 0x81, 0x21, 0x91, 0x91]],
982 ],
983 ),
984 ];
985
986 for (name, mut pck, mtu, payloads, expected) in tests {
987 for (i, payload) in payloads.iter().enumerate() {
988 let actual = pck.packetize(mtu, payload)?;
989 assert_eq!(expected[i], actual, "{name}: Generated packet[{i}] differs");
990 }
991 }
992
993 Ok(())
994 }
995
996 #[test]
997 fn test_vp8_payload_eror() -> Result<(), PacketError> {
998 let mut pck = Vp8Packetizer::default();
999 let empty = &[];
1000 let payload = &[0x90, 0x90, 0x90];
1001
1002 let result = pck.packetize(1, empty)?;
1004 assert!(result.is_empty(), "Generated payload should be empty");
1005
1006 let result = pck.packetize(1, payload)?;
1008 assert_eq!(result.len(), 0, "Generated payload should be empty");
1009
1010 let result = pck.packetize(2, payload)?;
1012 assert_eq!(
1013 result.len(),
1014 payload.len(),
1015 "Generated payload should be the same size as original payload size"
1016 );
1017
1018 Ok(())
1019 }
1020
1021 #[test]
1022 fn test_vp8_partition_head_checker_is_partition_head() -> Result<(), PacketError> {
1023 let vp8 = Vp8Depacketizer::default();
1024
1025 assert!(
1027 !vp8.is_partition_head(&[0x00]),
1028 "Small packet should not be the head of a new partition"
1029 );
1030
1031 assert!(
1033 vp8.is_partition_head(&[0x10, 0x00, 0x00, 0x00]),
1034 "Packet with S flag should be the head of a new partition"
1035 );
1036
1037 assert!(
1039 !vp8.is_partition_head(&[0x00, 0x00, 0x00, 0x00]),
1040 "Packet without S flag should not be the head of a new partition"
1041 );
1042
1043 Ok(())
1044 }
1045
1046 fn rewrite_payload(
1047 payload: &[u8],
1048 patch: impl FnOnce(Vp8PatchBuilder) -> Vp8PatchBuilder,
1049 ) -> Result<Vec<u8>, Vp8PatchError> {
1050 let descriptor = Vp8Descriptor::parse(payload).expect("valid VP8 descriptor");
1051 let patch = patch(descriptor.patch()).build()?;
1052
1053 let mut out = vec![0; payload.len()];
1054 patch.copy_to(payload, &mut out);
1055 Ok(out)
1056 }
1057
1058 #[test]
1059 fn test_vp8_descriptor_exposes_fields() {
1060 let short = Vp8Descriptor::parse(&[0x90, 0x80, 0x42, 0x00]).unwrap();
1061 assert_eq!(short.picture_id(), Some(0x42));
1062 assert_eq!(short.tl0_pic_idx(), None);
1063 assert_eq!(short.key_idx(), None);
1064
1065 let full = Vp8Descriptor::parse(&[0x90, 0xf0, 0x92, 0x34, 0x55, 0xa7, 0x00]).unwrap();
1066 assert_eq!(full.picture_id(), Some(0x1234));
1067 assert_eq!(full.tl0_pic_idx(), Some(0x55));
1068 assert_eq!(full.key_idx(), Some(0x07));
1069 }
1070
1071 #[test]
1072 fn test_vp8_patch_updates_descriptor_fields() {
1073 assert_eq!(
1074 rewrite_payload(&[0x80, 0x80, 0x01, 0x90], |patch| {
1075 patch.picture_id(u16::from(PICTURE_ID_SHORT_MASK))
1076 })
1077 .unwrap(),
1078 [0x80, 0x80, PICTURE_ID_SHORT_MASK, 0x90]
1079 );
1080 assert_eq!(
1081 rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| {
1082 patch.picture_id(0x0234)
1083 })
1084 .unwrap(),
1085 [0x80, 0x80, 0x82, 0x34, 0x90]
1086 );
1087 assert_eq!(
1088 rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| {
1089 patch.picture_id(PICTURE_ID_MAX)
1090 })
1091 .unwrap(),
1092 [0x80, 0x80, 0xff, 0xff, 0x90]
1093 );
1094 assert_eq!(
1095 rewrite_payload(&[0x80, 0x60, 0x12, 0x00, 0x90], |patch| {
1096 patch.tl0_pic_idx(0xab)
1097 })
1098 .unwrap(),
1099 [0x80, 0x60, 0xab, 0x00, 0x90]
1100 );
1101 assert_eq!(
1102 rewrite_payload(&[0x80, 0x30, 0xaa, 0x90], |patch| {
1103 patch.key_idx(KEY_IDX_MASK)
1104 })
1105 .unwrap(),
1106 [0x80, 0x30, 0xbf, 0x90]
1107 );
1108 }
1109
1110 #[test]
1111 fn test_vp8_patch_rejects_unsupported_descriptor_shapes() {
1112 assert_eq!(
1113 Vp8Descriptor::parse(&[0x80, 0x80]).unwrap_err(),
1114 Vp8DescriptorError::ShortPayload
1115 );
1116 assert_eq!(
1117 rewrite_payload(&[0x00, 0x90], |patch| patch.picture_id(1)).unwrap_err(),
1118 Vp8PatchError::PictureIdMissing
1119 );
1120 assert_eq!(
1121 rewrite_payload(&[0x00, 0x90], |patch| {
1122 patch.picture_id(PICTURE_ID_MAX + 1)
1123 })
1124 .unwrap_err(),
1125 Vp8PatchError::PictureIdMissing
1126 );
1127 assert_eq!(
1128 rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| {
1129 patch.tl0_pic_idx(1)
1130 })
1131 .unwrap_err(),
1132 Vp8PatchError::Tl0PicIdxMissing
1133 );
1134 assert_eq!(
1135 rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| {
1136 patch.key_idx(1)
1137 })
1138 .unwrap_err(),
1139 Vp8PatchError::KeyIdxMissing
1140 );
1141 assert_eq!(
1142 rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| {
1143 patch.key_idx(KEY_IDX_MASK + 1)
1144 })
1145 .unwrap_err(),
1146 Vp8PatchError::KeyIdxMissing
1147 );
1148 assert_eq!(
1149 Vp8Descriptor::parse(&[0x80, 0x40, 0x12, 0x90]).unwrap_err(),
1150 Vp8DescriptorError::MalformedDescriptor
1151 );
1152 }
1153
1154 #[test]
1155 fn test_vp8_patch_rejects_impossible_values() {
1156 assert_eq!(
1157 rewrite_payload(&[0x80, 0x80, 0x01, 0x90], |patch| {
1158 patch.picture_id(0x80)
1159 })
1160 .unwrap_err(),
1161 Vp8PatchError::PictureIdTooLarge
1162 );
1163 assert_eq!(
1164 rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| {
1165 patch.picture_id(PICTURE_ID_MAX + 1)
1166 })
1167 .unwrap_err(),
1168 Vp8PatchError::PictureIdTooLarge
1169 );
1170 assert_eq!(
1171 rewrite_payload(&[0x80, 0x10, 0x00, 0x90], |patch| {
1172 patch.key_idx(KEY_IDX_MASK + 1)
1173 })
1174 .unwrap_err(),
1175 Vp8PatchError::KeyIdxTooLarge
1176 );
1177 }
1178
1179 #[test]
1180 fn test_detect_vp8_keyframe() {
1181 assert!(!detect_vp8_keyframe(&[]));
1183
1184 assert!(detect_vp8_keyframe(&[0x10, 0x00]));
1188
1189 assert!(!detect_vp8_keyframe(&[0x10, 0x01]));
1192
1193 assert!(!detect_vp8_keyframe(&[0x00, 0x00]));
1195
1196 assert!(!detect_vp8_keyframe(&[0x11, 0x00]));
1198
1199 assert!(detect_vp8_keyframe(&[0x90, 0x80, 0x42, 0x00]));
1205
1206 assert!(!detect_vp8_keyframe(&[0x90, 0x80, 0x42, 0x01]));
1208
1209 assert!(detect_vp8_keyframe(&[0x90, 0x80, 0x80, 0x42, 0x00]));
1214
1215 assert!(detect_vp8_keyframe(&[
1223 0x90, 0xE0, 0x80, 0x42, 0x01, 0x00, 0x00
1224 ]));
1225
1226 assert!(detect_vp8_keyframe(&[0x90, 0x40, 0x01, 0x00]));
1227
1228 assert!(!detect_vp8_keyframe(&[0x90, 0x80]));
1230
1231 assert!(!detect_vp8_keyframe(&[0x90, 0x80, 0x42]));
1233 }
1234
1235 #[test]
1236 fn test_vp8_descriptor_keyframe_detection_matches_helper() {
1237 let payloads: &[&[u8]] = &[
1238 &[],
1239 &[0x10, 0x00],
1240 &[0x10, 0x01],
1241 &[0x00, 0x00],
1242 &[0x11, 0x00],
1243 &[0x90, 0x80, 0x42, 0x00],
1244 &[0x90, 0x80, 0x42, 0x01],
1245 &[0x90, 0x80],
1246 &[0x90, 0x80, 0x42],
1247 ];
1248
1249 for payload in payloads {
1250 let descriptor_starts_keyframe = Vp8Descriptor::parse(payload)
1251 .map(|descriptor| descriptor.starts_keyframe(payload))
1252 .unwrap_or(false);
1253 assert_eq!(descriptor_starts_keyframe, detect_vp8_keyframe(payload));
1254 }
1255 }
1256
1257 #[test]
1258 fn packetize_respects_mtu() -> Result<(), PacketError> {
1259 let payload = vec![0xABu8; 2000];
1260 for &mtu in &[100usize, 300, 600, 1200] {
1261 let mut pck = Vp8Packetizer::default();
1262 let pkts = pck.packetize(mtu, &payload)?;
1263 assert!(!pkts.is_empty(), "VP8 produced no packets at mtu {mtu}");
1264 for (i, pkt) in pkts.iter().enumerate() {
1265 assert!(
1266 pkt.len() <= mtu,
1267 "VP8 packet {i} size {} > mtu {mtu}",
1268 pkt.len()
1269 );
1270 }
1271 }
1272 Ok(())
1273 }
1274
1275 fn picture_id_of(depack: &mut Vp8Depacketizer, picture_id: &[u8]) -> Option<u64> {
1276 let mut packet = vec![0x90, 0x80];
1278 packet.extend_from_slice(picture_id);
1279 packet.push(0x01);
1280 let mut payload = Vec::new();
1281 let mut extra = CodecExtra::None;
1282 depack
1283 .depacketize(&packet, &mut payload, &mut extra)
1284 .unwrap();
1285 let CodecExtra::Vp8(extra) = extra else {
1286 panic!("expected VP8 codec extra");
1287 };
1288 extra.picture_id
1289 }
1290
1291 fn frame(keyframe: bool, picture_id: &[u8], tl0_pic_idx: u8) -> Vec<Vec<u8>> {
1293 let mut packet = vec![0x90, 0xE0];
1294 packet.extend_from_slice(picture_id);
1295 packet.extend_from_slice(&[tl0_pic_idx, 0x00, u8::from(!keyframe)]);
1296 vec![packet]
1297 }
1298
1299 fn assert_every_frame_emitted(frames: impl IntoIterator<Item = Vec<Vec<u8>>>) {
1300 use crate::packet::{CodecDepacketizer, DepacketizingBuffer, RtpMeta};
1301 use crate::rtp_::{MediaTime, RtpHeader};
1302 use std::time::Instant;
1303
1304 let mut buf =
1305 DepacketizingBuffer::new(CodecDepacketizer::Vp8(Vp8Depacketizer::default()), 3);
1306 let now = Instant::now();
1307 let mut seq = 0_u64;
1308
1309 for (frame, packets) in frames.into_iter().enumerate() {
1310 let count = packets.len();
1311 let time = frame as u64 * 3000;
1312
1313 for (i, packet) in packets.into_iter().enumerate() {
1314 let meta = RtpMeta {
1315 received: now,
1316 time: MediaTime::from_90khz(time),
1317 seq_no: seq.into(),
1318 last_sender_info: None,
1319 header: RtpHeader {
1320 sequence_number: seq as u16,
1321 timestamp: time as u32,
1322 marker: i == count - 1,
1323 ..Default::default()
1324 },
1325 };
1326 buf.push(meta, packet);
1327 seq += 1;
1328 }
1329
1330 let dep = buf
1331 .pop(now, None)
1332 .unwrap_or_else(|| panic!("frame {frame} was not emitted"))
1333 .unwrap();
1334 assert!(dep.contiguous, "frame {frame} is not contiguous");
1335 }
1336 }
1337
1338 #[test]
1339 fn depacketizer_preserves_picture_id_epoch_when_width_grows() {
1340 let mut depack = Vp8Depacketizer::default();
1341 for (picture_id, expected) in [(126_u8, 126_u64), (127, 127), (0, 128), (1, 129)] {
1342 assert_eq!(picture_id_of(&mut depack, &[picture_id]), Some(expected));
1343 }
1344 assert_eq!(picture_id_of(&mut depack, &[0x80, 2]), Some(130));
1346 }
1347
1348 #[test]
1349 fn depacketizing_buffer_emits_frames_when_picture_id_width_grows() {
1350 let frames = [
1351 frame(true, &[126], 10),
1352 frame(false, &[127], 11),
1353 frame(false, &[0], 12),
1354 frame(false, &[1], 13),
1355 frame(false, &[0x80, 2], 14),
1356 frame(false, &[0x80, 3], 15),
1357 ];
1358 assert_every_frame_emitted(frames);
1359 }
1360
1361 #[test]
1362 fn depacketizer_preserves_wide_picture_id_after_loss_at_width_growth() {
1363 let mut depack = Vp8Depacketizer::default();
1364 assert_eq!(picture_id_of(&mut depack, &[0]), Some(0));
1365 assert_eq!(picture_id_of(&mut depack, &[0x80, 100]), Some(100));
1367 }
1368
1369 #[test]
1370 fn depacketizing_buffer_recovers_after_loss_at_picture_id_width_growth() {
1371 let frames = std::iter::once(frame(true, &[0], 0))
1374 .chain((100..=130_u8).map(|pid| frame(pid == 100, &[0x80, pid], pid - 99)));
1375 assert_every_frame_emitted(frames);
1376 }
1377}