forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb07f07aTahinli3 months ago1061 commits

lib.rs353 lines, 13.1 KiBHistoryRawDownload
1//! AV1 bitstream syntax: OBU framing, the sequence header and the frame header.
2//!
3//! This crate parses what a *stateless* hardware decoder has to be told before
4//! it can decode a frame — everything outside the entropy-coded tile data. That
5//! is the whole of `sequence_header_obu` and `uncompressed_header` plus the tile
6//! group headers, which is exactly the shape of
7//! `VADecPictureParameterBufferAV1` and `VASliceParameterBufferAV1`; the tile
8//! payloads themselves are handed to the driver as bytes, located by
9//! [`Tile::offset`] and [`Tile::size`].
10//!
11//! [`Av1Parser`] holds the state the format spreads across frames: the sequence
12//! header (without which a frame header cannot even be parsed), the eight
13//! reference slots with their sizes, order hints, saved segmentation, loop
14//! filter deltas, global motion and film grain, and the reference update after
15//! each frame (spec 7.20). Feed it every OBU of a stream in order and it answers
16//! with headers whose fields are the spec's, under the spec's names.
17//!
18//! What is deliberately not here: the symbol decoder and everything behind it
19//! (tile data, CDFs), Annex B length-delimited framing (containers hand over the
20//! low-overhead format), the large scale tile mode, and metadata payloads —
21//! [`metadata_type`] names the type and leaves the body to a caller that has a
22//! use for HDR metadata, which is [`ec_core::color`]'s business rather than a
23//! decode submission's.
24//!
25//! Malformed input is an [`Error`], never a panic: truncation is
26//! [`Error::NeedMore`], a rule violation is [`Error::Corrupt`].
27//!
28//! AV1 is covered by the AOMedia Patent License 1.0, which grants what an
29//! independent implementation of the specification needs; this crate is such an
30//! implementation, written from the specification alone.
31
32#![forbid(unsafe_code)]
33#![warn(missing_docs)]
34
35mod frame;
36pub mod obu;
37pub mod sequence;
38mod warp;
39
40use ec_core::{BitReader, Error, Result};
41
42pub use frame::{
43 CdefParams, DeltaParams, FilmGrainParams, FrameHeader, FrameType, InterpolationFilter,
44 LoopFilterParams, LoopRestorationParams, QuantizationParams, ReferenceSlot, RestorationType,
45 SegmentationParams, Tile, TileInfo, TxMode, WarpModel, WarpParams,
46};
47pub use obu::{ObuHeader, ObuType};
48pub use sequence::{
49 ChromaSamplePosition, ColorConfig, DecoderModelInfo, OperatingPoint, SequenceHeader,
50 TimingInfo, metadata_type,
51};
52
53use frame::{FrameState, apply_refresh, apply_show_existing_refresh, parse_tile_group};
54
55/// Reference frame slots in the AV1 decoded frame buffer (spec 3).
56pub const NUM_REF_FRAMES: usize = 8;
57/// References a single inter frame may name: LAST through ALTREF (spec 3).
58pub const REFS_PER_FRAME: usize = 7;
59/// References including intra, which is what the loop filter deltas are indexed by.
60pub const TOTAL_REFS_PER_FRAME: usize = 8;
61/// `PRIMARY_REF_NONE` (spec 3): this frame inherits no probability or filter state.
62pub const PRIMARY_REF_NONE: u8 = 7;
63/// Number of segments a frame can define (spec 3).
64pub const MAX_SEGMENTS: usize = 8;
65/// Number of per-segment features (spec 3).
66pub const SEG_LVL_MAX: usize = 8;
67/// Segment feature: alternate quantizer index (spec 3).
68pub const SEG_LVL_ALT_Q: usize = 0;
69/// Segment feature: alternate loop filter level, luma vertical (spec 3).
70pub const SEG_LVL_ALT_LF_Y_V: usize = 1;
71/// Segment feature: reference frame override (spec 3).
72pub const SEG_LVL_REF_FRAME: usize = 5;
73/// Segment feature: skip (spec 3).
74pub const SEG_LVL_SKIP: usize = 6;
75/// Segment feature: global motion vector (spec 3).
76pub const SEG_LVL_GLOBALMV: usize = 7;
77/// `MAX_TILE_WIDTH` in samples (spec 3).
78pub const MAX_TILE_WIDTH: u32 = 4096;
79/// `MAX_TILE_AREA` in samples (spec 3).
80pub const MAX_TILE_AREA: u32 = 4096 * 2304;
81/// `MAX_TILE_COLS` (spec 3).
82pub const MAX_TILE_COLS: u32 = 64;
83/// `MAX_TILE_ROWS` (spec 3).
84pub const MAX_TILE_ROWS: u32 = 64;
85/// `RESTORATION_TILESIZE_MAX` (spec 3).
86pub const RESTORATION_TILESIZE_MAX: u32 = 256;
87
88/// What an OBU turned out to hold.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum ObuKind {
91 /// `OBU_SEQUENCE_HEADER`.
92 SequenceHeader(Box<SequenceHeader>),
93 /// `OBU_TEMPORAL_DELIMITER`: the start of a temporal unit, no payload.
94 TemporalDelimiter,
95 /// `OBU_FRAME_HEADER`, or `OBU_REDUNDANT_FRAME_HEADER` (whose parse changes
96 /// no state, as the spec requires).
97 FrameHeader(Box<FrameHeader>),
98 /// `OBU_TILE_GROUP`, belonging to the frame header that preceded it.
99 TileGroup(Vec<Tile>),
100 /// `OBU_FRAME`: a frame header and its tile group in one OBU.
101 Frame(Box<FrameHeader>, Vec<Tile>),
102 /// `OBU_METADATA`, with its `metadata_type` (spec 6.7.1).
103 Metadata(u32),
104 /// `OBU_TILE_LIST`, the large scale tile mode this crate does not parse.
105 TileList,
106 /// `OBU_PADDING`.
107 Padding,
108 /// A reserved OBU type, skipped by size.
109 Reserved(u8),
110}
111
112/// One parsed OBU, and where it sat in the buffer.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct ParsedObu {
115 /// The OBU header.
116 pub header: ObuHeader,
117 /// Byte offset of the OBU header from the start of the buffer parsed.
118 pub offset: usize,
119 /// Total bytes the OBU occupies, header and size field included.
120 pub total_size: usize,
121 /// Byte offset of the OBU payload from the start of the buffer parsed.
122 pub payload_offset: usize,
123 /// `obu_size`: payload length in bytes.
124 pub payload_size: usize,
125 /// What the payload held.
126 pub kind: ObuKind,
127}
128
129/// An AV1 OBU parser carrying the state the format spreads across frames.
130#[derive(Debug, Clone, Default)]
131pub struct Av1Parser {
132 sequence: Option<SequenceHeader>,
133 state: FrameState,
134 /// The frame header a following `OBU_TILE_GROUP` belongs to.
135 pending: Option<FrameHeader>,
136}
137
138impl Av1Parser {
139 /// A parser with no sequence header and no reference state.
140 pub fn new() -> Av1Parser {
141 Av1Parser::default()
142 }
143
144 /// The sequence header in force, once one has been parsed.
145 pub fn sequence_header(&self) -> Option<&SequenceHeader> {
146 self.sequence.as_ref()
147 }
148
149 /// The reference slots as they stand, after every frame parsed so far.
150 pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] {
151 &self.state.refs
152 }
153
154 /// Parse every OBU in one temporal unit (or any run of whole OBUs).
155 ///
156 /// Offsets in the result — including [`Tile::offset`] — are relative to the
157 /// start of `data`, so they can be handed to a decoder that submits `data`
158 /// as one buffer.
159 pub fn parse_temporal_unit(&mut self, data: &[u8]) -> Result<Vec<ParsedObu>> {
160 let mut out = Vec::new();
161 let mut pos = 0usize;
162 while pos < data.len() {
163 let obu = self.parse_obu_at(data, pos)?;
164 pos += obu.total_size;
165 out.push(obu);
166 }
167 Ok(out)
168 }
169
170 /// Parse the single OBU that starts at the beginning of `data`.
171 pub fn parse_obu(&mut self, data: &[u8]) -> Result<ParsedObu> {
172 self.parse_obu_at(data, 0)
173 }
174
175 fn parse_obu_at(&mut self, data: &[u8], offset: usize) -> Result<ParsedObu> {
176 let buf = data.get(offset..).ok_or(Error::NeedMore)?;
177 let mut r = BitReader::new(buf);
178 let header = ObuHeader::parse(&mut r)?;
179 let payload_size = if header.has_size_field {
180 obu::read_leb128(&mut r)? as usize
181 } else {
182 buf.len()
183 .checked_sub(1 + usize::from(header.extension_flag))
184 .ok_or(Error::NeedMore)?
185 };
186 let header_bytes = (r.bit_position() / 8) as usize;
187 let payload = buf
188 .get(header_bytes..header_bytes + payload_size)
189 .ok_or(Error::NeedMore)?;
190 let payload_offset = offset + header_bytes;
191
192 // Layer dropping (spec 5.3.1): an OBU outside the selected operating
193 // point is skipped without being parsed.
194 let dropped = self.sequence.as_ref().is_some_and(|seq| {
195 seq.operating_point_idc != 0
196 && header.extension_flag
197 && !matches!(
198 header.obu_type,
199 ObuType::SequenceHeader | ObuType::TemporalDelimiter
200 )
201 && !(((seq.operating_point_idc >> header.temporal_id) & 1 != 0)
202 && ((seq.operating_point_idc >> (header.spatial_id + 8)) & 1 != 0))
203 });
204
205 let kind = if dropped {
206 ObuKind::Reserved(0)
207 } else {
208 self.parse_payload(&header, payload, payload_offset)?
209 };
210
211 Ok(ParsedObu {
212 header,
213 offset,
214 total_size: header_bytes + payload_size,
215 payload_offset,
216 payload_size,
217 kind,
218 })
219 }
220
221 fn parse_payload(
222 &mut self,
223 header: &ObuHeader,
224 payload: &[u8],
225 payload_offset: usize,
226 ) -> Result<ObuKind> {
227 match header.obu_type {
228 ObuType::SequenceHeader => {
229 let seq = SequenceHeader::parse(&mut BitReader::new(payload))?;
230 self.sequence = Some(seq.clone());
231 Ok(ObuKind::SequenceHeader(Box::new(seq)))
232 }
233 ObuType::TemporalDelimiter => Ok(ObuKind::TemporalDelimiter),
234 ObuType::FrameHeader | ObuType::RedundantFrameHeader => {
235 let redundant = header.obu_type == ObuType::RedundantFrameHeader;
236 let h = self.parse_frame_header(payload, header, redundant)?;
237 Ok(ObuKind::FrameHeader(Box::new(h)))
238 }
239 ObuType::TileGroup => {
240 let info = self
241 .pending
242 .as_ref()
243 .map(|h| h.tile_info.clone())
244 .ok_or_else(|| {
245 Error::corrupt("AV1 tile group with no preceding frame header")
246 })?;
247 Ok(ObuKind::TileGroup(parse_tile_group(
248 payload,
249 payload_offset,
250 &info,
251 )?))
252 }
253 ObuType::Frame => {
254 let mut r = BitReader::new(payload);
255 let h = self.parse_frame_header_from(&mut r, header, false)?;
256 r.align_to_byte();
257 let consumed = (r.bit_position() / 8) as usize;
258 let tiles = parse_tile_group(
259 payload.get(consumed..).ok_or(Error::NeedMore)?,
260 payload_offset + consumed,
261 &h.tile_info,
262 )?;
263 Ok(ObuKind::Frame(Box::new(h), tiles))
264 }
265 ObuType::Metadata => Ok(ObuKind::Metadata(metadata_type(payload)?)),
266 ObuType::TileList => Ok(ObuKind::TileList),
267 ObuType::Padding => Ok(ObuKind::Padding),
268 ObuType::Reserved(code) => Ok(ObuKind::Reserved(code)),
269 }
270 }
271
272 fn parse_frame_header(
273 &mut self,
274 payload: &[u8],
275 obu: &ObuHeader,
276 redundant: bool,
277 ) -> Result<FrameHeader> {
278 let mut r = BitReader::new(payload);
279 self.parse_frame_header_from(&mut r, obu, redundant)
280 }
281
282 fn parse_frame_header_from(
283 &mut self,
284 r: &mut BitReader<'_>,
285 obu: &ObuHeader,
286 redundant: bool,
287 ) -> Result<FrameHeader> {
288 let seq = self
289 .sequence
290 .clone()
291 .ok_or_else(|| Error::corrupt("AV1 frame header before any sequence header"))?;
292 // A redundant frame header must leave the decoder exactly as it found
293 // it (spec 5.9.1), so it parses against a scratch copy of the state.
294 let mut scratch;
295 let state = if redundant {
296 scratch = self.state.clone();
297 &mut scratch
298 } else {
299 &mut self.state
300 };
301 let h = frame::parse_uncompressed_header(r, &seq, state, obu.temporal_id, obu.spatial_id)?;
302 if !redundant {
303 if h.show_existing_frame {
304 apply_show_existing_refresh(&mut self.state, &h);
305 } else {
306 apply_refresh(&mut self.state, &h, seq.color_config.bit_depth);
307 }
308 self.pending = Some(h.clone());
309 }
310 Ok(h)
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
319 fn frame_header_without_a_sequence_header_is_corrupt() {
320 let mut p = Av1Parser::new();
321 // OBU_FRAME_HEADER, has_size_field, size 1, one payload byte.
322 let err = p.parse_obu(&[0x1a, 0x01, 0x00]).unwrap_err();
323 assert!(matches!(err, Error::Corrupt { .. }), "{err}");
324 }
325
326 #[test]
327 fn temporal_delimiter_round_trips() {
328 let mut p = Av1Parser::new();
329 let obus = p.parse_temporal_unit(&[0x12, 0x00]).unwrap();
330 assert_eq!(obus.len(), 1);
331 assert_eq!(obus[0].kind, ObuKind::TemporalDelimiter);
332 assert_eq!(obus[0].total_size, 2);
333 }
334
335 #[test]
336 fn truncated_obu_is_need_more() {
337 let mut p = Av1Parser::new();
338 // Claims a 100-byte payload that is not there.
339 assert!(matches!(
340 p.parse_obu(&[0x0a, 0x64, 0x00]),
341 Err(Error::NeedMore)
342 ));
343 }
344
345 #[test]
346 fn tile_group_without_a_frame_header_is_corrupt() {
347 let mut p = Av1Parser::new();
348 assert!(matches!(
349 p.parse_obu(&[0x22, 0x01, 0x00]),
350 Err(Error::Corrupt { .. })
351 ));
352 }
353}