Skip to main content

rtci_rtp/codec/vp9/
superframe.rs

1//! VP9 superframes (VP9 bitstream specification, Annex B): several frames in one chunk, followed
2//! by an index of their sizes. A spatially scalable VP9 encoder writes each picture as one
3//! superframe whose frames are the spatial layers, lowest first; RFC 9605 section 6.1.3 needs
4//! each layer in its own SFrame ciphertext, so the superframe is split before encryption and
5//! joined again after decryption.
6
7#[cfg(test)]
8#[path = "superframe_test.rs"]
9mod superframe_test;
10
11use bytes::{BufMut, Bytes, BytesMut};
12use shared::error::{Error, Result};
13
14/// The most frames a superframe index describes (`frames_in_superframe_minus_1` is 3 bits).
15pub const VP9_MAX_SUPERFRAME_FRAMES: usize = 8;
16
17/// The top three bits of the superframe marker byte (`superframe_marker`, 0b110).
18const SUPERFRAME_MARKER: u8 = 0b1100_0000;
19
20/// The frames of `chunk`: those its superframe index lists, in order, or the chunk itself when
21/// it has no index (Annex B.3: the index is recognised by its marker byte at the end, repeated
22/// at the start of the index). An empty chunk has no frame.
23///
24/// # Errors
25///
26/// An index whose frame sizes do not make up the chunk exactly with the index, or that lists a
27/// frame of size 0.
28pub fn split_superframe(chunk: &Bytes) -> Result<Vec<Bytes>> {
29    let Some(&marker) = chunk.last() else {
30        return Ok(vec![]);
31    };
32    if marker & 0b1110_0000 != SUPERFRAME_MARKER {
33        return Ok(vec![chunk.clone()]);
34    }
35    let bytes_per_size = usize::from((marker >> 3) & 0b11) + 1;
36    let frames = usize::from(marker & 0b111) + 1;
37    let index_size = 2 + bytes_per_size * frames;
38    if chunk.len() < index_size || chunk[chunk.len() - index_size] != marker {
39        // Not an index: the last byte of a frame that happens to look like a marker.
40        return Ok(vec![chunk.clone()]);
41    }
42    let index = &chunk[chunk.len() - index_size + 1..chunk.len() - 1];
43    let mut out = Vec::with_capacity(frames);
44    let mut offset = 0usize;
45    for size in index.chunks_exact(bytes_per_size) {
46        let size = size
47            .iter()
48            .rev()
49            .fold(0usize, |value, &byte| (value << 8) | usize::from(byte));
50        if size == 0 || offset + size > chunk.len() - index_size {
51            return Err(Error::Other(
52                "VP9 superframe: the index does not describe the chunk".to_owned(),
53            ));
54        }
55        out.push(chunk.slice(offset..offset + size));
56        offset += size;
57    }
58    if offset != chunk.len() - index_size {
59        return Err(Error::Other(
60            "VP9 superframe: the frames do not fill the chunk".to_owned(),
61        ));
62    }
63    Ok(out)
64}
65
66/// `frames` as one chunk: a single frame as it is, two to eight frames followed by a superframe
67/// index (with the smallest size field that holds the largest frame). A single frame whose last
68/// byte looks like a superframe marker gets an index of its own, so that it is not taken for a
69/// superframe.
70///
71/// # Errors
72///
73/// No frame, an empty frame, more than eight frames, or a frame of 2^32 bytes or more.
74pub fn join_superframe(frames: &[Bytes]) -> Result<Bytes> {
75    let fail = |what: &str| Err(Error::Other(format!("VP9 superframe: {what}")));
76    match frames {
77        [] => return fail("no frame"),
78        [frame]
79            if frame
80                .last()
81                .is_some_and(|&b| b & 0b1110_0000 != SUPERFRAME_MARKER) =>
82        {
83            return Ok(frame.clone());
84        }
85        _ if frames.len() > VP9_MAX_SUPERFRAME_FRAMES => return fail("at most eight frames"),
86        _ if frames.iter().any(Bytes::is_empty) => return fail("an empty frame"),
87        _ => {}
88    }
89    let largest = frames.iter().map(Bytes::len).max().unwrap_or(0);
90    let Ok(largest) = u32::try_from(largest) else {
91        return fail("a frame of 2^32 bytes or more");
92    };
93    let bytes_per_size = (4 - largest.leading_zeros() as usize / 8).max(1);
94    let marker = SUPERFRAME_MARKER | ((bytes_per_size as u8 - 1) << 3) | (frames.len() as u8 - 1);
95    let mut out = BytesMut::with_capacity(
96        frames.iter().map(Bytes::len).sum::<usize>() + 2 + bytes_per_size * frames.len(),
97    );
98    for frame in frames {
99        out.put_slice(frame);
100    }
101    out.put_u8(marker);
102    for frame in frames {
103        out.put_slice(&(frame.len() as u32).to_le_bytes()[..bytes_per_size]);
104    }
105    out.put_u8(marker);
106    Ok(out.freeze())
107}