Skip to main content

rtci_rtp/codec/av1/
temporal_unit.rs

1//! An AV1 temporal unit split into the data of its spatial layers (AV1 specification 7.5: the
2//! OBUs of a temporal unit's frames carry their layer in the OBU extension header). RFC 9605
3//! section 6.1.3 needs each layer in its own SFrame ciphertext, so a spatially scalable
4//! temporal unit is split before encryption; after decryption the layers' data, lowest first,
5//! is concatenated again.
6
7#[cfg(test)]
8#[path = "temporal_unit_test.rs"]
9mod temporal_unit_test;
10
11use bytes::{Bytes, BytesMut};
12use shared::error::{Error, Result};
13
14use crate::codec::av1::leb128::read_leb128;
15use crate::codec::av1::obu::{
16    OBU_TYPE_SEQUENCE_HEADER, OBU_TYPE_TEMPORAL_DELIMITER, obu_has_extension, obu_has_size,
17    obu_type,
18};
19
20/// The OBUs of one spatial layer of a temporal unit, as they were in the unit.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Av1LayerData {
23    /// `spatial_id` of the layer's OBUs (0 when none has an extension header).
24    pub spatial_id: u8,
25    /// `temporal_id` of the layer's OBUs (0 when none has an extension header).
26    pub temporal_id: u8,
27    /// The OBUs, byte for byte (headers and size fields included).
28    pub data: Bytes,
29}
30
31/// The spatial layers of `temporal_unit` (low overhead bitstream format, AV1 specification
32/// 5.2), lowest first, each with its OBUs unchanged. OBUs without an extension header (the
33/// temporal delimiter, a sequence header, metadata) go with the layer whose OBUs follow them,
34/// those at the end with the last layer. A unit without extension headers is one layer.
35///
36/// # Errors
37///
38/// A header or a size past the end, a temporal delimiter after the first OBU (a second
39/// temporal unit), or a spatial layer that comes after a higher one. An OBU without a size
40/// field runs to the end of the unit.
41pub fn split_temporal_unit(temporal_unit: &Bytes) -> Result<Vec<Av1LayerData>> {
42    let mut layers: Vec<Av1LayerData> = vec![];
43    // The current layer: where its data starts, its spatial and temporal id.
44    let mut current: Option<(usize, u8, u8)> = None;
45    // Where the OBUs of no layer since the current layer's last OBU start.
46    let mut pending: Option<usize> = None;
47    for (offset, header) in obu_spans(temporal_unit)? {
48        if obu_type(header) == OBU_TYPE_TEMPORAL_DELIMITER && offset > 0 {
49            return fail("more than one temporal unit");
50        }
51        if !obu_has_extension(header) {
52            pending.get_or_insert(offset);
53            continue;
54        }
55        let extension = temporal_unit[offset + 1];
56        let (temporal_id, spatial_id) = (extension >> 5, (extension >> 3) & 0b11);
57        match current {
58            None => current = Some((0, spatial_id, temporal_id)),
59            Some((_, current_spatial_id, _)) if current_spatial_id == spatial_id => {}
60            Some((_, current_spatial_id, _)) if current_spatial_id > spatial_id => {
61                return fail("a spatial layer after a higher one");
62            }
63            Some((start, current_spatial_id, current_temporal_id)) => {
64                // The OBUs of no layer just before this one lead it.
65                let boundary = pending.unwrap_or(offset);
66                layers.push(Av1LayerData {
67                    spatial_id: current_spatial_id,
68                    temporal_id: current_temporal_id,
69                    data: temporal_unit.slice(start..boundary),
70                });
71                current = Some((boundary, spatial_id, temporal_id));
72            }
73        }
74        pending = None;
75    }
76    let (start, spatial_id, temporal_id) = current.unwrap_or((0, 0, 0));
77    if start < temporal_unit.len() {
78        layers.push(Av1LayerData {
79            spatial_id,
80            temporal_id,
81            data: temporal_unit.slice(start..),
82        });
83    }
84    Ok(layers)
85}
86
87/// For an "S" mode (spatial layers that do not predict from each other: simulcast in one RTP
88/// stream), puts a copy of the unit's sequence header in front of every layer after the first
89/// that has none, so that a forwarder can keep any one layer and leave it decodable (AV1 RTP
90/// section 6.1: "a sequence header OBU SHOULD be aggregated with each spatial layer"). A unit
91/// without a sequence header (not a key picture) is left as it is.
92///
93/// # Errors
94///
95/// A layer's data that is not OBUs.
96pub fn repeat_sequence_header_per_layer(layers: &mut [Av1LayerData]) -> Result<()> {
97    let mut sequence_header = None;
98    for layer in layers.iter_mut() {
99        let own = sequence_header_of(&layer.data)?;
100        match (&own, &sequence_header) {
101            (Some(_), _) => sequence_header = own,
102            (None, Some(header)) => {
103                let mut data = BytesMut::with_capacity(header.len() + layer.data.len());
104                data.extend_from_slice(header);
105                data.extend_from_slice(&layer.data);
106                layer.data = data.freeze();
107            }
108            (None, None) => {}
109        }
110    }
111    Ok(())
112}
113
114/// The first sequence header OBU of `data`, byte for byte.
115fn sequence_header_of(data: &Bytes) -> Result<Option<Bytes>> {
116    let spans = obu_spans(data)?;
117    Ok(spans
118        .iter()
119        .enumerate()
120        .find(|(_, (_, header))| obu_type(*header) == OBU_TYPE_SEQUENCE_HEADER)
121        .map(|(i, (start, _))| {
122            let end = spans.get(i + 1).map_or(data.len(), |(next, _)| *next);
123            data.slice(*start..end)
124        }))
125}
126
127fn fail<T>(what: &str) -> Result<T> {
128    Err(Error::Other(format!("AV1 temporal unit: {what}")))
129}
130
131/// Where each OBU of `data` starts, with its header byte. An OBU without a size field runs to
132/// the end.
133fn obu_spans(data: &[u8]) -> Result<Vec<(usize, u8)>> {
134    let mut spans = vec![];
135    let mut offset = 0usize;
136    while offset < data.len() {
137        let header = data[offset];
138        let header_size = if obu_has_extension(header) { 2 } else { 1 };
139        if offset + header_size > data.len() {
140            return fail("an OBU header past the end");
141        }
142        let end = if obu_has_size(header) {
143            let (size, leb128_size) = read_leb128(&data[offset + header_size..])
144                .ok_or(Error::ErrPayloadTooSmallForObuPayloadSize)?;
145            let end = offset + header_size + leb128_size + size as usize;
146            if end > data.len() {
147                return fail("an OBU size past the end");
148            }
149            end
150        } else {
151            data.len()
152        };
153        spans.push((offset, header));
154        offset = end;
155    }
156    Ok(spans)
157}