Skip to main content

rtci_rtp/codec/vp9/
mod.rs

1#[cfg(test)]
2mod vp9_depacketizer_fields_test;
3#[cfg(test)]
4mod vp9_descriptor_test;
5#[cfg(test)]
6mod vp9_layers_test;
7#[cfg(test)]
8mod vp9_test;
9
10use crate::packetizer::{Depacketizer, Payloader};
11use shared::error::{Error, Result};
12
13use bytes::{Buf, BufMut, Bytes, BytesMut};
14use std::fmt;
15use std::sync::Arc;
16
17/// The mandatory octet and a 15-bit picture ID
18const VP9HEADER_SIZE: usize = 3;
19const MAX_VP9REF_PICS: usize = 3;
20/// The number of reference frame slots a VP9 decoder keeps (VP9 bitstream specification 3).
21const VP9_REF_SLOTS: usize = 8;
22
23/// The highest spatial layer id the three-bit `SID` field carries (RFC 9628 section 4.2).
24pub const VP9_MAX_SPATIAL_ID: u8 = 7;
25/// The highest temporal layer id the three-bit `TID` field carries (RFC 9628 section 4.2).
26pub const VP9_MAX_TEMPORAL_ID: u8 = 7;
27/// The largest reference index (`P_DIFF`) the seven-bit field carries.
28pub const VP9_MAX_P_DIFF: u8 = 127;
29
30/// InitialPictureIDFn is a function that returns random initial picture ID.
31pub type InitialPictureIDFn = Arc<dyn (Fn() -> u16) + Send + Sync>;
32
33/// One picture of a VP9 picture group (RFC 9628 section 4.2.1): its temporal layer, whether it
34/// is a switching up point, and the pictures it predicts from.
35#[derive(Debug, Default, Clone, PartialEq, Eq)]
36pub struct Vp9PictureGroupEntry {
37    /// `TID` of the picture.
38    pub temporal_id: u8,
39    /// `U`: pictures of higher temporal layers after this one do not depend on pictures of
40    /// higher temporal layers before it.
41    pub switching_up_point: bool,
42    /// The picture's reference indices (`P_DIFF`, at most three): how many pictures back each
43    /// reference is.
44    pub reference_diffs: Vec<u8>,
45}
46
47/// The VP9 scalability structure (SS, RFC 9628 section 4.2.1): the number of spatial layers,
48/// their resolutions, and for a fixed prediction pattern the picture group (PG).
49#[derive(Debug, Default, Clone, PartialEq, Eq)]
50pub struct Vp9ScalabilityStructure {
51    /// The number of spatial layers in the stream, 1 to 8 (`N_S` + 1).
52    pub spatial_layers: u8,
53    /// Width and height of each spatial layer's frames, lowest layer first. Empty when the SS
54    /// carries no resolutions (`Y`=0); otherwise one entry per spatial layer.
55    pub resolutions: Vec<(u16, u16)>,
56    /// The picture group, in order from the key picture on. Empty when the SS describes none
57    /// (`G`=0): one temporal layer in non-flexible mode, or dependencies given per packet in
58    /// flexible mode.
59    pub picture_group: Vec<Vp9PictureGroupEntry>,
60}
61
62impl Vp9ScalabilityStructure {
63    /// Checks that the structure can be written: 1 to 8 spatial layers, a resolution for each
64    /// or none, at most 255 pictures in the group with at most three references each, and a
65    /// first picture in temporal layer 0 (RFC 9628 section 4.2.1).
66    pub fn validate(&self) -> Result<()> {
67        let fail = |what: &str| Err(Error::Other(format!("VP9 scalability structure: {what}")));
68        if self.spatial_layers == 0 || self.spatial_layers > VP9_MAX_SPATIAL_ID + 1 {
69            return fail("1 to 8 spatial layers");
70        }
71        if !self.resolutions.is_empty() && self.resolutions.len() != self.spatial_layers as usize {
72            return fail("one resolution per spatial layer, or none");
73        }
74        if self.picture_group.len() > 255 {
75            return fail("at most 255 pictures in a picture group");
76        }
77        for entry in &self.picture_group {
78            if entry.temporal_id > VP9_MAX_TEMPORAL_ID {
79                return fail("TID is three bits");
80            }
81            if entry.reference_diffs.len() > MAX_VP9REF_PICS {
82                return fail("at most three reference indices per picture");
83            }
84        }
85        if self
86            .picture_group
87            .first()
88            .is_some_and(|e| e.temporal_id != 0)
89        {
90            return fail("the first picture of the group has TID 0");
91        }
92        Ok(())
93    }
94
95    /// The number of octets [`marshal_to`](Self::marshal_to) writes.
96    pub fn marshal_size(&self) -> usize {
97        let mut size = 1 + 4 * self.resolutions.len();
98        if !self.picture_group.is_empty() {
99            size += 1;
100            for entry in &self.picture_group {
101                size += 1 + entry.reference_diffs.len();
102            }
103        }
104        size
105    }
106
107    /// Appends the SS as it appears in a payload descriptor with `V`=1. The reserved bits are
108    /// written as 0.
109    ///
110    /// # Errors
111    ///
112    /// Whatever [`validate`](Self::validate) refuses.
113    pub fn marshal_to(&self, out: &mut BytesMut) -> Result<()> {
114        self.validate()?;
115        //      +-+-+-+-+-+-+-+-+
116        // V:   | N_S |Y|G|-|-|-|
117        //      +-+-+-+-+-+-+-+-+
118        let mut b = (self.spatial_layers - 1) << 5;
119        if !self.resolutions.is_empty() {
120            b |= 0x10; // Y
121        }
122        if !self.picture_group.is_empty() {
123            b |= 0x08; // G
124        }
125        out.put_u8(b);
126        for (width, height) in &self.resolutions {
127            out.put_u16(*width);
128            out.put_u16(*height);
129        }
130        if !self.picture_group.is_empty() {
131            out.put_u8(self.picture_group.len() as u8); // N_G
132            for entry in &self.picture_group {
133                // | TID |U| R |-|-|
134                let mut b = entry.temporal_id << 5;
135                if entry.switching_up_point {
136                    b |= 0x10;
137                }
138                b |= (entry.reference_diffs.len() as u8) << 2;
139                out.put_u8(b);
140                for diff in &entry.reference_diffs {
141                    out.put_u8(*diff);
142                }
143            }
144        }
145        Ok(())
146    }
147}
148
149/// What the encoder knows about one VP9 frame (one spatial layer of a picture) and the payload
150/// descriptor carries (RFC 9628 section 4.2).
151///
152/// The default describes the only frame of a picture in temporal layer 0: `end_of_picture` is
153/// set, the rest is 0 / unset.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct Vp9FrameInfo {
156    /// `TID`, the frame's temporal layer (0 to 7). Every frame of a picture has the same one,
157    /// except in a pattern with shifted temporal layers, which only flexible mode can carry.
158    pub temporal_id: u8,
159    /// `SID`, the frame's spatial layer (0 to 7). The frames of a picture are sent in
160    /// increasing order.
161    pub spatial_id: u8,
162    /// `U`: pictures of higher temporal layers after this one do not depend on pictures of
163    /// higher temporal layers before it.
164    pub switching_up_point: bool,
165    /// `D`: the frame predicts from the frame of spatial layer `SID`-1 of the same picture.
166    pub inter_layer_dependency: bool,
167    /// `Z`: no frame of a higher spatial layer, in this picture or a later one, depends on
168    /// this frame.
169    pub not_reference_for_upper_layers: bool,
170    /// The frame is the picture's last. The next frame starts a picture with the next picture
171    /// ID, and the RTP marker belongs on this frame's last packet (RFC 9628 section 4.1).
172    pub end_of_picture: bool,
173    /// Whether the frame is a key frame. `None` reads it from the frame's uncompressed header;
174    /// set it when the payloader cannot (the frame is encrypted end to end).
175    pub key_frame: Option<bool>,
176    /// `P`: whether the frame predicts from another picture. `None` derives it from the
177    /// frame's uncompressed header (the reference slots it reads).
178    pub inter_picture_predicted: Option<bool>,
179    /// Flexible mode's reference indices (`P_DIFF`): how many pictures back each picture the
180    /// frame predicts from is, at most three values of 1 to 127. Empty derives them from the
181    /// frame's uncompressed header.
182    pub reference_diffs: Vec<u8>,
183}
184
185impl Default for Vp9FrameInfo {
186    fn default() -> Self {
187        Self {
188            temporal_id: 0,
189            spatial_id: 0,
190            switching_up_point: false,
191            inter_layer_dependency: false,
192            not_reference_for_upper_layers: false,
193            end_of_picture: true,
194            key_frame: None,
195            inter_picture_predicted: None,
196            reference_diffs: vec![],
197        }
198    }
199}
200
201/// Vp9Payloader payloads VP9 packets.
202///
203/// By default it uses the non-flexible mode, as browsers expect from a sender
204/// without SVC (RFC 9628 section 4.2): it reads each frame's uncompressed
205/// header, marks a frame that predicts from another picture with `P=1` (a key
206/// or intra-only frame with `P=0`), and puts a scalability structure with the
207/// frame size on a key frame's first packet. `flexible_mode` selects the
208/// flexible mode instead: no scalability structure unless one is set, and the
209/// reference indices (`P_DIFF`) of every predicted frame, read from the
210/// header's reference slots.
211///
212/// The mode only changes at a key picture, as the RFC requires. A stream
213/// whose first frame is not VP9 at all starts in flexible mode, as before,
214/// and stays there until a key frame parses; such a frame is sent with `P=1`
215/// (unknown, so not offered as a switch point) unless it is the stream's
216/// first.
217///
218/// [`Payloader::payload`] sends a picture of one frame without layer indices.
219/// [`Vp9Payloader::payload_layer_frame`] takes the frame's layer information
220/// from the encoder and writes the layer indices (`TID`, `U`, `SID`, `D`,
221/// `TL0PICIDX`), `Z`, and one picture ID for all the frames of a picture.
222#[derive(Default, Clone)]
223pub struct Vp9Payloader {
224    picture_id: u16,
225    initialized: bool,
226
227    /// Supplies the starting picture id; randomized when absent.
228    pub initial_picture_id_fn: Option<InitialPictureIDFn>,
229    /// Sends in flexible mode (`F=1`) instead of non-flexible mode.
230    pub flexible_mode: bool,
231    /// The `TL0PICIDX` of the first picture of temporal layer 0; random when absent (RFC 9628
232    /// section 4.2: "SHOULD start on a random number").
233    pub initial_tl0_pic_idx: Option<u8>,
234
235    /// The SS to send on key pictures.
236    scalability_structure: Option<Vp9ScalabilityStructure>,
237    /// The mode in use (`Some(true)`: flexible), fixed at the last key picture.
238    mode: Option<bool>,
239    /// Pictures completed so far, unwrapped.
240    picture_number: u64,
241    /// `picture_number` of the last key picture.
242    key_picture_number: u64,
243    /// The temporal layers of the picture group sent at the last key picture.
244    picture_group_tids: Vec<u8>,
245    /// `TL0PICIDX` of the last picture of temporal layer 0.
246    tl0_pic_idx: u8,
247    /// The picture each reference slot was last refreshed by.
248    slots: [Option<u64>; VP9_REF_SLOTS],
249    /// The spatial layer of the last frame sent of a picture that has not ended.
250    open_picture_sid: Option<u8>,
251    /// [`Payloader::set_next_frame_info`]: the layer information of the next frame
252    /// [`Payloader::payload`] is given.
253    next_frame_info: Option<Vp9FrameInfo>,
254    /// Whether any frame has been sent.
255    started: bool,
256}
257
258impl fmt::Debug for Vp9Payloader {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        f.debug_struct("Vp9Payloader")
261            .field("picture_id", &self.picture_id)
262            .field("initialized", &self.initialized)
263            .field("flexible_mode", &self.flexible_mode)
264            .field("mode", &self.mode)
265            .field("scalability_structure", &self.scalability_structure)
266            .field("tl0_pic_idx", &self.tl0_pic_idx)
267            .finish()
268    }
269}
270
271impl Payloader for Vp9Payloader {
272    /// Payload fragments an Vp9Payloader packet across one or more byte arrays
273    fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
274        /*
275         * https://www.rfc-editor.org/rfc/rfc9628#section-4.2
276         *
277         * Flexible mode (F=1)
278         *        0 1 2 3 4 5 6 7
279         *       +-+-+-+-+-+-+-+-+
280         *       |I|P|L|F|B|E|V|Z| (REQUIRED)
281         *       +-+-+-+-+-+-+-+-+
282         *  I:   |M| PICTURE ID  | (REQUIRED)
283         *       +-+-+-+-+-+-+-+-+
284         *  M:   | EXTENDED PID  | (RECOMMENDED)
285         *       +-+-+-+-+-+-+-+-+
286         *  L:   | tid |U| SID |D| (CONDITIONALLY RECOMMENDED)
287         *       +-+-+-+-+-+-+-+-+                             -\
288         *  P,F: | P_DIFF      |N| (CONDITIONALLY REQUIRED)    - up to 3 times
289         *       +-+-+-+-+-+-+-+-+                             -/
290         *  V:   | SS            |
291         *       | ..            |
292         *       +-+-+-+-+-+-+-+-+
293         *
294         * Non-flexible mode (F=0)
295         *        0 1 2 3 4 5 6 7
296         *       +-+-+-+-+-+-+-+-+
297         *       |I|P|L|F|B|E|V|Z| (REQUIRED)
298         *       +-+-+-+-+-+-+-+-+
299         *  I:   |M| PICTURE ID  | (RECOMMENDED)
300         *       +-+-+-+-+-+-+-+-+
301         *  M:   | EXTENDED PID  | (RECOMMENDED)
302         *       +-+-+-+-+-+-+-+-+
303         *  L:   | tid |U| SID |D| (CONDITIONALLY RECOMMENDED)
304         *       +-+-+-+-+-+-+-+-+
305         *       |   tl0picidx   | (CONDITIONALLY REQUIRED)
306         *       +-+-+-+-+-+-+-+-+
307         *  V:   | SS            |
308         *       | ..            |
309         *       +-+-+-+-+-+-+-+-+
310         */
311        let info = self.next_frame_info.take();
312        self.payload_frame(mtu, payload, info.as_ref())
313    }
314
315    /// RFC 9628 section 4.1: the marker is set on "the final packet of the highest spatial
316    /// layer frame", the picture's last. After a frame that leaves its picture open
317    /// (`end_of_picture` unset) no packet of that frame carries it.
318    fn marker_rule(&self) -> crate::packetizer::MarkerRule {
319        if self.open_picture_sid.is_some() {
320            crate::packetizer::MarkerRule::Never
321        } else {
322            crate::packetizer::MarkerRule::LastPacketOfFrame
323        }
324    }
325
326    fn set_next_frame_info(&mut self, info: &dyn std::any::Any) {
327        if let Some(info) = info.downcast_ref::<Vp9FrameInfo>() {
328            self.next_frame_info = Some(info.clone());
329        }
330    }
331
332    fn clone_to(&self) -> Box<dyn Payloader> {
333        Box::new(self.clone())
334    }
335}
336
337impl Vp9Payloader {
338    /// Sets the scalability structure sent on the first packet of every key picture (RFC 9628
339    /// section 4.2.1), or with `None` goes back to the default: in non-flexible mode one
340    /// spatial layer of the key frame's size and a picture group of one picture, in flexible
341    /// mode no SS.
342    ///
343    /// In non-flexible mode the picture group is what tells a receiver the temporal structure,
344    /// and [`payload_layer_frame`](Self::payload_layer_frame) refuses a frame whose `TID` is
345    /// not the one its picture maps to. It takes effect at the next key picture, the only
346    /// place an SS may change.
347    ///
348    /// # Errors
349    ///
350    /// A structure [`Vp9ScalabilityStructure::validate`] refuses.
351    pub fn set_scalability_structure(
352        &mut self,
353        structure: Option<Vp9ScalabilityStructure>,
354    ) -> Result<()> {
355        if let Some(structure) = &structure {
356            structure.validate()?;
357        }
358        self.scalability_structure = structure;
359        Ok(())
360    }
361
362    /// The picture ID the next picture is sent with (meaningful once a frame has been sent,
363    /// or with `initial_picture_id_fn` set).
364    pub fn picture_id(&self) -> u16 {
365        self.picture_id
366    }
367
368    /// Fragments one VP9 frame of a layered stream, describing it with `info`.
369    ///
370    /// Every packet carries the layer indices (`L`=1). The frames of a picture are passed in
371    /// increasing `spatial_id` order, the last with `end_of_picture`; they share one picture
372    /// ID, and in non-flexible mode one `TL0PICIDX`, incremented for a picture of temporal
373    /// layer 0. The caller sets the RTP marker on the last packet of the frame with
374    /// `end_of_picture` and on no other (RFC 9628 section 4.1).
375    ///
376    /// # Errors
377    ///
378    /// Layer information the descriptor cannot carry or the RFC forbids: `TID` or `SID`
379    /// above 7; `D` on spatial layer 0; a frame that is not inter-picture predicted outside
380    /// temporal layer 0; spatial layers out of order within a picture; more than three
381    /// reference indices, or one outside 1 to 127; in non-flexible mode a `TID` that is not
382    /// the one the picture group gives the picture; an MTU with no room for the descriptor
383    /// (and, on a key picture's first packet, the scalability structure).
384    pub fn payload_layer_frame(
385        &mut self,
386        mtu: usize,
387        frame: &Bytes,
388        info: &Vp9FrameInfo,
389    ) -> Result<Vec<Bytes>> {
390        self.payload_frame(mtu, frame, Some(info))
391    }
392
393    fn payload_frame(
394        &mut self,
395        mtu: usize,
396        frame: &Bytes,
397        info: Option<&Vp9FrameInfo>,
398    ) -> Result<Vec<Bytes>> {
399        let fail = |what: String| Err(Error::Other(format!("VP9 payloader: {what}")));
400        if let Some(info) = info {
401            if info.temporal_id > VP9_MAX_TEMPORAL_ID || info.spatial_id > VP9_MAX_SPATIAL_ID {
402                return fail(format!(
403                    "TID {} / SID {} do not fit three bits",
404                    info.temporal_id, info.spatial_id
405                ));
406            }
407            if info.inter_layer_dependency && info.spatial_id == 0 {
408                return fail("D must be 0 on spatial layer 0".to_owned());
409            }
410            if info.reference_diffs.len() > MAX_VP9REF_PICS
411                || info
412                    .reference_diffs
413                    .iter()
414                    .any(|d| *d == 0 || *d > VP9_MAX_P_DIFF)
415            {
416                return fail("at most three reference indices, each 1 to 127".to_owned());
417            }
418            if let Some(open_sid) = self.open_picture_sid
419                && info.spatial_id <= open_sid
420            {
421                return fail(format!(
422                    "SID {} after SID {open_sid} in one picture",
423                    info.spatial_id
424                ));
425            }
426        }
427
428        if frame.is_empty() || mtu == 0 {
429            return Ok(vec![]);
430        }
431
432        if !self.initialized {
433            if self.initial_picture_id_fn.is_none() {
434                self.initial_picture_id_fn =
435                    Some(Arc::new(|| -> u16 { rand::random::<u16>() & 0x7FFF }));
436            }
437            self.picture_id = if let Some(f) = &self.initial_picture_id_fn {
438                f() & 0x7FFF
439            } else {
440                0
441            };
442            // The first picture of temporal layer 0 increments it to the initial value.
443            self.tl0_pic_idx = self
444                .initial_tl0_pic_idx
445                .unwrap_or_else(rand::random::<u8>)
446                .wrapping_sub(1);
447            self.initialized = true;
448        }
449
450        let header = Vp9FrameHeader::parse(frame);
451        let first_of_picture = self.open_picture_sid.is_none();
452        let spatial_id = info.map_or(0, |i| i.spatial_id);
453        let temporal_id = info.map_or(0, |i| i.temporal_id);
454        let key_frame = info
455            .and_then(|i| i.key_frame)
456            .unwrap_or_else(|| header.is_some_and(|h| h.key_frame));
457        // A key picture: its base spatial layer frame is a key frame (RFC 9628 4.2).
458        let key_picture_start = key_frame && first_of_picture && spatial_id == 0;
459
460        // "The value of the F bit MUST only change on the first packet of a key picture."
461        let flexible = match self.mode {
462            Some(mode) if !key_picture_start => mode,
463            // Nothing is known about the frame (it is not VP9, and the caller did not say what
464            // it is): there is no frame size for an SS, so flexible mode it is.
465            _ => {
466                self.flexible_mode
467                    || (header.is_none() && info.is_none_or(|i| i.key_frame.is_none()))
468            }
469        };
470
471        // P and, for flexible mode, the reference indices.
472        let derived = self.references(header.as_ref(), key_frame);
473        let predicted = info
474            .and_then(|i| i.inter_picture_predicted)
475            .unwrap_or(derived.0);
476        let mut reference_diffs: Vec<u8> = vec![];
477        if predicted && flexible {
478            reference_diffs = match info {
479                Some(info) if !info.reference_diffs.is_empty() => info.reference_diffs.clone(),
480                _ => derived.1,
481            };
482            if reference_diffs.is_empty() {
483                // "At least one reference index MUST be specified"; the previous picture when
484                // the frame does not say.
485                reference_diffs.push(1);
486            }
487        }
488        if !predicted && temporal_id != 0 {
489            // "When P is set to zero, the TID field (if present) MUST also be set to 0."
490            return fail(format!(
491                "a frame without inter-picture prediction has TID {temporal_id}"
492            ));
493        }
494
495        // Non-flexible mode: the picture's TID is the one its place in the picture group has.
496        let picture_group_tids = if key_picture_start {
497            self.key_picture_structure(flexible, header.as_ref())
498                .map(|s| s.picture_group.iter().map(|e| e.temporal_id).collect())
499                .unwrap_or_default()
500        } else {
501            self.picture_group_tids.clone()
502        };
503        if !flexible && info.is_some() && !picture_group_tids.is_empty() {
504            let since_key = if key_picture_start {
505                0
506            } else {
507                self.picture_number.wrapping_sub(self.key_picture_number)
508            };
509            let expected =
510                picture_group_tids[(since_key % picture_group_tids.len() as u64) as usize];
511            if expected != temporal_id {
512                return fail(format!(
513                    "TID {temporal_id} where the picture group has TID {expected}"
514                ));
515            }
516        }
517
518        // The scalability structure goes on the first packet of a key picture.
519        let mut ss = BytesMut::new();
520        if key_picture_start
521            && let Some(structure) = self.key_picture_structure(flexible, header.as_ref())
522        {
523            structure.marshal_to(&mut ss)?;
524        }
525
526        // TL0PICIDX counts the pictures of temporal layer 0.
527        let tl0_pic_idx = if !flexible && info.is_some() && first_of_picture && temporal_id == 0 {
528            self.tl0_pic_idx.wrapping_add(1)
529        } else {
530            self.tl0_pic_idx
531        };
532
533        // The descriptor after its first octet, the same on every packet of the frame.
534        let mut descriptor = BytesMut::with_capacity(8);
535        descriptor.put_u8((self.picture_id >> 8) as u8 | 0x80);
536        descriptor.put_u8((self.picture_id & 0xFF) as u8);
537        let mut b0 = 0x80; // I
538        if predicted {
539            b0 |= 0x40; // P
540        }
541        if flexible {
542            b0 |= 0x10; // F
543        }
544        match info {
545            Some(info) => {
546                b0 |= 0x20; // L
547                let mut layer = (info.temporal_id << 5) | (info.spatial_id << 1);
548                if info.switching_up_point {
549                    layer |= 0x10; // U
550                }
551                if info.inter_layer_dependency {
552                    layer |= 0x01; // D
553                }
554                descriptor.put_u8(layer);
555                if !flexible {
556                    descriptor.put_u8(tl0_pic_idx);
557                }
558                if info.not_reference_for_upper_layers {
559                    b0 |= 0x01; // Z
560                }
561            }
562            // Without layers: one spatial layer, so nothing above depends on the frame. (The
563            // flexible mode of before did not say so, and still does not.)
564            None if !flexible => b0 |= 0x01,
565            None => {}
566        }
567        for (i, diff) in reference_diffs.iter().enumerate() {
568            let more = i + 1 < reference_diffs.len();
569            descriptor.put_u8((diff << 1) | more as u8);
570        }
571
572        let header_size = 1 + descriptor.len();
573        if mtu <= header_size + ss.len() {
574            // No room for a single octet of the frame. Without layer information this has
575            // always meant "no packets"; a caller that describes its frames is told.
576            return match info {
577                Some(_) => fail(format!(
578                    "an MTU of {mtu} has no room for a descriptor of {} octets",
579                    header_size + ss.len()
580                )),
581                None => Ok(vec![]),
582            };
583        }
584
585        let mut payloads = vec![];
586        let mut index = 0;
587        while index < frame.len() {
588            let with_ss = index == 0 && !ss.is_empty();
589            let room = mtu - header_size - if with_ss { ss.len() } else { 0 };
590            let fragment = std::cmp::min(room, frame.len() - index);
591
592            let mut out = BytesMut::with_capacity(mtu.min(header_size + ss.len() + fragment));
593            let mut b = b0;
594            if index == 0 {
595                b |= 0x08; // B
596            }
597            if index + fragment == frame.len() {
598                b |= 0x04; // E
599            }
600            if with_ss {
601                b |= 0x02; // V
602            }
603            out.put_u8(b);
604            out.put(&descriptor[..]);
605            if with_ss {
606                out.put(&ss[..]);
607            }
608            out.put(&frame[index..index + fragment]);
609            payloads.push(out.freeze());
610            index += fragment;
611        }
612
613        // The frame is sent: account for it.
614        self.started = true;
615        self.mode = Some(flexible);
616        self.tl0_pic_idx = tl0_pic_idx;
617        if key_picture_start {
618            self.key_picture_number = self.picture_number;
619            self.picture_group_tids = picture_group_tids;
620        }
621        if key_frame {
622            self.slots = [Some(self.picture_number); VP9_REF_SLOTS];
623        } else if let Some(refresh) = header.and_then(|h| h.refresh_frame_flags) {
624            for (i, slot) in self.slots.iter_mut().enumerate() {
625                if refresh & (1 << i) != 0 {
626                    *slot = Some(self.picture_number);
627                }
628            }
629        }
630        if info.is_none_or(|i| i.end_of_picture) {
631            self.open_picture_sid = None;
632            self.picture_number += 1;
633            self.picture_id = (self.picture_id + 1) & 0x7FFF;
634        } else {
635            self.open_picture_sid = Some(spatial_id);
636        }
637
638        Ok(payloads)
639    }
640
641    /// Whether the frame predicts from another picture (`P`), and which ones (flexible mode's
642    /// `P_DIFF`s), as far as its uncompressed header tells.
643    fn references(&self, header: Option<&Vp9FrameHeader>, key_frame: bool) -> (bool, Vec<u8>) {
644        if key_frame {
645            return (false, vec![]);
646        }
647        let Some(header) = header else {
648            // Not a VP9 frame. Nothing precedes the stream's first frame; any other may
649            // depend on what came before, and must not be offered as a switch point.
650            return (self.started, vec![]);
651        };
652        if header.intra_only {
653            return (false, vec![]);
654        }
655        let slots: Vec<u8> = match (header.show_existing, header.ref_frame_idx) {
656            (Some(slot), _) => vec![slot],
657            (None, Some(refs)) => refs.to_vec(),
658            // An inter frame whose header ends before its reference indices.
659            (None, None) => return (true, vec![]),
660        };
661        let mut diffs: Vec<u8> = vec![];
662        let mut predicted = false;
663        for slot in slots {
664            match self.slots[slot as usize] {
665                // A reference to a frame of this picture is inter-layer prediction (the D
666                // bit), not inter-picture prediction.
667                Some(picture) if picture == self.picture_number => {}
668                Some(picture) => {
669                    predicted = true;
670                    // The furthest a reference index reaches is 127 pictures.
671                    let diff = (self.picture_number - picture).min(VP9_MAX_P_DIFF as u64) as u8;
672                    if !diffs.contains(&diff) {
673                        diffs.push(diff);
674                    }
675                }
676                // A slot nothing sent on this stream has written: an older picture.
677                None => predicted = true,
678            }
679        }
680        (predicted, diffs)
681    }
682
683    /// The SS a key picture starting now carries: the one set, or in non-flexible mode the
684    /// default (one spatial layer of the key frame's size; one picture per group, predicted
685    /// from the picture before).
686    fn key_picture_structure(
687        &self,
688        flexible: bool,
689        header: Option<&Vp9FrameHeader>,
690    ) -> Option<Vp9ScalabilityStructure> {
691        if let Some(structure) = &self.scalability_structure {
692            return Some(structure.clone());
693        }
694        if flexible {
695            return None;
696        }
697        let resolutions = match header.and_then(|h| h.size) {
698            // WIDTH and HEIGHT are 16 bits; a larger frame is announced without them.
699            Some((width, height)) if width <= 0xFFFF && height <= 0xFFFF => {
700                vec![(width as u16, height as u16)]
701            }
702            _ => vec![],
703        };
704        Some(Vp9ScalabilityStructure {
705            spatial_layers: 1,
706            resolutions,
707            picture_group: vec![Vp9PictureGroupEntry {
708                temporal_id: 0,
709                switching_up_point: true,
710                reference_diffs: vec![1],
711            }],
712        })
713    }
714}
715
716/// What the payloader needs from a VP9 frame's uncompressed header (VP9
717/// bitstream specification 6.2).
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
719pub(crate) struct Vp9FrameHeader {
720    /// `frame_type == KEY_FRAME`.
721    pub(crate) key_frame: bool,
722    /// `intra_only`: a frame that is not a key frame and predicts from no other.
723    pub(crate) intra_only: bool,
724    /// `show_existing_frame`: the slot of the frame shown again; there is no new frame.
725    pub(crate) show_existing: Option<u8>,
726    /// A key frame's width and height.
727    pub(crate) size: Option<(u32, u32)>,
728    /// The reference slots the frame is stored in. `None` on a key frame (all of them) and
729    /// when the header ends before the field.
730    pub(crate) refresh_frame_flags: Option<u8>,
731    /// The reference slots an inter frame predicts from. `None` when the header ends before
732    /// them.
733    pub(crate) ref_frame_idx: Option<[u8; 3]>,
734}
735
736/// Reads bits, most significant first.
737struct BitReader<'a> {
738    data: &'a [u8],
739    pos: usize,
740}
741
742impl BitReader<'_> {
743    fn bits(&mut self, n: usize) -> Option<u32> {
744        let mut v = 0u32;
745        for _ in 0..n {
746            let byte = *self.data.get(self.pos / 8)?;
747            v = (v << 1) | ((byte >> (7 - (self.pos % 8))) & 1) as u32;
748            self.pos += 1;
749        }
750        Some(v)
751    }
752}
753
754impl Vp9FrameHeader {
755    /// Parses the header; `None` when the bytes are not a VP9 frame.
756    pub(crate) fn parse(frame: &[u8]) -> Option<Self> {
757        let mut r = BitReader {
758            data: frame,
759            pos: 0,
760        };
761        if r.bits(2)? != 2 {
762            return None; // frame_marker
763        }
764        let low = r.bits(1)?;
765        let high = r.bits(1)?;
766        let profile = (high << 1) | low;
767        if profile == 3 {
768            r.bits(1)?; // reserved_zero
769        }
770        if r.bits(1)? == 1 {
771            // show_existing_frame: a repeat of an earlier frame, no new data.
772            return Some(Self {
773                show_existing: Some(r.bits(3)? as u8),
774                ..Default::default()
775            });
776        }
777        let key_frame = r.bits(1)? == 0;
778        let show_frame = r.bits(1)? == 1;
779        let error_resilient_mode = r.bits(1)? == 1;
780        if key_frame {
781            if r.bits(24)? != 0x49_83_42 {
782                return None; // frame_sync_code
783            }
784            Self::color_config(&mut r, profile)?;
785            let width = r.bits(16)? + 1;
786            let height = r.bits(16)? + 1;
787            return Some(Self {
788                key_frame,
789                size: Some((width, height)),
790                ..Default::default()
791            });
792        }
793
794        // An inter or intra-only frame. Its first octet is all the non-flexible mode needs;
795        // a header that ends early leaves the reference fields unknown.
796        let mut header = Self::default();
797        let rest = (|| -> Option<()> {
798            header.intra_only = !show_frame && r.bits(1)? == 1;
799            if !error_resilient_mode {
800                r.bits(2)?; // reset_frame_context
801            }
802            if header.intra_only {
803                if r.bits(24)? != 0x49_83_42 {
804                    return None; // frame_sync_code
805                }
806                if profile > 0 {
807                    Self::color_config(&mut r, profile)?;
808                }
809                header.refresh_frame_flags = Some(r.bits(8)? as u8);
810            } else {
811                header.refresh_frame_flags = Some(r.bits(8)? as u8);
812                let mut refs = [0u8; 3];
813                for slot in &mut refs {
814                    *slot = r.bits(3)? as u8;
815                    r.bits(1)?; // ref_frame_sign_bias
816                }
817                header.ref_frame_idx = Some(refs);
818            }
819            Some(())
820        })();
821        // A header cut short leaves the reference fields unknown.
822        let _ = rest;
823        Some(header)
824    }
825
826    /// `color_config()` of the uncompressed header.
827    fn color_config(r: &mut BitReader<'_>, profile: u32) -> Option<()> {
828        if profile >= 2 {
829            r.bits(1)?; // ten_or_twelve_bit
830        }
831        let color_space = r.bits(3)?;
832        if color_space != 7 {
833            r.bits(1)?; // color_range
834            if profile == 1 || profile == 3 {
835                r.bits(3)?; // subsampling_x, subsampling_y, reserved_zero
836            }
837        } else if profile == 1 || profile == 3 {
838            r.bits(1)?; // reserved_zero
839        }
840        Some(())
841    }
842}
843
844/// Vp9Packet represents the VP9 header that is stored in the payload of an RTP Packet
845///
846/// Every field describes the packet last given to [`Depacketizer::depacketize`]: a field the
847/// packet did not carry reads 0 / `false` / empty. In particular the scalability structure
848/// fields are those of a packet with `V`=1 only; a consumer that needs the stream's current
849/// structure keeps [`Vp9Packet::scalability_structure`] of the last packet that had one.
850#[derive(PartialEq, Eq, Debug, Default, Clone)]
851pub struct Vp9Packet {
852    /// picture ID is present
853    pub i: bool,
854    /// inter-picture predicted frame.
855    pub p: bool,
856    /// layer indices present
857    pub l: bool,
858    /// flexible mode. Read as `false` when `I` is 0, whatever the bit says (RFC 9628 section
859    /// 4.2: F is ignored without a picture ID).
860    pub f: bool,
861    /// start of frame. beginning of new vp9 frame
862    pub b: bool,
863    /// end of frame
864    pub e: bool,
865    /// scalability structure (SS) present
866    pub v: bool,
867    /// Not a reference frame for upper spatial layers
868    pub z: bool,
869
870    /// Recommended headers
871    /// 7 or 15 bits, picture ID.
872    pub picture_id: u16,
873    /// Whether the picture ID was sent in 15 bits (`M`=1) rather than 7. The width can change
874    /// during a session; reference indices are computed modulo the width in use (RFC 9628
875    /// section 4.2).
876    pub picture_id_15_bits: bool,
877
878    /// Conditionally recommended headers
879    /// Temporal layer ID
880    pub tid: u8,
881    /// Switching up point
882    pub u: bool,
883    /// Spatial layer ID
884    pub sid: u8,
885    /// Inter-layer dependency used
886    pub d: bool,
887
888    /// Conditionally required headers
889    /// Reference index (F=1)
890    pub pdiff: Vec<u8>,
891    /// Temporal layer zero index (F=0)
892    pub tl0picidx: u8,
893
894    /// Scalability structure headers
895    /// N_S + 1 indicates the number of spatial layers present in the VP9 stream
896    pub ns: u8,
897    /// Each spatial layer's frame resolution present
898    pub y: bool,
899    /// PG description present flag.
900    pub g: bool,
901    /// N_G indicates the number of pictures in a Picture Group (PG)
902    pub ng: u8,
903    /// Frame width for each spatial layer.
904    pub width: Vec<u16>,
905    /// Frame height for each spatial layer.
906    pub height: Vec<u16>,
907    /// Temporal layer ID of pictures in a Picture Group
908    pub pgtid: Vec<u8>,
909    /// Switching up point of pictures in a Picture Group
910    pub pgu: Vec<bool>,
911    /// Reference indices of pictures in a Picture Group
912    pub pgpdiff: Vec<Vec<u8>>,
913}
914
915impl Depacketizer for Vp9Packet {
916    /// depacketize parses the passed byte slice and stores the result in the Vp9Packet this method is called upon
917    fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
918        if packet.is_empty() {
919            return Err(Error::ErrShortPacket);
920        }
921
922        // One depacketizer reads a whole stream: nothing of the previous packet's descriptor
923        // is left for this one. (The reference indices used to accumulate across packets, and
924        // a picture group across scalability structures.)
925        *self = Self::default();
926
927        let reader = &mut packet.clone();
928        let b = reader.get_u8();
929
930        self.i = (b & 0x80) != 0;
931        self.p = (b & 0x40) != 0;
932        self.l = (b & 0x20) != 0;
933        // "If the I bit is set to zero, then this bit MUST also be set to zero and ignored by
934        // receivers" (RFC 9628 4.2).
935        self.f = (b & 0x10) != 0 && self.i;
936        self.b = (b & 0x08) != 0;
937        self.e = (b & 0x04) != 0;
938        self.v = (b & 0x02) != 0;
939        self.z = (b & 0x01) != 0;
940
941        let mut payload_index = 1;
942
943        if self.i {
944            payload_index = self.parse_picture_id(reader, payload_index)?;
945        }
946
947        if self.l {
948            payload_index = self.parse_layer_info(reader, payload_index)?;
949        }
950
951        if self.f && self.p {
952            payload_index = self.parse_ref_indices(reader, payload_index)?;
953        }
954
955        if self.v {
956            payload_index = self.parse_ssdata(reader, payload_index)?;
957        }
958
959        Ok(packet.slice(payload_index..))
960    }
961
962    /// is_partition_head checks whether if this is a head of the VP9 partition
963    ///
964    /// A picture starts at a packet with `B`=1 whose frame does not depend on a lower spatial
965    /// layer of the same picture: with `D`=1 the frame it depends on comes first, so a run of
966    /// packets that begins there has lost it.
967    fn is_partition_head(&self, payload: &Bytes) -> bool {
968        let Some(&b) = payload.first() else {
969            return false;
970        };
971        if b & 0x08 == 0 {
972            return false;
973        }
974        if b & 0x20 != 0 {
975            // The layer indices follow the picture ID (one or two octets, when I is set).
976            let mut index = 1;
977            if b & 0x80 != 0 {
978                index += match payload.get(1) {
979                    Some(m) if m & 0x80 != 0 => 2,
980                    _ => 1,
981                };
982            }
983            if payload.get(index).is_some_and(|layer| layer & 0x01 != 0) {
984                return false;
985            }
986        }
987        true
988    }
989
990    fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
991        marker
992    }
993
994    fn has_key_frames(&self) -> bool {
995        true
996    }
997
998    /// The first packet of a picture ([`is_partition_head`](Depacketizer::is_partition_head):
999    /// `B`=1, not dependent on a lower spatial layer) of the base spatial layer whose `P` bit
1000    /// is clear (RFC 9628 section 4.2: "P: Inter-picture predicted frame. When set to zero,
1001    /// the frame does not utilize inter-picture prediction"). An upper spatial layer's frame
1002    /// with `P`=0 (a layer synchronization frame) is not one: the picture's lower layers and
1003    /// the other layers' earlier pictures are still needed.
1004    fn is_key_frame_start(&self, payload: &Bytes) -> bool {
1005        let Some(&b) = payload.first() else {
1006            return false;
1007        };
1008        if b & 0x40 != 0 || !self.is_partition_head(payload) {
1009            return false;
1010        }
1011        if b & 0x20 != 0 {
1012            let mut index = 1;
1013            if b & 0x80 != 0 {
1014                index += match payload.get(1) {
1015                    Some(m) if m & 0x80 != 0 => 2,
1016                    _ => 1,
1017                };
1018            }
1019            // L: |  T  |U|  S  |D|
1020            return payload
1021                .get(index)
1022                .is_some_and(|layer| (layer >> 1) & 0x07 == 0);
1023        }
1024        true
1025    }
1026}
1027
1028impl Vp9Packet {
1029    // Picture ID:
1030    //
1031    //      +-+-+-+-+-+-+-+-+
1032    // I:   |M| PICTURE ID  |   M:0 => picture id is 7 bits.
1033    //      +-+-+-+-+-+-+-+-+   M:1 => picture id is 15 bits.
1034    // M:   | EXTENDED PID  |
1035    //      +-+-+-+-+-+-+-+-+
1036    //
1037    fn parse_picture_id(
1038        &mut self,
1039        reader: &mut dyn Buf,
1040        mut payload_index: usize,
1041    ) -> Result<usize> {
1042        if reader.remaining() == 0 {
1043            return Err(Error::ErrShortPacket);
1044        }
1045        let b = reader.get_u8();
1046        payload_index += 1;
1047        // PID present?
1048        if (b & 0x80) != 0 {
1049            if reader.remaining() == 0 {
1050                return Err(Error::ErrShortPacket);
1051            }
1052            // M == 1, PID is 15bit
1053            self.picture_id = (((b & 0x7f) as u16) << 8) | (reader.get_u8() as u16);
1054            self.picture_id_15_bits = true;
1055            payload_index += 1;
1056        } else {
1057            self.picture_id = (b & 0x7F) as u16;
1058        }
1059
1060        Ok(payload_index)
1061    }
1062
1063    fn parse_layer_info(
1064        &mut self,
1065        reader: &mut dyn Buf,
1066        mut payload_index: usize,
1067    ) -> Result<usize> {
1068        payload_index = self.parse_layer_info_common(reader, payload_index)?;
1069
1070        if self.f {
1071            Ok(payload_index)
1072        } else {
1073            self.parse_layer_info_non_flexible_mode(reader, payload_index)
1074        }
1075    }
1076
1077    // Layer indices (flexible mode):
1078    //
1079    //      +-+-+-+-+-+-+-+-+
1080    // L:   |  T  |U|  S  |D|
1081    //      +-+-+-+-+-+-+-+-+
1082    //
1083    fn parse_layer_info_common(
1084        &mut self,
1085        reader: &mut dyn Buf,
1086        mut payload_index: usize,
1087    ) -> Result<usize> {
1088        if reader.remaining() == 0 {
1089            return Err(Error::ErrShortPacket);
1090        }
1091        let b = reader.get_u8();
1092        payload_index += 1;
1093
1094        self.tid = b >> 5;
1095        self.u = b & 0x10 != 0;
1096        self.sid = (b >> 1) & 0x7;
1097        self.d = b & 0x01 != 0;
1098
1099        // Every value of the three-bit SID is a spatial layer (RFC 9628 4.2).
1100        Ok(payload_index)
1101    }
1102
1103    // Layer indices (non-flexible mode):
1104    //
1105    //      +-+-+-+-+-+-+-+-+
1106    // L:   |  T  |U|  S  |D|
1107    //      +-+-+-+-+-+-+-+-+
1108    //      |   tl0picidx   |
1109    //      +-+-+-+-+-+-+-+-+
1110    //
1111    fn parse_layer_info_non_flexible_mode(
1112        &mut self,
1113        reader: &mut dyn Buf,
1114        mut payload_index: usize,
1115    ) -> Result<usize> {
1116        if reader.remaining() == 0 {
1117            return Err(Error::ErrShortPacket);
1118        }
1119        self.tl0picidx = reader.get_u8();
1120        payload_index += 1;
1121        Ok(payload_index)
1122    }
1123
1124    // Reference indices:
1125    //
1126    //      +-+-+-+-+-+-+-+-+                P=1,F=1: At least one reference index
1127    // P,F: | P_DIFF      |N|  up to 3 times          has to be specified.
1128    //      +-+-+-+-+-+-+-+-+                    N=1: An additional P_DIFF follows
1129    //                                                current P_DIFF.
1130    //
1131    fn parse_ref_indices(
1132        &mut self,
1133        reader: &mut dyn Buf,
1134        mut payload_index: usize,
1135    ) -> Result<usize> {
1136        let mut b = 1u8;
1137        while (b & 0x1) != 0 {
1138            if reader.remaining() == 0 {
1139                return Err(Error::ErrShortPacket);
1140            }
1141            b = reader.get_u8();
1142            payload_index += 1;
1143
1144            // RFC 9628 4.2: up to three reference indices (P_DIFF) per picture; a fourth is
1145            // the error, not the third. (A P_DIFF of 0 is invalid; it is kept as received for
1146            // the consumer to judge.)
1147            self.pdiff.push(b >> 1);
1148            if self.pdiff.len() > MAX_VP9REF_PICS {
1149                return Err(Error::ErrTooManyPDiff);
1150            }
1151        }
1152
1153        Ok(payload_index)
1154    }
1155
1156    // Scalability structure (SS):
1157    //
1158    //      +-+-+-+-+-+-+-+-+
1159    // V:   | N_S |Y|G|-|-|-|
1160    //      +-+-+-+-+-+-+-+-+              -|
1161    // Y:   |     WIDTH     | (OPTIONAL)    .
1162    //      +               +               .
1163    //      |               | (OPTIONAL)    .
1164    //      +-+-+-+-+-+-+-+-+               . N_S + 1 times
1165    //      |     HEIGHT    | (OPTIONAL)    .
1166    //      +               +               .
1167    //      |               | (OPTIONAL)    .
1168    //      +-+-+-+-+-+-+-+-+              -|
1169    // G:   |      N_G      | (OPTIONAL)
1170    //      +-+-+-+-+-+-+-+-+                           -|
1171    // N_G: |  T  |U| R |-|-| (OPTIONAL)                 .
1172    //      +-+-+-+-+-+-+-+-+              -|            . N_G times
1173    //      |    P_DIFF     | (OPTIONAL)    . R times    .
1174    //      +-+-+-+-+-+-+-+-+              -|           -|
1175    //
1176    fn parse_ssdata(&mut self, reader: &mut dyn Buf, mut payload_index: usize) -> Result<usize> {
1177        if reader.remaining() == 0 {
1178            return Err(Error::ErrShortPacket);
1179        }
1180
1181        let b = reader.get_u8();
1182        payload_index += 1;
1183
1184        self.ns = b >> 5;
1185        self.y = b & 0x10 != 0;
1186        // `N_S |Y|G|-|-|-|`: G is bit 3 alone. The three low bits are reserved and must not
1187        // be read as G (RFC 9628 4.2.1).
1188        self.g = b & 0x08 != 0;
1189
1190        let ns = (self.ns + 1) as usize;
1191
1192        if self.y {
1193            if reader.remaining() < 4 * ns {
1194                return Err(Error::ErrShortPacket);
1195            }
1196
1197            self.width = vec![0u16; ns];
1198            self.height = vec![0u16; ns];
1199            for i in 0..ns {
1200                self.width[i] = reader.get_u16();
1201                self.height[i] = reader.get_u16();
1202            }
1203            payload_index += 4 * ns;
1204        }
1205
1206        if self.g {
1207            if reader.remaining() == 0 {
1208                return Err(Error::ErrShortPacket);
1209            }
1210
1211            self.ng = reader.get_u8();
1212            payload_index += 1;
1213        }
1214
1215        for i in 0..self.ng as usize {
1216            if reader.remaining() == 0 {
1217                return Err(Error::ErrShortPacket);
1218            }
1219            let b = reader.get_u8();
1220            payload_index += 1;
1221
1222            self.pgtid.push(b >> 5);
1223            self.pgu.push(b & 0x10 != 0);
1224
1225            let r = ((b >> 2) & 0x3) as usize;
1226            if reader.remaining() < r {
1227                return Err(Error::ErrShortPacket);
1228            }
1229
1230            self.pgpdiff.push(vec![]);
1231            for _ in 0..r {
1232                let b = reader.get_u8();
1233                payload_index += 1;
1234
1235                self.pgpdiff[i].push(b);
1236            }
1237        }
1238
1239        Ok(payload_index)
1240    }
1241
1242    /// The scalability structure this packet carried (`V`=1), if any.
1243    pub fn scalability_structure(&self) -> Option<Vp9ScalabilityStructure> {
1244        if !self.v {
1245            return None;
1246        }
1247        Some(Vp9ScalabilityStructure {
1248            spatial_layers: self.ns + 1,
1249            resolutions: self
1250                .width
1251                .iter()
1252                .copied()
1253                .zip(self.height.iter().copied())
1254                .collect(),
1255            picture_group: (0..self.pgtid.len())
1256                .map(|i| Vp9PictureGroupEntry {
1257                    temporal_id: self.pgtid[i],
1258                    switching_up_point: self.pgu[i],
1259                    reference_diffs: self.pgpdiff[i].clone(),
1260                })
1261                .collect(),
1262        })
1263    }
1264
1265    /// The picture ID of the picture `reference_diff` pictures back (a `P_DIFF` of this
1266    /// packet), computed modulo the width this packet's picture ID was sent in (RFC 9628
1267    /// section 4.2).
1268    pub fn referenced_picture_id(&self, reference_diff: u8) -> u16 {
1269        let mask = if self.picture_id_15_bits {
1270            0x7FFF
1271        } else {
1272            0x7F
1273        };
1274        self.picture_id.wrapping_sub(reference_diff as u16) & mask
1275    }
1276}
1277
1278/// What a [`Vp9LayerFilter`] decided for one packet.
1279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1280pub struct Vp9Forward {
1281    /// Whether to forward the packet.
1282    pub forward: bool,
1283    /// The RTP marker bit to forward it with. When the layers above the selected one are
1284    /// dropped, the picture ends at the selected layer's last packet for this receiver, and
1285    /// the marker moves there (RFC 9628 section 4.1).
1286    pub marker: bool,
1287}
1288
1289/// Decides which packets of a layered VP9 stream to forward for a target spatial and temporal
1290/// layer, from the payload descriptor alone (RFC 9628 sections 4.2 and 9).
1291///
1292/// A middlebox keeps one per receiver and gives it every packet of the stream in order. The
1293/// rules it applies:
1294///
1295/// * a frame above the temporal layer in use is dropped; the temporal layer goes up after a
1296///   forwarded picture that is a switching up point (`U`=1) or starts a key picture, and down
1297///   at once;
1298/// * of the spatial layers below the one in use, a frame is forwarded unless it says no
1299///   higher layer depends on it (`Z`=1);
1300/// * the spatial layer goes up at a frame of the wanted layer that does not predict from an
1301///   earlier picture (`P`=0) and whose lower-layer dependency (`D`), if any, was forwarded,
1302///   in a picture whose frame of the layer in use is such a frame too (a key picture): in any
1303///   other picture the marker has already been given to the layer in use;
1304/// * it goes down as soon as a frame of the lower layer is decodable for this receiver: at
1305///   once when the lower layers were being forwarded (full SVC), at that layer's next `P`=0
1306///   frame otherwise (K-SVC, simulcast in one stream), which the caller asks for with a PLI
1307///   or FIR when [`Vp9LayerFilter::needs_key_frame`] says so.
1308///
1309/// Nothing is forwarded before a frame the receiver can start from (`P`=0 and `D`=0). A
1310/// stream without layer indices (`L`=0) is forwarded whole.
1311#[derive(Debug, Clone, PartialEq, Eq)]
1312pub struct Vp9LayerFilter {
1313    target_sid: u8,
1314    target_tid: u8,
1315    current_sid: u8,
1316    current_tid: u8,
1317    /// Per spatial layer: the receiver was sent every frame of it (within the temporal layers
1318    /// in use) since one it could start from.
1319    decodable: [bool; 8],
1320    /// The picture in progress and the spatial layers of it that were forwarded (a bit mask).
1321    picture: Option<(Option<u16>, u8)>,
1322    /// The marker was forwarded for the picture in progress: nothing more of it can follow.
1323    picture_closed: bool,
1324    /// The frame in progress (its spatial layer) and what was decided for it.
1325    frame: Option<(u8, bool)>,
1326}
1327
1328impl Vp9LayerFilter {
1329    /// A filter that selects spatial layer `target_sid` and the temporal layers up to
1330    /// `target_tid`.
1331    pub fn new(target_sid: u8, target_tid: u8) -> Self {
1332        Self {
1333            target_sid: target_sid.min(VP9_MAX_SPATIAL_ID),
1334            target_tid: target_tid.min(VP9_MAX_TEMPORAL_ID),
1335            current_sid: 0,
1336            current_tid: 0,
1337            decodable: [false; 8],
1338            picture: None,
1339            picture_closed: false,
1340            frame: None,
1341        }
1342    }
1343
1344    /// Changes the target layers. Each takes effect at the next point where the stream allows
1345    /// it (see the type's description).
1346    pub fn set_target(&mut self, target_sid: u8, target_tid: u8) {
1347        self.target_sid = target_sid.min(VP9_MAX_SPATIAL_ID);
1348        self.target_tid = target_tid.min(VP9_MAX_TEMPORAL_ID);
1349        self.current_tid = self.current_tid.min(self.target_tid);
1350    }
1351
1352    /// The target spatial and temporal layer.
1353    pub fn target(&self) -> (u8, u8) {
1354        (self.target_sid, self.target_tid)
1355    }
1356
1357    /// The spatial and temporal layer forwarded at the moment.
1358    pub fn current(&self) -> (u8, u8) {
1359        (self.current_sid, self.current_tid)
1360    }
1361
1362    /// Whether the selection cannot be reached without a frame the receiver can start from:
1363    /// nothing has been forwarded yet, or a lower spatial layer is wanted whose frames were
1364    /// not being forwarded. The caller should request a key frame.
1365    pub fn needs_key_frame(&self) -> bool {
1366        !self.decodable[self.current_sid as usize]
1367            || (self.target_sid < self.current_sid && !self.decodable[self.target_sid as usize])
1368    }
1369
1370    /// Decides for one packet: `descriptor` is its parsed payload descriptor (a [`Vp9Packet`]
1371    /// after [`Depacketizer::depacketize`]) and `marker` its RTP marker bit.
1372    pub fn forward(&mut self, descriptor: &Vp9Packet, marker: bool) -> Vp9Forward {
1373        if !descriptor.l {
1374            // No layer indices: nothing to select on.
1375            return Vp9Forward {
1376                forward: true,
1377                marker,
1378            };
1379        }
1380        let sid = descriptor.sid;
1381        let picture_id = descriptor.i.then_some(descriptor.picture_id);
1382
1383        // A new picture: a new picture ID or, without one, a frame that starts at a spatial
1384        // layer no higher than the last one seen.
1385        let new_picture = match (self.picture, self.frame) {
1386            (Some((id, _)), Some((last_sid, _))) => {
1387                id != picture_id || (picture_id.is_none() && descriptor.b && sid <= last_sid)
1388            }
1389            _ => true,
1390        };
1391        if new_picture {
1392            self.picture = Some((picture_id, 0));
1393            self.picture_closed = false;
1394            self.frame = None;
1395        }
1396
1397        // A decision holds for all packets of a frame.
1398        let decided = match self.frame {
1399            Some((frame_sid, forward)) if frame_sid == sid && !descriptor.b => Some(forward),
1400            _ => None,
1401        };
1402        let forward = decided.unwrap_or_else(|| self.decide(descriptor));
1403        self.frame = Some((sid, forward));
1404
1405        // The picture ends for this receiver at the last packet of the selected spatial layer,
1406        // unless a switch up may still add a frame to it: that takes a picture whose frames
1407        // predict from no earlier one.
1408        let ends_here = forward
1409            && descriptor.e
1410            && sid == self.current_sid
1411            && (self.current_sid >= self.target_sid || descriptor.p);
1412        let marker = forward && (marker || ends_here);
1413        self.picture_closed |= marker;
1414        Vp9Forward { forward, marker }
1415    }
1416
1417    /// Decides for a frame, at its first packet.
1418    fn decide(&mut self, d: &Vp9Packet) -> bool {
1419        let sid = d.sid;
1420        let s = sid as usize;
1421        let forwarded_sids = self.picture.map_or(0, |(_, mask)| mask);
1422        // The frame's dependency on the layer below, in this picture, is met.
1423        let lower_ok = !d.d || (sid > 0 && forwarded_sids & (1 << (sid - 1)) != 0);
1424        let decodable = (!d.p || self.decodable[s]) && lower_ok;
1425
1426        if d.tid > self.current_tid {
1427            // Frames in the temporal layers in use never depend on this one.
1428            return false;
1429        }
1430
1431        let wanted = if sid == self.current_sid {
1432            true
1433        } else if sid < self.current_sid {
1434            // A reference for the layers above, or the layer a switch down is waiting for.
1435            !d.z || sid == self.target_sid
1436        } else {
1437            // A switch up: possible where the frame predicts from no earlier picture, unless
1438            // the receiver was already told the picture is complete.
1439            sid <= self.target_sid && !d.p && !self.picture_closed
1440        };
1441        let forward = wanted && decodable;
1442
1443        if forward {
1444            self.decodable[s] = true;
1445            if let Some((_, mask)) = &mut self.picture {
1446                *mask |= 1 << sid;
1447            }
1448            if sid > self.current_sid || (sid == self.target_sid && sid < self.current_sid) {
1449                // Up at a frame that predicts from no earlier picture; down as soon as the
1450                // lower layer is decodable (the frames above it in this picture are dropped).
1451                self.current_sid = sid;
1452            }
1453            // "Subsequent pictures with temporal-layer ID values higher than T will not
1454            // depend on any picture before the current picture ... with a temporal-layer ID
1455            // value greater than T"; a key picture (it carries the SS) resets every layer.
1456            if d.u || (d.v && !d.p) {
1457                self.current_tid = self.target_tid;
1458            }
1459        } else {
1460            self.decodable[s] = false;
1461        }
1462        forward
1463    }
1464}