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