Skip to main content

str0m/packet/
vp9.rs

1use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer};
2use crate::rtp_::{extend_u7, extend_u8, extend_u15};
3
4use std::fmt;
5
6/// Max non-flexible VP9 descriptor size reserved for MTU headroom:
7/// flags(1) + PID(2) + L(1) + tl0picidx(1) + ≤1 SS byte on keyframe first-packets; 8 is a safe bound.
8const VP9_NON_FLEXIBLE_HEADER_SIZE: usize = 8;
9/// VP9 RTP payload descriptor size for flexible mode:
10/// flags(1) + 15-bit PID(2) = 3
11const VP9_FLEXIBLE_HEADER_SIZE: usize = 3;
12const MAX_SPATIAL_LAYERS: usize = 3;
13const MAX_VP9REF_PICS: usize = 3;
14
15/// VP9 packetizer mode controlling the RTP payload descriptor format.
16#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
17pub enum Vp9PacketizerMode {
18    /// Flexible mode (F=1): minimal 3-byte header (flags + 15-bit PID).
19    /// Simpler but causes issues with Safari which drops inter-frames.
20    Flexible,
21    /// Non-flexible mode (F=0): 5-6 byte header with layer indices and
22    /// scalability structure. Compatible with all major browsers.
23    #[default]
24    NonFlexible,
25}
26
27/// Vp9 information describing the depacketized/packetized data.
28#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
29pub struct Vp9CodecExtra {
30    /// Map of the SVC layers.
31    ///
32    /// Index of each element corresponds to `spatial layer` index.
33    ///
34    /// Each element represents the end (not including) in [`MediaData::data`]
35    /// for `spatial layer` it belongs.
36    ///
37    /// The all `spatial layer`s (up to 3) in [`MediaData::data`] are sorted by
38    /// `spatial layer` index from lower to greater. So, the beginning of some
39    /// `spatial layer` is the end (including) of the previous `spatial layer`
40    /// (for the `spatial layer` with index 0 the beginning is 0).
41    ///
42    /// ```text
43    /// [MediaData::data]:
44    /// +-----+----------------------+---------------------------+
45    /// | SL0 |         SL1          |            SL2            |
46    /// +-----+----------------------+---------------------------+
47    /// |     |                      |                           |
48    /// V     V                      V                           V
49    /// 0   layers_scheme[0]       layers_scheme[1]            layers_scheme[2]
50    /// ```
51    ///
52    /// **Note:** There is no syncronization between
53    /// [`Vp9CodecExtra::layers_scheme`] and [`MediaData::data`]! If you need
54    /// to keep [`Vp9CodecExtra::layers_scheme`] in actual state you have to
55    /// update the [`Vp9CodecExtra::layers_scheme`] on mutating the
56    /// [`MediaData::data`].
57    ///
58    /// [`MediaData::data`]: crate::media::MediaData::data
59    ///
60    /// ## Example
61    ///
62    /// Say you have a VP9 track working in "L3T3" scalability mode and you
63    /// want to retranslate S1T2 layer. So you need to retranslate the all
64    /// spatial and temporal layers <= target layer.
65    ///
66    /// ```no_run
67    /// # use str0m::{format::CodecExtra, media::MediaData};
68    /// #
69    /// // We want to receive S1T2 layer.
70    /// let (target_spatial, target_temporal) = (1u8, 2u8);
71    ///
72    /// let media_data: MediaData = todo!();
73    ///
74    /// if let CodecExtra::Vp9(vp9_extra) = media_data.codec_extra {
75    ///     // Try to get current `temporal layer`. If `None` there is no SVC.
76    ///     if let Some(tid) = vp9_extra.tid {
77    ///         if let (true, Some(end_of_target_layer)) = (
78    ///             // Check whether we need this `temporal layer`.
79    ///             tid <= target_temporal,
80    ///             // Check whether we have information about the right
81    ///             // border of data for the target `spatial layer`.
82    ///             vp9_extra.layers_scheme[target_spatial as usize],
83    ///         ) {
84    ///             // Keep only the bytes for spatial layers up to `target_spatial`.
85    ///             let data = &media_data.data[..end_of_target_layer];
86    ///         }
87    ///     }
88    /// }
89    /// ```
90    pub layers_scheme: [Option<usize>; MAX_SPATIAL_LAYERS],
91
92    /// Temporal layer id.
93    pub tid: Option<u8>,
94
95    /// Map of the SVC layers widths.
96    ///
97    /// Specified for every spatial layer.
98    pub layers_widths: [Option<u16>; MAX_SPATIAL_LAYERS],
99
100    /// Map of the SVC layers heights.
101    ///
102    /// Specified for every spatial layer.
103    pub layers_heights: [Option<u16>; MAX_SPATIAL_LAYERS],
104
105    /// Extended picture id of layer 0 frames, if present
106    pub tl0_picture_id: Option<u64>,
107
108    /// Extended picture id, if present
109    pub picture_id: Option<u64>,
110
111    /// Flag which indicates that within [`MediaData`], there is an individual frame
112    /// containing complete and independent visual information. This frame serves
113    /// as a reference point for other frames in the video sequence.
114    ///
115    /// [`MediaData`]: crate::media::MediaData
116    pub is_keyframe: bool,
117}
118
119/// Detect whether a raw VP9 frame is a keyframe by inspecting the bitstream header.
120///
121/// VP9 uncompressed header (profile 0/1):
122///   `frame_marker(2) | profile_low(1) | profile_high(1) | show_existing(1) | frame_type(1)`
123///
124/// VP9 uncompressed header (profile 2/3):
125///   `frame_marker(2) | profile_low(1) | profile_high(1) | reserved(1) | show_existing(1) | frame_type(1)`
126///
127/// - `frame_marker` must be `0b10`
128/// - `frame_type`: 0 = KEY_FRAME, 1 = NON_KEY_FRAME
129/// - `show_existing_frame` = 1 references a previously decoded frame (not a real keyframe)
130///
131/// This function works on raw VP9 bitstream data (without RTP descriptor).
132pub fn detect_vp9_keyframe_bitstream(payload: &[u8]) -> bool {
133    if payload.is_empty() {
134        return false;
135    }
136    let b = payload[0];
137    // frame_marker must be 0b10 (bits 7-6)
138    if (b & 0xC0) != 0x80 {
139        return false;
140    }
141    // profile_high_bit is at bit 4
142    let profile_high = (b >> 4) & 1;
143    let (show_existing_frame, frame_type) = if profile_high == 1 {
144        // Profile 2 or 3: reserved_zero at bit 3, show_existing at bit 2, frame_type at bit 1
145        ((b >> 2) & 1, (b >> 1) & 1)
146    } else {
147        // Profile 0 or 1: show_existing at bit 3, frame_type at bit 2
148        ((b >> 3) & 1, (b >> 2) & 1)
149    };
150    // show_existing_frame references a previously decoded frame, not a real keyframe
151    if show_existing_frame != 0 {
152        return false;
153    }
154    // frame_type: 0 = KEY_FRAME
155    frame_type == 0
156}
157
158/// Detect whether a VP9 RTP payload contains a keyframe by inspecting the P bit.
159///
160/// VP9 RTP descriptor byte 0: `I|P|L|F|B|E|V|Z`
161/// - P=0: independently decodable frame (keyframe)
162/// - P=1: inter-picture predicted frame
163///
164/// Works with both flexible (F=1) and non-flexible (F=0) mode packets.
165pub fn detect_vp9_keyframe(payload: &[u8]) -> bool {
166    if payload.is_empty() {
167        return false;
168    }
169    // P bit is bit 6 of byte 0. P=0 means keyframe.
170    (payload[0] & 0x40) == 0
171}
172
173/// Packetizes VP9 RTP packets.
174///
175/// Supports both non-flexible mode (F=0) and flexible mode (F=1), controlled
176/// by [`Vp9PacketizerMode`]. Defaults to non-flexible mode for broad browser
177/// compatibility — Safari and older Chrome drop inter-frames with F=1.
178#[derive(Default, Clone)]
179pub struct Vp9Packetizer {
180    picture_id: u16,
181    /// Temporal layer 0 picture index — increments on every frame (since all
182    /// frames are packetized as TID=0). Used in L byte for non-flexible mode.
183    tl0picidx: u8,
184    initialized: bool,
185    mode: Vp9PacketizerMode,
186    #[cfg(test)]
187    initial_picture_id: u16,
188}
189
190impl Vp9Packetizer {
191    /// Create a VP9 packetizer with the specified mode.
192    pub fn with_mode(mode: Vp9PacketizerMode) -> Self {
193        Self {
194            mode,
195            ..Default::default()
196        }
197    }
198}
199
200impl fmt::Debug for Vp9Packetizer {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        f.debug_struct("Vp9Packetizer")
203            .field("picture_id", &self.picture_id)
204            .field("tl0picidx", &self.tl0picidx)
205            .field("initialized", &self.initialized)
206            .field("mode", &self.mode)
207            .finish()
208    }
209}
210
211impl Packetizer for Vp9Packetizer {
212    /// Packetize a VP9 frame into one or more RTP packets.
213    fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result<Vec<Vec<u8>>, PacketError> {
214        if payload.is_empty() || mtu == 0 {
215            return Ok(vec![]);
216        }
217
218        if !self.initialized {
219            #[cfg(test)]
220            {
221                self.picture_id = self.initial_picture_id;
222            }
223            #[cfg(not(test))]
224            {
225                use str0m_proto::NonCryptographicRng;
226                self.picture_id = NonCryptographicRng::u16() & 0x7FFF;
227            }
228            self.initialized = true;
229        }
230
231        match self.mode {
232            Vp9PacketizerMode::NonFlexible => self.packetize_non_flexible(mtu, payload),
233            Vp9PacketizerMode::Flexible => self.packetize_flexible(mtu, payload),
234        }
235    }
236
237    fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool {
238        last
239    }
240}
241
242impl Vp9Packetizer {
243    /// Non-flexible mode (F=0) packetization.
244    ///
245    /// 5-8 byte header with layer indices and scalability structure.
246    /// Compatible with all major browsers including Safari.
247    ///
248    /// ```text
249    ///        0 1 2 3 4 5 6 7
250    ///       +-+-+-+-+-+-+-+-+
251    ///       |I|P|L|F|B|E|V|Z| (REQUIRED)
252    ///       +-+-+-+-+-+-+-+-+
253    ///  I:   |M| PICTURE ID  | (RECOMMENDED)
254    ///       +-+-+-+-+-+-+-+-+
255    ///  M:   | EXTENDED PID  | (RECOMMENDED)
256    ///       +-+-+-+-+-+-+-+-+
257    ///  L:   | tid |U| SID |D| (CONDITIONALLY RECOMMENDED)
258    ///       +-+-+-+-+-+-+-+-+
259    ///       |   tl0picidx   | (CONDITIONALLY REQUIRED)
260    ///       +-+-+-+-+-+-+-+-+
261    ///  V:   | SS            |
262    ///       | ..            |
263    ///       +-+-+-+-+-+-+-+-+
264    /// ```
265    fn packetize_non_flexible(
266        &mut self,
267        mtu: usize,
268        payload: &[u8],
269    ) -> Result<Vec<Vec<u8>>, PacketError> {
270        // Detect keyframe from VP9 bitstream to set P flag correctly.
271        let is_keyframe = detect_vp9_keyframe_bitstream(payload);
272
273        // tl0picidx increments on every TID=0 frame. Since we always emit TID=0,
274        // this increments on every frame per draft-ietf-payload-vp9, Section 6.3.
275        self.tl0picidx = self.tl0picidx.wrapping_add(1);
276
277        // VP9_NON_FLEXIBLE_HEADER_SIZE is the max header (8 bytes, accounting for SS
278        // on keyframes). This ensures we never exceed MTU even on keyframe first-packets.
279        let max_fragment_size = mtu as isize - VP9_NON_FLEXIBLE_HEADER_SIZE as isize;
280        let mut payloads = vec![];
281        let mut payload_data_remaining = payload.len();
282        let mut payload_data_index = 0;
283
284        if std::cmp::min(max_fragment_size, payload_data_remaining as isize) <= 0 {
285            return Ok(vec![]);
286        }
287
288        while payload_data_remaining > 0 {
289            let current_fragment_size =
290                std::cmp::min(max_fragment_size as usize, payload_data_remaining);
291            let is_first = payload_data_index == 0;
292            let is_last = payload_data_remaining == current_fragment_size;
293
294            // Non-keyframe: 5 bytes (flags + 15-bit PID + L + tl0picidx)
295            // Keyframe first packet: 6 bytes (+ 1 byte SS data, G=0)
296            let ss_size = if is_keyframe && is_first { 1 } else { 0 };
297            let header_size = 5 + ss_size;
298            let mut out = Vec::with_capacity(header_size + current_fragment_size);
299
300            // Byte 0: I|P|L|F|B|E|V|Z
301            let mut flags = 0xA0u8; // I=1, L=1 (F=0 implicit)
302            if !is_keyframe {
303                flags |= 0x40; // P=1 for inter-predicted frames
304            }
305            if is_first {
306                flags |= 0x08; // B=1 (beginning of frame)
307            }
308            if is_last {
309                flags |= 0x04; // E=1 (end of frame)
310            }
311            if is_keyframe && is_first {
312                flags |= 0x02; // V=1 (scalability structure present)
313            }
314            out.push(flags);
315
316            // Bytes 1-2: 15-bit picture ID (M=1)
317            out.push((self.picture_id >> 8) as u8 | 0x80);
318            out.push((self.picture_id & 0xFF) as u8);
319
320            // Bytes 3-4: Layer indices (L=1, non-flexible mode)
321            // TID(3)|U(1)|SID(3)|D(1) = TID=0, U=1, SID=0, D=0
322            out.push(0x10);
323            // tl0picidx (required when F=0 and L=1)
324            out.push(self.tl0picidx);
325
326            // SS byte on keyframe first packet: N_S=0, Y=0, G=0 (no GOF). A single-layer stream has no
327            // GOF to advertise; a G=1/R=0 GOF mis-signals references (see commit msg). This matches what
328            // libwebrtc emits for non-scalable VP9 (g_bit = num_frames_in_gof > 0). RFC 9628 §4.2.
329            if is_keyframe && is_first {
330                out.push(0x00);
331            }
332
333            out.extend_from_slice(
334                &payload[payload_data_index..payload_data_index + current_fragment_size],
335            );
336
337            payloads.push(out);
338
339            payload_data_remaining -= current_fragment_size;
340            payload_data_index += current_fragment_size;
341        }
342
343        self.picture_id += 1;
344        self.picture_id &= 0x7FFF;
345
346        Ok(payloads)
347    }
348
349    /// Flexible mode (F=1) packetization.
350    ///
351    /// Minimal 3-byte header (flags + 15-bit PID). Simpler but may cause
352    /// issues with Safari which drops inter-frames.
353    ///
354    /// ```text
355    ///        0 1 2 3 4 5 6 7
356    ///       +-+-+-+-+-+-+-+-+
357    ///       |I|P|L|F|B|E|V|Z| (REQUIRED)
358    ///       +-+-+-+-+-+-+-+-+
359    ///  I:   |M| PICTURE ID  | (RECOMMENDED)
360    ///       +-+-+-+-+-+-+-+-+
361    ///  M:   | EXTENDED PID  | (RECOMMENDED)
362    ///       +-+-+-+-+-+-+-+-+
363    /// ```
364    fn packetize_flexible(
365        &mut self,
366        mtu: usize,
367        payload: &[u8],
368    ) -> Result<Vec<Vec<u8>>, PacketError> {
369        let max_fragment_size = mtu as isize - VP9_FLEXIBLE_HEADER_SIZE as isize;
370        let mut payloads = vec![];
371        let mut payload_data_remaining = payload.len();
372        let mut payload_data_index = 0;
373
374        if std::cmp::min(max_fragment_size, payload_data_remaining as isize) <= 0 {
375            return Ok(vec![]);
376        }
377
378        while payload_data_remaining > 0 {
379            let current_fragment_size =
380                std::cmp::min(max_fragment_size as usize, payload_data_remaining);
381            let is_first = payload_data_index == 0;
382            let is_last = payload_data_remaining == current_fragment_size;
383
384            let mut out = Vec::with_capacity(VP9_FLEXIBLE_HEADER_SIZE + current_fragment_size);
385
386            // Byte 0: I|P|L|F|B|E|V|Z — I=1, F=1
387            let mut flags = 0x90u8; // I=1, F=1
388            if is_first {
389                flags |= 0x08; // B=1
390            }
391            if is_last {
392                flags |= 0x04; // E=1
393            }
394            out.push(flags);
395
396            // Bytes 1-2: 15-bit picture ID (M=1)
397            out.push((self.picture_id >> 8) as u8 | 0x80);
398            out.push((self.picture_id & 0xFF) as u8);
399
400            out.extend_from_slice(
401                &payload[payload_data_index..payload_data_index + current_fragment_size],
402            );
403
404            payloads.push(out);
405
406            payload_data_remaining -= current_fragment_size;
407            payload_data_index += current_fragment_size;
408        }
409
410        self.picture_id += 1;
411        self.picture_id &= 0x7FFF;
412
413        Ok(payloads)
414    }
415}
416
417/// Depacketizes VP9 RTP packets.
418#[derive(PartialEq, Eq, Debug, Default, Clone)]
419pub struct Vp9Depacketizer {
420    /// picture ID is present
421    pub i: bool,
422    /// inter-picture predicted frame.
423    pub p: bool,
424    /// layer indices present
425    pub l: bool,
426    /// flexible mode
427    pub f: bool,
428    /// start of frame. beginning of new vp9 frame
429    pub b: bool,
430    /// end of frame
431    pub e: bool,
432    /// scalability structure (SS) present
433    pub v: bool,
434    /// Not a reference frame for upper spatial layers
435    pub z: bool,
436
437    /// Recommended headers
438    /// 7 or 15 bits, picture ID.
439    pub picture_id: u16,
440    /// extended picture id
441    pub extended_pid: Option<u64>,
442
443    /// Conditionally recommended headers
444    /// Temporal layer ID
445    pub tid: u8,
446    /// Switching up point
447    pub u: bool,
448    /// Spatial layer ID
449    pub sid: u8,
450    /// Inter-layer dependency used
451    pub d: bool,
452
453    /// Conditionally required headers
454    /// Reference index (F=1)
455    pub pdiff: [u8; MAX_VP9REF_PICS],
456    /// Temporal layer zero index (F=0)
457    pub tl0picidx: u8,
458    /// extended version of tl0picidx
459    pub extended_tl0picidx: Option<u64>,
460
461    /// Scalability structure headers
462    /// N_S + 1 indicates the number of spatial layers present in the VP9 stream
463    pub ns: u8,
464    /// Each spatial layer's frame resolution present
465    pub y: bool,
466    /// PG description present flag.
467    pub g: bool,
468    /// N_G indicates the number of pictures in a Picture Group (PG)
469    pub ng: u8,
470    pub width: [Option<u16>; MAX_SPATIAL_LAYERS],
471    pub height: [Option<u16>; MAX_SPATIAL_LAYERS],
472    /// Temporal layer ID of pictures in a Picture Group
473    pub pgtid: Vec<u8>,
474    /// Switching up point of pictures in a Picture Group
475    pub pgu: Vec<bool>,
476    /// Reference indices of pictures in a Picture Group
477    pub pgpdiff: Vec<Vec<u8>>,
478}
479
480impl Depacketizer for Vp9Depacketizer {
481    fn out_size_hint(&self, packets_size: usize) -> Option<usize> {
482        Some(packets_size)
483    }
484
485    /// depacketize parses the passed byte slice and stores the result
486    /// in the Vp9Packet this method is called upon
487    fn depacketize(
488        &mut self,
489        packet: &[u8],
490        out: &mut Vec<u8>,
491        extra: &mut CodecExtra,
492    ) -> Result<(), PacketError> {
493        if packet.is_empty() {
494            return Err(PacketError::ErrShortPacket);
495        }
496
497        let mut reader = (packet, 0);
498        let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
499
500        self.i = (b & 0x80) != 0;
501        self.p = (b & 0x40) != 0;
502        self.l = (b & 0x20) != 0;
503        self.f = (b & 0x10) != 0;
504        self.b = (b & 0x08) != 0;
505        self.e = (b & 0x04) != 0;
506        self.v = (b & 0x02) != 0;
507        self.z = (b & 0x01) != 0;
508
509        let mut payload_index = 1;
510
511        if self.i {
512            payload_index = self.parse_picture_id(&mut reader, payload_index)?;
513        }
514
515        if self.l {
516            payload_index = self.parse_layer_info(&mut reader, payload_index)?;
517        }
518
519        if self.f && self.p {
520            payload_index = self.parse_ref_indices(&mut reader, payload_index)?;
521        }
522
523        if self.v {
524            payload_index = self.parse_ssdata(&mut reader, payload_index)?;
525        }
526
527        self.update_extra(extra, out.len(), packet.len(), payload_index)?;
528
529        out.extend_from_slice(&packet[payload_index..]);
530
531        Ok(())
532    }
533
534    /// is_partition_head checks whether if this is a head of the VP9 partition
535    fn is_partition_head(&self, payload: &[u8]) -> bool {
536        if payload.is_empty() {
537            false
538        } else {
539            (payload[0] & 0x08) != 0
540        }
541    }
542
543    fn is_partition_tail(&self, marker: bool, _payload: &[u8]) -> bool {
544        marker
545    }
546}
547
548impl Vp9Depacketizer {
549    /// Updates provided [`CodecExtra`].
550    /// __MUST__ be called after the all transformations of `payload_index`.
551    fn update_extra(
552        &self,
553        extra: &mut CodecExtra,
554        out_len: usize,
555        packet_len: usize,
556        payload_index: usize,
557    ) -> Result<(), PacketError> {
558        let mut vp9_extra = match extra {
559            CodecExtra::Vp9(e) => *e,
560            _ => Vp9CodecExtra::default(),
561        };
562
563        if self.l {
564            let new_stop = out_len + packet_len - payload_index;
565
566            if let Some(stop) = vp9_extra.layers_scheme[self.sid as usize] {
567                if stop != out_len {
568                    return Err(PacketError::ErrVP9CorruptedPacket);
569                }
570            }
571
572            vp9_extra.layers_scheme[self.sid as usize] = Some(new_stop);
573            vp9_extra.tid = Some(self.tid);
574
575            if !self.f {
576                vp9_extra.tl0_picture_id = self.extended_tl0picidx;
577            }
578        }
579
580        // I: "Picture ID (PID) present" (RFC 9628 section 4.2). A packet without it
581        // keeps the picture id of an earlier packet of the same frame.
582        if self.i {
583            vp9_extra.picture_id = self.extended_pid;
584        }
585        vp9_extra
586            .layers_widths
587            .copy_from_slice(&self.width[..MAX_SPATIAL_LAYERS]);
588        vp9_extra
589            .layers_heights
590            .copy_from_slice(&self.height[..MAX_SPATIAL_LAYERS]);
591        vp9_extra.is_keyframe |= !self.p && (self.sid == 0 || !self.l) && self.b;
592
593        *extra = CodecExtra::Vp9(vp9_extra);
594
595        Ok(())
596    }
597
598    // Picture ID:
599    //
600    //      +-+-+-+-+-+-+-+-+
601    // I:   |M| PICTURE ID  |   M:0 => picture id is 7 bits.
602    //      +-+-+-+-+-+-+-+-+   M:1 => picture id is 15 bits.
603    // M:   | EXTENDED PID  |
604    //      +-+-+-+-+-+-+-+-+
605    //
606    fn parse_picture_id(
607        &mut self,
608        reader: &mut dyn BitRead,
609        mut payload_index: usize,
610    ) -> Result<usize, PacketError> {
611        if reader.remaining_bits() == 0 {
612            return Err(PacketError::ErrShortPacket);
613        }
614        let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
615        payload_index += 1;
616        let previous_picture_id = u64::from(self.picture_id);
617        let previous = self.extended_pid.map(|_| previous_picture_id);
618        // PID present?
619        let next = if (b & 0x80) != 0 {
620            if reader.remaining_bits() == 0 {
621                return Err(PacketError::ErrShortPacket);
622            }
623            // M == 1, PID is 15bit
624            let x = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
625            self.picture_id = (((b & 0x7f) as u16) << 8) | (x as u16);
626            payload_index += 1;
627            extend_u15(previous, self.picture_id)
628        } else {
629            self.picture_id = (b & 0x7F) as u16;
630            extend_u7(previous, b)
631        };
632
633        // A wider wire ID is zero-extended after a width change. Preserve the
634        // offset from earlier short-ID wraps by extending the raw-ID delta.
635        self.extended_pid = Some(match self.extended_pid {
636            Some(previous) => previous.wrapping_add(next.wrapping_sub(previous_picture_id)),
637            None => next,
638        });
639
640        Ok(payload_index)
641    }
642
643    fn parse_layer_info(
644        &mut self,
645        reader: &mut dyn BitRead,
646        mut payload_index: usize,
647    ) -> Result<usize, PacketError> {
648        payload_index = self.parse_layer_info_common(reader, payload_index)?;
649
650        if self.f {
651            Ok(payload_index)
652        } else {
653            self.parse_layer_info_non_flexible_mode(reader, payload_index)
654        }
655    }
656
657    // Layer indices (flexible mode):
658    //
659    //      +-+-+-+-+-+-+-+-+
660    // L:   |  T  |U|  S  |D|
661    //      +-+-+-+-+-+-+-+-+
662    //
663    fn parse_layer_info_common(
664        &mut self,
665        reader: &mut dyn BitRead,
666        mut payload_index: usize,
667    ) -> Result<usize, PacketError> {
668        if reader.remaining_bits() == 0 {
669            return Err(PacketError::ErrShortPacket);
670        }
671        let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
672        payload_index += 1;
673
674        self.tid = b >> 5;
675        self.u = b & 0x10 != 0;
676        self.sid = (b >> 1) & 0x7;
677        self.d = b & 0x01 != 0;
678
679        if self.sid as usize >= MAX_SPATIAL_LAYERS {
680            Err(PacketError::ErrTooManySpatialLayers)
681        } else {
682            Ok(payload_index)
683        }
684    }
685
686    // Layer indices (non-flexible mode):
687    //
688    //      +-+-+-+-+-+-+-+-+
689    // L:   |  T  |U|  S  |D|
690    //      +-+-+-+-+-+-+-+-+
691    //      |   tl0picidx   |
692    //      +-+-+-+-+-+-+-+-+
693    //
694    fn parse_layer_info_non_flexible_mode(
695        &mut self,
696        reader: &mut dyn BitRead,
697        mut payload_index: usize,
698    ) -> Result<usize, PacketError> {
699        if reader.remaining_bits() == 0 {
700            return Err(PacketError::ErrShortPacket);
701        }
702        self.tl0picidx = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
703        self.extended_tl0picidx = Some(extend_u8(self.extended_tl0picidx, self.tl0picidx));
704        payload_index += 1;
705        Ok(payload_index)
706    }
707
708    // Reference indices:
709    //
710    //      +-+-+-+-+-+-+-+-+                P=1,F=1: At least one reference index
711    // P,F: | P_DIFF      |N|  up to 3 times          has to be specified.
712    //      +-+-+-+-+-+-+-+-+                    N=1: An additional P_DIFF follows
713    //                                                current P_DIFF.
714    //
715    fn parse_ref_indices(
716        &mut self,
717        reader: &mut dyn BitRead,
718        mut payload_index: usize,
719    ) -> Result<usize, PacketError> {
720        let mut b = 1u8;
721        let mut num_ref_pics = 0;
722        while (b & 0x1) != 0 {
723            if num_ref_pics == MAX_VP9REF_PICS {
724                return Err(PacketError::ErrTooManyPDiff);
725            }
726
727            if reader.remaining_bits() == 0 {
728                return Err(PacketError::ErrShortPacket);
729            }
730            b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
731            payload_index += 1;
732
733            self.pdiff[num_ref_pics] = b >> 1;
734            num_ref_pics += 1;
735        }
736
737        Ok(payload_index)
738    }
739
740    // Scalability structure (SS):
741    //
742    //      +-+-+-+-+-+-+-+-+
743    // V:   | N_S |Y|G|-|-|-|
744    //      +-+-+-+-+-+-+-+-+              -|
745    // Y:   |     WIDTH     | (OPTIONAL)    .
746    //      +               +               .
747    //      |               | (OPTIONAL)    .
748    //      +-+-+-+-+-+-+-+-+               . N_S + 1 times
749    //      |     HEIGHT    | (OPTIONAL)    .
750    //      +               +               .
751    //      |               | (OPTIONAL)    .
752    //      +-+-+-+-+-+-+-+-+              -|
753    // G:   |      N_G      | (OPTIONAL)
754    //      +-+-+-+-+-+-+-+-+                           -|
755    // N_G: |  T  |U| R |-|-| (OPTIONAL)                 .
756    //      +-+-+-+-+-+-+-+-+              -|            . N_G times
757    //      |    P_DIFF     | (OPTIONAL)    . R times    .
758    //      +-+-+-+-+-+-+-+-+              -|           -|
759    //
760    fn parse_ssdata(
761        &mut self,
762        reader: &mut dyn BitRead,
763        mut payload_index: usize,
764    ) -> Result<usize, PacketError> {
765        if reader.remaining_bits() == 0 {
766            return Err(PacketError::ErrShortPacket);
767        }
768
769        let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
770        payload_index += 1;
771
772        self.ns = b >> 5;
773        self.y = b & 0x10 != 0;
774        self.g = (b >> 1) & 0x7 != 0;
775
776        let ns = (self.ns + 1) as usize;
777        self.ng = 0;
778
779        if ns > MAX_SPATIAL_LAYERS {
780            return Err(PacketError::ErrVP9CorruptedPacket);
781        }
782
783        if self.y {
784            if reader.remaining_bits() < 4 * ns {
785                return Err(PacketError::ErrShortPacket);
786            }
787
788            for i in 0..ns {
789                self.width[i] = Some(reader.get_u16().ok_or(PacketError::ErrShortPacket)?);
790                self.height[i] = Some(reader.get_u16().ok_or(PacketError::ErrShortPacket)?);
791            }
792            payload_index += 4 * ns;
793        }
794
795        if self.g {
796            if reader.remaining_bits() == 0 {
797                return Err(PacketError::ErrShortPacket);
798            }
799
800            self.ng = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
801            payload_index += 1;
802        }
803
804        for i in 0..self.ng as usize {
805            if reader.remaining_bits() == 0 {
806                return Err(PacketError::ErrShortPacket);
807            }
808            let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
809            payload_index += 1;
810
811            self.pgtid.push(b >> 5);
812            self.pgu.push(b & 0x10 != 0);
813
814            let r = ((b >> 2) & 0x3) as usize;
815            if reader.remaining_bits() < r {
816                return Err(PacketError::ErrShortPacket);
817            }
818
819            self.pgpdiff.push(vec![]);
820            for _ in 0..r {
821                let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?;
822                payload_index += 1;
823
824                self.pgpdiff[i].push(b);
825            }
826        }
827
828        Ok(payload_index)
829    }
830}
831
832#[cfg(test)]
833mod test {
834    use super::*;
835
836    #[test]
837    #[allow(clippy::erasing_op, clippy::identity_op)]
838    fn test_vp9_packet_unmarshal() -> Result<(), PacketError> {
839        let tests: Vec<(&str, &[u8], Vp9Depacketizer, &[u8], Option<PacketError>)> = vec![
840            (
841                "Empty",
842                &[],
843                Vp9Depacketizer::default(),
844                &[],
845                Some(PacketError::ErrShortPacket),
846            ),
847            (
848                "NonFlexible",
849                &[0x00, 0xAA],
850                Vp9Depacketizer::default(),
851                &[0xAA],
852                None,
853            ),
854            (
855                "NonFlexiblePictureID",
856                &[0x80, 0x02, 0xAA],
857                Vp9Depacketizer {
858                    i: true,
859                    picture_id: 0x02,
860                    extended_pid: Some(0x02),
861                    ..Default::default()
862                },
863                &[0xAA],
864                None,
865            ),
866            (
867                "NonFlexiblePictureIDExt",
868                &[0x80, 0x81, 0xFF, 0xAA],
869                Vp9Depacketizer {
870                    i: true,
871                    picture_id: 0x01FF,
872                    extended_pid: Some(0x01FF),
873                    ..Default::default()
874                },
875                &[0xAA],
876                None,
877            ),
878            (
879                "NonFlexiblePictureIDExt_ShortPacket0",
880                &[0x80, 0x81],
881                Vp9Depacketizer::default(),
882                &[],
883                Some(PacketError::ErrShortPacket),
884            ),
885            (
886                "NonFlexiblePictureIDExt_ShortPacket1",
887                &[0x80],
888                Vp9Depacketizer::default(),
889                &[],
890                Some(PacketError::ErrShortPacket),
891            ),
892            (
893                "NonFlexibleLayerIndicePictureID",
894                &[0xA0, 0x02, 0x23, 0x01, 0xAA],
895                Vp9Depacketizer {
896                    i: true,
897                    l: true,
898                    picture_id: 0x02,
899                    extended_pid: Some(0x02),
900                    tid: 0x01,
901                    sid: 0x01,
902                    d: true,
903                    tl0picidx: 0x01,
904                    extended_tl0picidx: Some(0x01),
905                    ..Default::default()
906                },
907                &[0xAA],
908                None,
909            ),
910            (
911                "FlexibleLayerIndicePictureID",
912                &[0xB0, 0x02, 0x23, 0x01, 0xAA],
913                Vp9Depacketizer {
914                    f: true,
915                    i: true,
916                    l: true,
917                    picture_id: 0x02,
918                    extended_pid: Some(0x02),
919                    tid: 0x01,
920                    sid: 0x01,
921                    d: true,
922                    ..Default::default()
923                },
924                &[0x01, 0xAA],
925                None,
926            ),
927            (
928                "NonFlexibleLayerIndicePictureID_ShortPacket0",
929                &[0xA0, 0x02, 0x23],
930                Vp9Depacketizer::default(),
931                &[],
932                Some(PacketError::ErrShortPacket),
933            ),
934            (
935                "NonFlexibleLayerIndicePictureID_ShortPacket1",
936                &[0xA0, 0x02],
937                Vp9Depacketizer::default(),
938                &[],
939                Some(PacketError::ErrShortPacket),
940            ),
941            (
942                "FlexiblePictureIDRefIndex",
943                &[0xD0, 0x02, 0x03, 0x04, 0xAA],
944                Vp9Depacketizer {
945                    i: true,
946                    p: true,
947                    f: true,
948                    picture_id: 0x02,
949                    extended_pid: Some(0x02),
950                    pdiff: [0x01, 0x02, 0],
951                    ..Default::default()
952                },
953                &[0xAA],
954                None,
955            ),
956            (
957                "FlexiblePictureIDRefIndex_TooManyPDiff",
958                &[0xD0, 0x02, 0x03, 0x05, 0x07, 0x09, 0x10, 0xAA],
959                Vp9Depacketizer::default(),
960                &[],
961                Some(PacketError::ErrTooManyPDiff),
962            ),
963            (
964                "FlexiblePictureIDRefIndexNoPayload",
965                &[0xD0, 0x02, 0x03, 0x04],
966                Vp9Depacketizer {
967                    i: true,
968                    p: true,
969                    f: true,
970                    picture_id: 0x02,
971                    extended_pid: Some(0x02),
972                    pdiff: [0x01, 0x02, 0],
973                    ..Default::default()
974                },
975                &[],
976                None,
977            ),
978            (
979                "FlexiblePictureIDRefIndex_ShortPacket0",
980                &[0xD0, 0x02, 0x03],
981                Vp9Depacketizer::default(),
982                &[],
983                Some(PacketError::ErrShortPacket),
984            ),
985            (
986                "FlexiblePictureIDRefIndex_ShortPacket1",
987                &[0xD0, 0x02],
988                Vp9Depacketizer::default(),
989                &[],
990                Some(PacketError::ErrShortPacket),
991            ),
992            (
993                "FlexiblePictureIDRefIndex_ShortPacket2",
994                &[0xD0],
995                Vp9Depacketizer::default(),
996                &[],
997                Some(PacketError::ErrShortPacket),
998            ),
999            (
1000                "ScalabilityStructureResolutionsNoPayload",
1001                &[
1002                    0x0A,
1003                    (1 << 5) | (1 << 4), // NS:1 Y:1 G:0
1004                    (640 >> 8) as u8,
1005                    (640 & 0xff) as u8,
1006                    (360 >> 8) as u8,
1007                    (360 & 0xff) as u8,
1008                    (1280 >> 8) as u8,
1009                    (1280 & 0xff) as u8,
1010                    (720 >> 8) as u8,
1011                    (720 & 0xff) as u8,
1012                ],
1013                Vp9Depacketizer {
1014                    b: true,
1015                    v: true,
1016                    ns: 1,
1017                    y: true,
1018                    g: false,
1019                    ng: 0,
1020                    width: {
1021                        let mut res = [None; MAX_SPATIAL_LAYERS];
1022                        res[0] = Some(640);
1023                        res[1] = Some(1280);
1024
1025                        res
1026                    },
1027                    height: {
1028                        let mut res = [None; MAX_SPATIAL_LAYERS];
1029                        res[0] = Some(360);
1030                        res[1] = Some(720);
1031
1032                        res
1033                    },
1034                    ..Default::default()
1035                },
1036                &[],
1037                None,
1038            ),
1039            (
1040                "ScalabilityStructureNoPayload",
1041                &[
1042                    0x0A,
1043                    (1 << 5) | (1 << 3), // NS:1 Y:0 G:1
1044                    2,
1045                    (1 << 4),            // T:0 U:1 R:0 -
1046                    (2 << 5) | (1 << 2), // T:2 U:0 R:1 -
1047                    33,
1048                ],
1049                Vp9Depacketizer {
1050                    b: true,
1051                    v: true,
1052                    ns: 1,
1053                    y: false,
1054                    g: true,
1055                    ng: 2,
1056                    pgtid: vec![0, 2],
1057                    pgu: vec![true, false],
1058                    pgpdiff: vec![vec![], vec![33]],
1059                    ..Default::default()
1060                },
1061                &[],
1062                None,
1063            ),
1064            (
1065                "ScalabilityStructureNoPictureGroupNoPayload",
1066                &[
1067                    0x0A,
1068                    1 << 3, // NS:0 Y:0 G:1
1069                    0,      // N_G=0, valid: single temporal layer / no fixed dependency info
1070                ],
1071                Vp9Depacketizer {
1072                    b: true,
1073                    v: true,
1074                    ns: 0,
1075                    y: false,
1076                    g: true,
1077                    ng: 0,
1078                    ..Default::default()
1079                },
1080                &[],
1081                None,
1082            ),
1083            (
1084                "ScalabilityStructureThreeLayers",
1085                &[
1086                    0x0A,
1087                    (2 << 5) | (1 << 4), // NS:2 Y:1 G:0
1088                    (480 >> 8) as u8,
1089                    (480 & 0xff) as u8,
1090                    (270 >> 8) as u8,
1091                    (270 & 0xff) as u8,
1092                    (960 >> 8) as u8,
1093                    (960 & 0xff) as u8,
1094                    (540 >> 8) as u8,
1095                    (540 & 0xff) as u8,
1096                    (1920 >> 8) as u8,
1097                    (1920 & 0xff) as u8,
1098                    (1080 >> 8) as u8,
1099                    (1080 & 0xff) as u8,
1100                ],
1101                Vp9Depacketizer {
1102                    b: true,
1103                    v: true,
1104                    ns: 2,
1105                    y: true,
1106                    g: false,
1107                    ng: 0,
1108                    width: [Some(480), Some(960), Some(1920)],
1109                    height: [Some(270), Some(540), Some(1080)],
1110                    ..Default::default()
1111                },
1112                &[],
1113                None,
1114            ),
1115            (
1116                "ParseRefIdx",
1117                &[
1118                    0xD8,                              /* I:1 P:1 L:0 F:1
1119                                                        * B:1 E:0 V:0 Z:0 */
1120                    (0x80 | ((17 >> 8) & 0x7F)) as u8, // Two byte pictureID.
1121                    17,                                // TL0PICIDX
1122                    (17 << 1) | 1,                     // P_DIFF N:1
1123                    (18 << 1) | 1,                     // P_DIFF N:1
1124                    (127 << 1) | 0,                    // P_DIFF N:0
1125                ],
1126                Vp9Depacketizer {
1127                    i: true,
1128                    p: true,
1129                    f: true,
1130                    b: true,
1131                    picture_id: 17,
1132                    extended_pid: Some(17),
1133                    pdiff: [17, 18, 127],
1134                    ..Default::default()
1135                },
1136                &[],
1137                None,
1138            ),
1139        ];
1140
1141        for (name, b, pkt, expected, err) in tests {
1142            let mut p = Vp9Depacketizer::default();
1143
1144            if let Some(expected) = err {
1145                let mut payload = Vec::new();
1146                let mut extra = CodecExtra::None;
1147                if let Err(actual) = p.depacketize(b, &mut payload, &mut extra) {
1148                    assert_eq!(
1149                        expected, actual,
1150                        "{name}: expected {expected}, but got {actual}"
1151                    );
1152                } else {
1153                    panic!("{name}: expected error, but got passed");
1154                }
1155            } else {
1156                let mut payload = Vec::new();
1157                let mut extra = CodecExtra::None;
1158                p.depacketize(b, &mut payload, &mut extra)?;
1159                assert_eq!(pkt, p, "{name}: expected {pkt:?}, but got {p:?}");
1160                assert_eq!(payload, expected);
1161            }
1162        }
1163
1164        Ok(())
1165    }
1166
1167    #[test]
1168    fn test_vp9_packetizer_payload() -> Result<(), PacketError> {
1169        let mut rands = vec![];
1170        for r0 in 8692..8702 {
1171            rands.push(vec![(r0 >> 8) as u8 | 0x80, (r0 & 0xFF) as u8]);
1172        }
1173
1174        // Non-flexible mode (F=0) header layout:
1175        //   Byte 0: I|P|L|F|B|E|V|Z  (I=1, L=1 always set)
1176        //   Bytes 1-2: 15-bit PID (M=1)
1177        //   Byte 3: TID(3)|U(1)|SID(3)|D(1) = 0x10 (TID=0, U=1, SID=0, D=0)
1178        //   Byte 4: tl0picidx (wrapping u8, increments every frame)
1179        //   [Byte 5]: SS data on keyframe first packet only (N_S=0, Y=0, G=0)
1180        //
1181        // Flags byte (non-keyframe): I=1,P=1,L=1,F=0 = 0xE0 base
1182        //   + B=0x08, E=0x04
1183        //   B+E: 0xEC, B only: 0xE8, E only: 0xE4, neither: 0xE0
1184        //
1185        // Test payloads (0x01, 0x02, etc.) don't match VP9 bitstream keyframe
1186        // pattern (frame_marker != 0b10), so they are treated as inter-frames (P=1).
1187        // tl0picidx starts at 0 and increments by 1 per frame.
1188        let tests: Vec<(&str, Vec<Vec<u8>>, usize, Vec<Vec<u8>>)> = vec![
1189            ("NilPayload", vec![vec![]], 100, vec![]),
1190            ("SmallMTU", vec![vec![0x00, 0x00]], 1, vec![]),
1191            ("NegativeMTU", vec![vec![0x00, 0x00]], 0, vec![]),
1192            (
1193                // Inter-frame, single packet: B+E set, tl0picidx=1
1194                "OnePacket",
1195                vec![vec![0x01, 0x02]],
1196                10,
1197                vec![vec![0xEC, rands[0][0], rands[0][1], 0x10, 0x01, 0x01, 0x02]],
1198            ),
1199            (
1200                // Inter-frame, 2 packets: MTU=9 → max_frag=1, tl0picidx=1
1201                "TwoPackets",
1202                vec![vec![0x01, 0x02]],
1203                9,
1204                vec![
1205                    vec![0xE8, rands[0][0], rands[0][1], 0x10, 0x01, 0x01],
1206                    vec![0xE4, rands[0][0], rands[0][1], 0x10, 0x01, 0x02],
1207                ],
1208            ),
1209            (
1210                // Inter-frame, 3 packets: MTU=9 → max_frag=1, tl0picidx=1
1211                "ThreePackets",
1212                vec![vec![0x01, 0x02, 0x03]],
1213                9,
1214                vec![
1215                    vec![0xE8, rands[0][0], rands[0][1], 0x10, 0x01, 0x01],
1216                    vec![0xE0, rands[0][0], rands[0][1], 0x10, 0x01, 0x02],
1217                    vec![0xE4, rands[0][0], rands[0][1], 0x10, 0x01, 0x03],
1218                ],
1219            ),
1220            (
1221                // Two inter-frames: frame1 tl0picidx=1, frame2 tl0picidx=2
1222                "TwoFramesFourPackets",
1223                vec![vec![0x01, 0x02, 0x03], vec![0x04]],
1224                10,
1225                vec![
1226                    vec![0xE8, rands[0][0], rands[0][1], 0x10, 0x01, 0x01, 0x02],
1227                    vec![0xE4, rands[0][0], rands[0][1], 0x10, 0x01, 0x03],
1228                    vec![0xEC, rands[1][0], rands[1][1], 0x10, 0x02, 0x04],
1229                ],
1230            ),
1231        ];
1232
1233        for (name, bs, mtu, expected) in tests {
1234            let mut pck = Vp9Packetizer {
1235                initial_picture_id: 8692,
1236                ..Default::default()
1237            };
1238
1239            let mut actual = vec![];
1240            for b in &bs {
1241                actual.extend(pck.packetize(mtu, b)?);
1242            }
1243            assert_eq!(expected, actual, "{name}: Payloaded packet");
1244        }
1245
1246        //"PictureIDOverflow"
1247        {
1248            let mut pck = Vp9Packetizer {
1249                initial_picture_id: 8692,
1250                ..Default::default()
1251            };
1252            let mut p_prev = Vp9Depacketizer::default();
1253            for i in 0..0x8000 {
1254                let res = pck.packetize(9, &[0x01])?;
1255                let mut p = Vp9Depacketizer::default();
1256                let mut payload = Vec::new();
1257                let mut extra = CodecExtra::None;
1258                p.depacketize(&res[0], &mut payload, &mut extra)?;
1259
1260                if i > 0 {
1261                    if p_prev.picture_id == 0x7FFF {
1262                        assert_eq!(
1263                            p.picture_id, 0,
1264                            "Picture ID next to 0x7FFF must be 0, got {}",
1265                            p.picture_id
1266                        );
1267                    } else if p_prev.picture_id + 1 != p.picture_id {
1268                        panic!(
1269                            "Picture ID next must be incremented by 1: {} -> {}",
1270                            p_prev.picture_id, p.picture_id,
1271                        );
1272                    }
1273                }
1274
1275                p_prev = p;
1276            }
1277        }
1278
1279        Ok(())
1280    }
1281
1282    #[test]
1283    fn test_vp9_packetizer_keyframe() -> Result<(), PacketError> {
1284        let mut pck = Vp9Packetizer {
1285            initial_picture_id: 100,
1286            ..Default::default()
1287        };
1288
1289        // VP9 profile 0 keyframe bitstream: 0x82 = 0b10_00_0_0_10
1290        // frame_marker=10, profile=00, show_existing=0, frame_type=0 (KEY)
1291        let keyframe = vec![0x82, 0xAA, 0xBB];
1292        let packets = pck.packetize(20, &keyframe)?;
1293
1294        assert_eq!(packets.len(), 1);
1295        let pkt = &packets[0];
1296        // Flags: I=1,P=0,L=1,F=0,B=1,E=1,V=1,Z=0 = 0xAE
1297        assert_eq!(pkt[0], 0xAE, "Keyframe flags should be 0xAE");
1298        // PID
1299        assert_eq!(pkt[1], (100 >> 8) as u8 | 0x80);
1300        assert_eq!(pkt[2], 100);
1301        // L byte: TID=0, U=1, SID=0, D=0
1302        assert_eq!(pkt[3], 0x10);
1303        // tl0picidx = 1 (first frame)
1304        assert_eq!(pkt[4], 1);
1305        // SS: N_S=0, Y=0, G=0 (no GOF) → 0x00 (1 byte)
1306        assert_eq!(pkt[5], 0x00);
1307        // Payload starts right after the 1-byte SS
1308        assert_eq!(&pkt[6..], &keyframe[..]);
1309
1310        // Parse-side: the emitted SS decodes as a single-layer, no-GOF structure (N_S=0, Y/G false).
1311        let mut dep = Vp9Depacketizer::default();
1312        let mut out = Vec::new();
1313        let mut extra = CodecExtra::None;
1314        dep.depacketize(pkt, &mut out, &mut extra)?;
1315        assert!(dep.v && dep.ns == 0 && !dep.y && !dep.g && dep.ng == 0);
1316        assert_eq!(&out[..], &keyframe[..]);
1317
1318        // Now an inter-frame: 0x84 = 0b10_00_0_1_00 (frame_type=1)
1319        let inter = vec![0x84, 0xCC];
1320        let packets = pck.packetize(20, &inter)?;
1321        assert_eq!(packets.len(), 1);
1322        let pkt = &packets[0];
1323        // Flags: I=1,P=1,L=1,F=0,B=1,E=1,V=0,Z=0 = 0xEC
1324        assert_eq!(pkt[0], 0xEC, "Inter-frame flags should be 0xEC");
1325        // tl0picidx = 2 (second frame, both TID=0 so both increment)
1326        assert_eq!(pkt[4], 2);
1327        // No SS data — payload starts at byte 5
1328        assert_eq!(&pkt[5..], &inter[..]);
1329
1330        Ok(())
1331    }
1332
1333    #[test]
1334    fn test_vp9_packetizer_fragmented_keyframe() -> Result<(), PacketError> {
1335        let mut pck = Vp9Packetizer {
1336            initial_picture_id: 50,
1337            ..Default::default()
1338        };
1339
1340        // VP9 profile 0 keyframe: 0x82 = frame_marker=10, profile=00, show_existing=0, frame_type=0
1341        // 10 bytes of payload, MTU=12 → max_frag = 12 - 8 = 4 (conservative reserve)
1342        // First packet: 6-byte header (with 1-byte G=0 SS) + 4 bytes payload = 10 ≤ MTU
1343        // Second packet: 5-byte header + 4 bytes payload = 9 ≤ MTU
1344        // Third packet: 5-byte header + 2 bytes payload = 7 ≤ MTU
1345        let keyframe = vec![0x82, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09];
1346        let packets = pck.packetize(12, &keyframe)?;
1347
1348        assert_eq!(
1349            packets.len(),
1350            3,
1351            "10-byte keyframe at MTU=12 should produce 3 packets"
1352        );
1353
1354        // Packet 1: B=1, E=0, V=1 (keyframe first)
1355        // Flags: I=1,P=0,L=1,F=0,B=1,E=0,V=1,Z=0 = 0xAA
1356        assert_eq!(packets[0][0], 0xAA);
1357        assert_eq!(packets[0].len(), 10); // 6-byte header + 4-byte payload
1358        assert_eq!(packets[0][3], 0x10); // L byte
1359        assert_eq!(packets[0][4], 1); // tl0picidx
1360        assert_eq!(packets[0][5], 0x00); // SS byte: N_S=0, Y=0, G=0 (no GOF)
1361        assert_eq!(&packets[0][6..], &keyframe[0..4]); // payload
1362
1363        // Packet 2: B=0, E=0, V=0 (middle)
1364        // Flags: I=1,P=0,L=1,F=0,B=0,E=0,V=0,Z=0 = 0xA0
1365        assert_eq!(packets[1][0], 0xA0);
1366        assert_eq!(packets[1].len(), 9); // 5-byte header + 4-byte payload
1367        assert_eq!(packets[1][4], 1); // same tl0picidx
1368        assert_eq!(&packets[1][5..], &keyframe[4..8]);
1369
1370        // Packet 3: B=0, E=1, V=0 (last)
1371        // Flags: I=1,P=0,L=1,F=0,B=0,E=1,V=0,Z=0 = 0xA4
1372        assert_eq!(packets[2][0], 0xA4);
1373        assert_eq!(packets[2].len(), 7); // 5-byte header + 2-byte payload
1374        assert_eq!(&packets[2][5..], &keyframe[8..10]);
1375
1376        // Verify none exceed MTU
1377        for (i, pkt) in packets.iter().enumerate() {
1378            assert!(
1379                pkt.len() <= 12,
1380                "Packet {i} exceeds MTU: {} > 12",
1381                pkt.len()
1382            );
1383        }
1384
1385        // Verify depacketizer round-trip: all 3 packets produce original payload
1386        let mut full_payload = Vec::new();
1387        let mut extra = CodecExtra::None;
1388        for pkt in &packets {
1389            let mut depkt = Vp9Depacketizer::default();
1390            depkt.depacketize(pkt, &mut full_payload, &mut extra)?;
1391        }
1392        assert_eq!(full_payload, keyframe);
1393
1394        Ok(())
1395    }
1396
1397    #[test]
1398    fn test_vp9_tl0picidx_wrapping() -> Result<(), PacketError> {
1399        let mut pck = Vp9Packetizer {
1400            initial_picture_id: 0,
1401            tl0picidx: 254, // Start near wrap point
1402            ..Default::default()
1403        };
1404
1405        // Frame 1: tl0picidx wraps 254 → 255
1406        let packets = pck.packetize(20, &[0x01])?;
1407        assert_eq!(packets[0][4], 255);
1408
1409        // Frame 2: tl0picidx wraps 255 → 0
1410        let packets = pck.packetize(20, &[0x01])?;
1411        assert_eq!(packets[0][4], 0);
1412
1413        // Frame 3: 0 → 1
1414        let packets = pck.packetize(20, &[0x01])?;
1415        assert_eq!(packets[0][4], 1);
1416
1417        Ok(())
1418    }
1419
1420    fn depacketize_one(depack: &mut Vp9Depacketizer, packet: &[u8]) -> Vp9CodecExtra {
1421        let mut payload = Vec::new();
1422        let mut extra = CodecExtra::None;
1423        depack
1424            .depacketize(packet, &mut payload, &mut extra)
1425            .unwrap();
1426        let CodecExtra::Vp9(extra) = extra else {
1427            panic!("expected VP9 codec extra");
1428        };
1429        extra
1430    }
1431
1432    #[test]
1433    fn depacketizer_extends_picture_id_and_tl0picidx() {
1434        let mut depack = Vp9Depacketizer::default();
1435
1436        for (pid, tl0, expected_pid, expected_tl0) in [
1437            (0x7FFE_u16, 254_u8, 0x7FFE_u64, 254_u64),
1438            (0x7FFF, 255, 0x7FFF, 255),
1439            (0, 0, 0x8000, 256),
1440            (1, 1, 0x8001, 257),
1441        ] {
1442            // I=1 L=1 B=1 E=1, 15-bit picture id, TID=0, tl0picidx
1443            let packet = [0xAC, 0x80 | (pid >> 8) as u8, pid as u8, 0x00, tl0, 0xAA];
1444            let extra = depacketize_one(&mut depack, &packet);
1445            assert_eq!(extra.picture_id, Some(expected_pid), "pid {pid}");
1446            assert_eq!(extra.tl0_picture_id, Some(expected_tl0), "tl0 {tl0}");
1447        }
1448    }
1449
1450    #[test]
1451    fn depacketizer_extends_7_bit_picture_id() {
1452        let mut depack = Vp9Depacketizer::default();
1453
1454        for (pid, expected) in [(126_u8, 126_u64), (127, 127), (0, 128), (1, 129)] {
1455            // I=1 B=1 E=1, 7-bit picture id
1456            let extra = depacketize_one(&mut depack, &[0x8C, pid, 0xAA]);
1457            assert_eq!(extra.picture_id, Some(expected), "pid {pid}");
1458        }
1459    }
1460
1461    #[test]
1462    fn depacketizer_reports_missing_picture_id() {
1463        let mut depack = Vp9Depacketizer::default();
1464
1465        let extra = depacketize_one(&mut depack, &[0xAC, 0x92, 0x34, 0x00, 7, 0xAA]);
1466        assert_eq!(extra.picture_id, Some(0x1234));
1467
1468        // I=0 L=1 B=1 E=1
1469        let extra = depacketize_one(&mut depack, &[0x2C, 0x00, 8, 0xAA]);
1470        assert_eq!(extra.picture_id, None);
1471        assert_eq!(extra.tl0_picture_id, Some(8));
1472
1473        // Picture id on the first packet of the frame only
1474        let mut payload = Vec::new();
1475        let mut extra = CodecExtra::None;
1476        depack
1477            .depacketize(&[0xA8, 0x92, 0x35, 0x00, 9, 0xAA], &mut payload, &mut extra)
1478            .unwrap();
1479        depack
1480            .depacketize(&[0x24, 0x00, 9, 0xBB], &mut payload, &mut extra)
1481            .unwrap();
1482        let CodecExtra::Vp9(extra) = extra else {
1483            panic!("expected VP9 codec extra");
1484        };
1485        assert_eq!(extra.picture_id, Some(0x1235));
1486    }
1487
1488    fn assert_every_frame_emitted(frames: impl IntoIterator<Item = Vec<Vec<u8>>>) {
1489        use crate::packet::{CodecDepacketizer, DepacketizingBuffer, RtpMeta};
1490        use crate::rtp_::{MediaTime, RtpHeader};
1491        use std::time::Instant;
1492
1493        let mut buf =
1494            DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 3);
1495        let now = Instant::now();
1496        let mut seq = 0_u64;
1497
1498        for (frame, packets) in frames.into_iter().enumerate() {
1499            let count = packets.len();
1500            let time = frame as u64 * 3000;
1501
1502            for (i, packet) in packets.into_iter().enumerate() {
1503                let meta = RtpMeta {
1504                    received: now,
1505                    time: MediaTime::from_90khz(time),
1506                    seq_no: seq.into(),
1507                    last_sender_info: None,
1508                    header: RtpHeader {
1509                        sequence_number: seq as u16,
1510                        timestamp: time as u32,
1511                        marker: i == count - 1,
1512                        ..Default::default()
1513                    },
1514                };
1515                buf.push(meta, packet);
1516                seq += 1;
1517            }
1518
1519            let dep = buf
1520                .pop(now, None)
1521                .unwrap_or_else(|| panic!("frame {frame} was not emitted"))
1522                .unwrap();
1523            assert!(dep.contiguous, "frame {frame} is not contiguous");
1524        }
1525    }
1526
1527    #[test]
1528    fn depacketizing_buffer_emits_every_frame_across_wraps() {
1529        let mut pck = Vp9Packetizer {
1530            initial_picture_id: 0x7FFF - 100,
1531            tl0picidx: 200,
1532            ..Default::default()
1533        };
1534        let frames: Vec<_> = (0..300)
1535            .map(|frame| {
1536                let first_byte = if frame == 0 { 0x80 } else { 0x84 };
1537                pck.packetize(10, &[first_byte, 1, 2, 3]).unwrap()
1538            })
1539            .collect();
1540
1541        assert_every_frame_emitted(frames);
1542    }
1543
1544    #[test]
1545    fn depacketizing_buffer_emits_every_frame_with_7_bit_picture_id() {
1546        // I=1 L=1 B=1 E=1 (P=1 after the first frame), 7-bit picture id, TID=0, tl0picidx
1547        let frames = (0..600_u64).map(|frame| {
1548            let flags = if frame == 0 { 0xAC } else { 0xEC };
1549            vec![vec![flags, (frame & 0x7F) as u8, 0x00, frame as u8, 0x84]]
1550        });
1551
1552        assert_every_frame_emitted(frames);
1553    }
1554
1555    #[test]
1556    fn depacketizing_buffer_emits_every_frame_without_picture_id() {
1557        // I=0 L=1 B=1 E=1 (P=1 after the first frame), TID=0, tl0picidx
1558        let frames = (0..300_u64).map(|frame| {
1559            let flags = if frame == 0 { 0x2C } else { 0x6C };
1560            vec![vec![flags, 0x00, frame as u8, 0x84]]
1561        });
1562
1563        assert_every_frame_emitted(frames);
1564    }
1565
1566    #[test]
1567    fn depacketizer_preserves_picture_id_epoch_when_width_grows() {
1568        let mut depack = Vp9Depacketizer::default();
1569        for (pid, expected) in [(126_u8, 126_u64), (127, 127), (0, 128), (1, 129)] {
1570            let extra = depacketize_one(&mut depack, &[0x8C, pid, 0xAA]);
1571            assert_eq!(extra.picture_id, Some(expected));
1572        }
1573        // RFC 9628 section 4.2: transitioning to 15 bits zero-extends the wire ID.
1574        let extra = depacketize_one(&mut depack, &[0x8C, 0x80, 2, 0xAA]);
1575        assert_eq!(extra.picture_id, Some(130));
1576    }
1577
1578    #[test]
1579    fn depacketizing_buffer_emits_frames_when_picture_id_width_grows() {
1580        let frames = [
1581            vec![vec![0xAC, 126, 0, 10, 0x80]],
1582            vec![vec![0xEC, 127, 0, 11, 0x84]],
1583            // A keyframe at the short-ID wrap lets the pre-PR code resynchronize.
1584            vec![vec![0xAC, 0, 0, 12, 0x80]],
1585            vec![vec![0xEC, 1, 0, 13, 0x84]],
1586            // The following picture has wire ID 0x0002 and M=1.
1587            vec![vec![0xEC, 0x80, 2, 0, 14, 0x84]],
1588            vec![vec![0xEC, 0x80, 3, 0, 15, 0x84]],
1589        ];
1590        assert_every_frame_emitted(frames);
1591    }
1592
1593    #[test]
1594    fn depacketizer_preserves_wide_picture_id_after_loss_at_width_growth() {
1595        let mut depack = Vp9Depacketizer::default();
1596        assert_eq!(
1597            depacketize_one(&mut depack, &[0x8C, 0, 0xAA]).picture_id,
1598            Some(0)
1599        );
1600        // The sender widens at PID 1; pictures 1..99 are lost in transit.
1601        let extra = depacketize_one(&mut depack, &[0x8C, 0x80, 100, 0xAA]);
1602        assert_eq!(extra.picture_id, Some(100));
1603    }
1604
1605    #[test]
1606    fn depacketizing_buffer_recovers_after_loss_at_picture_id_width_growth() {
1607        // A middlebox drops enhancement pictures 1..99 and rewrites RTP sequence numbers.
1608        // Picture 100 is a keyframe, so all following pictures are decodable.
1609        let frames =
1610            std::iter::once(vec![vec![0xAC, 0, 0, 0, 0x80]]).chain((100..=130_u8).map(|pid| {
1611                let (flags, payload) = if pid == 100 {
1612                    (0xAC, 0x80)
1613                } else {
1614                    (0xEC, 0x84)
1615                };
1616                vec![vec![flags, 0x80, pid, 0, pid - 99, payload]]
1617            }));
1618        assert_every_frame_emitted(frames);
1619    }
1620
1621    #[test]
1622    fn test_vp9_packetizer_flexible_mode() -> Result<(), PacketError> {
1623        let mut rands = vec![];
1624        for r0 in 8692..8702 {
1625            rands.push(vec![(r0 >> 8) as u8 | 0x80, (r0 & 0xFF) as u8]);
1626        }
1627
1628        // With VP9_FLEXIBLE_HEADER_SIZE=3, min productive MTU is 4.
1629        // Flexible mode: 3 bytes header (flags + 15-bit PID)
1630        //
1631        // Flags byte: I|P|L|F|B|E|V|Z
1632        //   I=1(0x80), F=1(0x10), B=first(0x08), E=last(0x04)
1633        //   B+E: 0x80|0x10|0x08|0x04 = 0x9C
1634        //   B:   0x80|0x10|0x08       = 0x98
1635        //   E:   0x80|0x10|0x04       = 0x94
1636        //   none:0x80|0x10            = 0x90
1637        let tests: Vec<(&str, Vec<Vec<u8>>, usize, Vec<Vec<u8>>)> = vec![
1638            ("NilPayload", vec![vec![]], 100, vec![]),
1639            ("SmallMTU", vec![vec![0x00, 0x00]], 1, vec![]),
1640            ("NegativeMTU", vec![vec![0x00, 0x00]], 0, vec![]),
1641            (
1642                "OnePacket",
1643                vec![vec![0x01, 0x02]],
1644                10,
1645                vec![vec![0x9C, rands[0][0], rands[0][1], 0x01, 0x02]],
1646            ),
1647            (
1648                // MTU=4 → max_frag=1 → 2 packets
1649                "TwoPackets",
1650                vec![vec![0x01, 0x02]],
1651                4,
1652                vec![
1653                    vec![0x98, rands[0][0], rands[0][1], 0x01],
1654                    vec![0x94, rands[0][0], rands[0][1], 0x02],
1655                ],
1656            ),
1657            (
1658                // MTU=4 → max_frag=1 → 3 packets
1659                "ThreePackets",
1660                vec![vec![0x01, 0x02, 0x03]],
1661                4,
1662                vec![
1663                    vec![0x98, rands[0][0], rands[0][1], 0x01],
1664                    vec![0x90, rands[0][0], rands[0][1], 0x02],
1665                    vec![0x94, rands[0][0], rands[0][1], 0x03],
1666                ],
1667            ),
1668            (
1669                // MTU=5 → max_frag=2 → frame1: 2 pkts, frame2: 1 pkt
1670                "TwoFramesFourPackets",
1671                vec![vec![0x01, 0x02, 0x03], vec![0x04]],
1672                5,
1673                vec![
1674                    vec![0x98, rands[0][0], rands[0][1], 0x01, 0x02],
1675                    vec![0x94, rands[0][0], rands[0][1], 0x03],
1676                    vec![0x9C, rands[1][0], rands[1][1], 0x04],
1677                ],
1678            ),
1679        ];
1680
1681        for (name, bs, mtu, expected) in tests {
1682            let mut pck = Vp9Packetizer {
1683                initial_picture_id: 8692,
1684                mode: Vp9PacketizerMode::Flexible,
1685                ..Default::default()
1686            };
1687
1688            let mut actual = vec![];
1689            for b in &bs {
1690                actual.extend(pck.packetize(mtu, b)?);
1691            }
1692            assert_eq!(expected, actual, "{name}: Payloaded packet");
1693        }
1694
1695        Ok(())
1696    }
1697
1698    #[test]
1699    fn test_vp9_packetizer_with_mode() {
1700        let pck = Vp9Packetizer::with_mode(Vp9PacketizerMode::Flexible);
1701        assert_eq!(pck.mode, Vp9PacketizerMode::Flexible);
1702
1703        let pck = Vp9Packetizer::with_mode(Vp9PacketizerMode::NonFlexible);
1704        assert_eq!(pck.mode, Vp9PacketizerMode::NonFlexible);
1705
1706        let pck = Vp9Packetizer::default();
1707        assert_eq!(pck.mode, Vp9PacketizerMode::NonFlexible);
1708    }
1709
1710    #[test]
1711    fn test_detect_vp9_keyframe_bitstream() {
1712        // Empty payload
1713        assert!(!detect_vp9_keyframe_bitstream(&[]));
1714
1715        // Invalid frame_marker (not 0b10)
1716        assert!(!detect_vp9_keyframe_bitstream(&[0x00])); // frame_marker=00
1717        assert!(!detect_vp9_keyframe_bitstream(&[0xC0])); // frame_marker=11
1718        assert!(!detect_vp9_keyframe_bitstream(&[0x40])); // frame_marker=01
1719
1720        // Profile 0 keyframe: 10_00_0_0_xx = 0x80..0x83
1721        assert!(detect_vp9_keyframe_bitstream(&[0x80]));
1722        assert!(detect_vp9_keyframe_bitstream(&[0x82]));
1723
1724        // Profile 0 inter-frame: 10_00_0_1_xx = 0x84..0x87
1725        assert!(!detect_vp9_keyframe_bitstream(&[0x84]));
1726        assert!(!detect_vp9_keyframe_bitstream(&[0x86]));
1727
1728        // Profile 0 show_existing_frame=1: 10_00_1_x_xx = 0x88..0x8F
1729        assert!(!detect_vp9_keyframe_bitstream(&[0x88]));
1730        assert!(!detect_vp9_keyframe_bitstream(&[0x8C]));
1731
1732        // Profile 1 keyframe: 10_10_0_0_xx = 0xA0..0xA3
1733        assert!(detect_vp9_keyframe_bitstream(&[0xA0]));
1734
1735        // Profile 1 inter-frame: 10_10_0_1_xx = 0xA4..0xA7
1736        assert!(!detect_vp9_keyframe_bitstream(&[0xA4]));
1737
1738        // Profile 2 keyframe: 10_01_R_0_0_x
1739        // 0x90 = 10_01_0_0_00 → profile_high=1, show_existing=0, frame_type=0
1740        assert!(detect_vp9_keyframe_bitstream(&[0x90]));
1741
1742        // Profile 2 inter-frame: 10_01_0_0_1_0 = 0x92
1743        assert!(!detect_vp9_keyframe_bitstream(&[0x92]));
1744    }
1745
1746    #[test]
1747    fn test_vp9_partition_head_checker_is_partition_head() -> Result<(), PacketError> {
1748        let vp9 = Vp9Depacketizer::default();
1749
1750        //"SmallPacket"
1751        assert!(
1752            !vp9.is_partition_head(&[]),
1753            "Small packet should not be the head of a new partition"
1754        );
1755
1756        //"NormalPacket"
1757        assert!(
1758            vp9.is_partition_head(&[0x18, 0x00, 0x00]),
1759            "VP9 RTP packet with B flag should be head of a new partition"
1760        );
1761        assert!(
1762            !vp9.is_partition_head(&[0x10, 0x00, 0x00]),
1763            "VP9 RTP packet without B flag should not be head of a new partition"
1764        );
1765
1766        Ok(())
1767    }
1768
1769    #[test]
1770    fn test_detect_vp9_keyframe() {
1771        // Empty payload
1772        assert!(!detect_vp9_keyframe(&[]));
1773
1774        // VP9 RTP descriptor byte 0: I|P|L|F|B|E|V|Z
1775        // P=0 (bit 6 clear) → keyframe
1776        // P=1 (bit 6 set) → inter-frame
1777
1778        // Keyframes (P=0)
1779        assert!(detect_vp9_keyframe(&[0x80])); // I=1
1780        assert!(detect_vp9_keyframe(&[0xA0])); // I=1, L=1
1781        assert!(detect_vp9_keyframe(&[0xAE])); // I=1, L=1, B=1, E=1, V=1
1782        assert!(detect_vp9_keyframe(&[0x00])); // all flags clear
1783
1784        // Inter-frames (P=1)
1785        assert!(!detect_vp9_keyframe(&[0xE8])); // I=1, P=1, L=1, B=1
1786        assert!(!detect_vp9_keyframe(&[0xEC])); // I=1, P=1, L=1, B=1, E=1
1787        assert!(!detect_vp9_keyframe(&[0x40])); // P=1 only
1788        assert!(!detect_vp9_keyframe(&[0xD5])); // I=1, P=1, F=1, E=1, Z=1
1789    }
1790
1791    #[test]
1792    fn packetize_respects_mtu() -> Result<(), PacketError> {
1793        // VP9 profile 0 keyframe header followed by payload bytes.
1794        let mut payload = vec![0x82u8];
1795        payload.extend(std::iter::repeat_n(0xABu8, 2000));
1796        for &mtu in &[100usize, 300, 600, 1200] {
1797            let mut pck = Vp9Packetizer {
1798                initial_picture_id: 100,
1799                ..Default::default()
1800            };
1801            let pkts = pck.packetize(mtu, &payload)?;
1802            assert!(!pkts.is_empty(), "VP9 produced no packets at mtu {mtu}");
1803            for (i, pkt) in pkts.iter().enumerate() {
1804                assert!(
1805                    pkt.len() <= mtu,
1806                    "VP9 packet {i} size {} > mtu {mtu}",
1807                    pkt.len()
1808                );
1809            }
1810        }
1811        Ok(())
1812    }
1813}