Skip to main content

oa/video/codec/
av1.rs

1//! Bounded AV1 access-unit and open-bitstream-unit structure.
2
3use crate::{Error, Result};
4
5use crate::video::{Av1Profile, VideoChromaSubsampling, VideoComponentBitDepth};
6
7mod frame_header;
8
9pub use crate::video::types::{Av1AccessUnitInfo, Av1ColorConfig, Av1TimingInfo};
10pub use frame_header::{
11	Av1FrameHeader, Av1FrameType, Av1GlobalMotionType, Av1InterpolationFilter, Av1ReferenceState,
12	Av1RestorationType, Av1TileGroup, Av1TransformMode, parse_av1_frame_header, parse_av1_tile_group,
13};
14
15/// Optional AV1 color-description triplet.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct Av1ColorDescription {
18	pub color_primaries: u8,
19	pub transfer_characteristics: u8,
20	pub matrix_coefficients: u8,
21}
22
23/// AV1 chroma sample position for 4:2:0 streams.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Av1ChromaSamplePosition {
26	Unknown,
27	Vertical,
28	Colocated,
29	Reserved,
30}
31
32impl Av1ChromaSamplePosition {
33	const fn from_raw(value: u32) -> Self {
34		match value {
35			0 => Self::Unknown,
36			1 => Self::Vertical,
37			2 => Self::Colocated,
38			_ => Self::Reserved,
39		}
40	}
41}
42
43/// One AV1 operating point declared by a sequence header.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct Av1OperatingPoint {
46	pub idc: u16,
47	pub level: u8,
48	pub high_tier: bool,
49	pub decoder_model_present: bool,
50	pub initial_display_delay_minus_1: Option<u8>,
51}
52
53/// How a sequence constrains one optional frame coding tool.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum Av1CodingToolChoice {
56	Disabled,
57	Enabled,
58	SelectPerFrame,
59}
60
61/// Parsed AV1 sequence header required by decode-session setup.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct Av1SequenceHeader {
64	pub profile: Av1Profile,
65	pub still_picture: bool,
66	pub reduced_still_picture_header: bool,
67	pub timing: Option<Av1TimingInfo>,
68	pub decoder_model_info_present: bool,
69	pub initial_display_delay_present: bool,
70	pub operating_points: Vec<Av1OperatingPoint>,
71	pub frame_width_bits_minus_1: u8,
72	pub frame_height_bits_minus_1: u8,
73	pub max_frame_width_minus_1: u16,
74	pub max_frame_height_minus_1: u16,
75	pub frame_id_numbers_present: bool,
76	pub delta_frame_id_length_minus_2: u8,
77	pub additional_frame_id_length_minus_1: u8,
78	pub use_128x128_superblock: bool,
79	pub enable_filter_intra: bool,
80	pub enable_intra_edge_filter: bool,
81	pub enable_inter_intra_compound: bool,
82	pub enable_masked_compound: bool,
83	pub enable_warped_motion: bool,
84	pub enable_dual_filter: bool,
85	pub enable_order_hint: bool,
86	pub enable_joint_compound: bool,
87	pub enable_reference_frame_motion_vectors: bool,
88	pub screen_content_tools: Av1CodingToolChoice,
89	pub integer_motion_vectors: Av1CodingToolChoice,
90	pub order_hint_bits: u8,
91	pub enable_superres: bool,
92	pub enable_cdef: bool,
93	pub enable_restoration: bool,
94	pub color: Av1ColorConfig,
95	pub film_grain_params_present: bool,
96}
97
98impl Av1SequenceHeader {
99	/// Return the maximum coded width in luma samples.
100	pub const fn coded_width(&self) -> u32 {
101		self.max_frame_width_minus_1 as u32 + 1
102	}
103
104	/// Return the maximum coded height in luma samples.
105	pub const fn coded_height(&self) -> u32 {
106		self.max_frame_height_minus_1 as u32 + 1
107	}
108}
109
110/// AV1 open-bitstream-unit identity.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum Av1ObuType {
113	SequenceHeader,
114	TemporalDelimiter,
115	FrameHeader,
116	TileGroup,
117	Metadata,
118	Frame,
119	RedundantFrameHeader,
120	TileList,
121	Padding,
122	Reserved(u8),
123}
124
125impl Av1ObuType {
126	const fn from_raw(value: u8) -> Self {
127		match value {
128			1 => Self::SequenceHeader,
129			2 => Self::TemporalDelimiter,
130			3 => Self::FrameHeader,
131			4 => Self::TileGroup,
132			5 => Self::Metadata,
133			6 => Self::Frame,
134			7 => Self::RedundantFrameHeader,
135			8 => Self::TileList,
136			15 => Self::Padding,
137			other => Self::Reserved(other),
138		}
139	}
140}
141
142/// One borrowed AV1 OBU and its exact access-unit byte range.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub struct Av1Obu<'a> {
145	type_: Av1ObuType,
146	header_offset: usize,
147	header_size: usize,
148	payload: &'a [u8],
149}
150
151impl<'a> Av1Obu<'a> {
152	/// Return the OBU type.
153	pub const fn type_(&self) -> Av1ObuType {
154		self.type_
155	}
156
157	/// Return the OBU header byte offset in the parsed payload.
158	pub const fn header_offset(&self) -> usize {
159		self.header_offset
160	}
161
162	/// Return the header, optional extension, and size-field byte count.
163	pub const fn header_size(&self) -> usize {
164		self.header_size
165	}
166
167	/// Borrow the OBU payload without copying.
168	pub const fn payload(&self) -> &'a [u8] {
169		self.payload
170	}
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub(crate) struct Av1Picture {
175	pub sequence: Av1SequenceHeader,
176	pub frame: Av1FrameHeader,
177	pub frame_header_offset: u32,
178	pub tiles: Option<Av1TileGroup>,
179}
180
181#[derive(Clone, Debug, Default)]
182pub(crate) struct Av1Parser {
183	sequence: Option<Av1SequenceHeader>,
184	references: Av1ReferenceState,
185}
186
187impl Av1Parser {
188	pub fn parse_access_unit(&mut self, bytes: &[u8]) -> Result<Vec<Av1Picture>> {
189		let mut next = self.clone();
190		let pictures = next.parse_access_unit_in_place(bytes)?;
191		*self = next;
192		Ok(pictures)
193	}
194
195	fn parse_access_unit_in_place(&mut self, bytes: &[u8]) -> Result<Vec<Av1Picture>> {
196		let mut pictures = Vec::new();
197		let mut pending = None;
198		for obu in parse_av1_obus(bytes)? {
199			match obu.type_() {
200				Av1ObuType::SequenceHeader => {
201					finish_pending_picture(&mut pending, &mut pictures)?;
202					self.sequence = Some(parse_av1_sequence_header(obu.payload())?);
203				}
204				Av1ObuType::Frame | Av1ObuType::FrameHeader => {
205					finish_pending_picture(&mut pending, &mut pictures)?;
206					let sequence = self.sequence.as_ref().ok_or_else(|| {
207						Error::failed_precondition("AV1 picture arrived before a sequence header")
208					})?;
209					let frame = parse_av1_frame_header(obu.payload(), sequence, &self.references)?;
210					let picture = Av1Picture {
211						sequence: sequence.clone(),
212						frame_header_offset: u32::try_from(obu.header_offset())
213							.map_err(|_| Error::out_of_range("AV1 frame-header offset exceeds u32"))?,
214						tiles: None,
215						frame,
216					};
217					self.references.refresh(&picture.frame);
218					if picture.frame.show_existing_frame {
219						pictures
220							.try_reserve(1)
221							.map_err(|_| Error::resource_exhausted("AV1 picture allocation failed"))?;
222						pictures.push(picture);
223					} else if obu.type_() == Av1ObuType::Frame {
224						let mut picture = picture;
225						picture.tiles = Some(parse_av1_tile_group(obu, &picture.frame)?);
226						validate_complete_picture(&picture)?;
227						pictures
228							.try_reserve(1)
229							.map_err(|_| Error::resource_exhausted("AV1 picture allocation failed"))?;
230						pictures.push(picture);
231					} else {
232						pending = Some(picture);
233					}
234				}
235				Av1ObuType::TileGroup => {
236					let picture = pending
237						.as_mut()
238						.ok_or_else(|| Error::data_loss("AV1 tile group has no preceding frame header"))?;
239					let group = parse_av1_tile_group(obu, &picture.frame)?;
240					let tiles = picture.tiles.get_or_insert_with(|| Av1TileGroup {
241						first_tile: 0,
242						tile_offsets: Vec::new(),
243						tile_sizes: Vec::new(),
244					});
245					if usize::from(group.first_tile) != tiles.tile_offsets.len() {
246						return Err(Error::data_loss(
247							"AV1 tile groups are not contiguous in tile order",
248						));
249					}
250					tiles
251						.tile_offsets
252						.try_reserve(group.tile_offsets.len())
253						.map_err(|_| Error::resource_exhausted("AV1 tile allocation failed"))?;
254					tiles
255						.tile_sizes
256						.try_reserve(group.tile_sizes.len())
257						.map_err(|_| Error::resource_exhausted("AV1 tile allocation failed"))?;
258					tiles.tile_offsets.extend(group.tile_offsets);
259					tiles.tile_sizes.extend(group.tile_sizes);
260				}
261				_ => {}
262			}
263		}
264		finish_pending_picture(&mut pending, &mut pictures)?;
265		Ok(pictures)
266	}
267}
268
269fn finish_pending_picture(
270	pending: &mut Option<Av1Picture>,
271	pictures: &mut Vec<Av1Picture>,
272) -> Result<()> {
273	let Some(picture) = pending.take() else {
274		return Ok(());
275	};
276	validate_complete_picture(&picture)?;
277	pictures
278		.try_reserve(1)
279		.map_err(|_| Error::resource_exhausted("AV1 picture allocation failed"))?;
280	pictures.push(picture);
281	Ok(())
282}
283
284fn validate_complete_picture(picture: &Av1Picture) -> Result<()> {
285	if picture.frame.show_existing_frame {
286		if picture.tiles.is_some() {
287			return Err(Error::data_loss(
288				"AV1 show-existing picture unexpectedly carries tiles",
289			));
290		}
291		return Ok(());
292	}
293	let expected = usize::from(picture.frame.tile_columns)
294		.checked_mul(usize::from(picture.frame.tile_rows))
295		.ok_or_else(|| Error::out_of_range("AV1 tile-grid size overflowed"))?;
296	let tiles = picture
297		.tiles
298		.as_ref()
299		.ok_or_else(|| Error::data_loss("coded AV1 picture carries no tile group"))?;
300	if tiles.first_tile != 0
301		|| tiles.tile_offsets.len() != expected
302		|| tiles.tile_sizes.len() != expected
303	{
304		return Err(Error::data_loss(
305			"coded AV1 picture does not contain one complete ordered tile set",
306		));
307	}
308	Ok(())
309}
310
311impl Av1AccessUnitInfo {
312	/// Return the number of coded or show-existing picture headers.
313	pub const fn picture_count(self) -> u32 {
314		self.frames + self.frame_headers
315	}
316}
317
318/// Parse one AV1 sequence-header OBU payload.
319///
320/// Pass [`Av1Obu::payload`] from an OBU whose type is
321/// [`Av1ObuType::SequenceHeader`]. The returned representation is independent
322/// of Vulkan's standard-video C structures and retains the stream metadata
323/// needed to create exact backend profiles and session parameters.
324///
325/// # Errors
326///
327/// Returns an error when the payload is empty or truncated, declares a
328/// reserved profile, carries an invalid frame-ID length, or encodes a chroma
329/// layout outside the AV1 profile rules.
330pub fn parse_av1_sequence_header(payload: &[u8]) -> Result<Av1SequenceHeader> {
331	if payload.is_empty() {
332		return Err(Error::invalid_argument(
333			"AV1 sequence-header payload is empty",
334		));
335	}
336	let mut reader = Av1BitReader::new(payload)?;
337	let profile = match reader.bits(3, "sequence profile")? {
338		0 => Av1Profile::Main,
339		1 => Av1Profile::High,
340		2 => Av1Profile::Professional,
341		_ => {
342			return Err(Error::data_loss(
343				"AV1 sequence header uses a reserved profile",
344			));
345		}
346	};
347	let still_picture = reader.bit("still-picture flag")?;
348	let reduced_still_picture_header = reader.bit("reduced-still-picture flag")?;
349
350	let mut timing = None;
351	let mut decoder_model_info_present = false;
352	let mut buffer_delay_length = 0_u32;
353	let mut initial_display_delay_present = false;
354	let operating_point_count;
355	if reduced_still_picture_header {
356		operating_point_count = 1;
357	} else {
358		if reader.bit("sequence timing-present flag")? {
359			let num_units_in_display_tick = reader.bits(32, "display-tick numerator")?;
360			let time_scale = reader.bits(32, "display-tick time scale")?;
361			let equal_picture_interval = reader.bit("equal-picture-interval flag")?;
362			let num_ticks_per_picture_minus_1 = equal_picture_interval
363				.then(|| reader.uvlc("ticks-per-picture interval"))
364				.transpose()?;
365			timing = Some(Av1TimingInfo {
366				num_units_in_display_tick,
367				time_scale,
368				equal_picture_interval,
369				num_ticks_per_picture_minus_1,
370			});
371			decoder_model_info_present = reader.bit("decoder-model-present flag")?;
372			if decoder_model_info_present {
373				buffer_delay_length = reader
374					.bits(5, "decoder-model buffer-delay length")?
375					.checked_add(1)
376					.ok_or_else(|| Error::data_loss("AV1 buffer-delay length overflowed"))?;
377				reader.skip(32, "decoder-model decoding tick")?;
378				reader.skip(5, "decoder-model removal-time length")?;
379				reader.skip(5, "decoder-model presentation-time length")?;
380			}
381		}
382		initial_display_delay_present = reader.bit("initial-display-delay-present flag")?;
383		operating_point_count = reader
384			.bits(5, "operating-point count")?
385			.checked_add(1)
386			.ok_or_else(|| Error::data_loss("AV1 operating-point count overflowed"))?;
387	}
388
389	let operating_point_capacity = usize::try_from(operating_point_count)
390		.map_err(|_| Error::out_of_range("AV1 operating-point count exceeds usize"))?;
391	let mut operating_points = Vec::new();
392	operating_points
393		.try_reserve_exact(operating_point_capacity)
394		.map_err(|_| Error::resource_exhausted("AV1 operating-point allocation failed"))?;
395	for index in 0..operating_point_count {
396		// In a reduced still-picture header the operating-point IDC is inferred
397		// as zero rather than present in the payload (AV1 section 5.5.1).
398		let idc = if reduced_still_picture_header {
399			0
400		} else {
401			u16::try_from(reader.bits(12, "operating-point IDC")?)
402				.map_err(|_| Error::internal("AV1 operating-point IDC exceeds u16"))?
403		};
404		let level = u8::try_from(reader.bits(5, "operating-point level")?)
405			.map_err(|_| Error::internal("AV1 operating-point level exceeds u8"))?;
406		let high_tier = if level > 7 {
407			reader.bit("operating-point tier")?
408		} else {
409			false
410		};
411		let decoder_model_present = if decoder_model_info_present {
412			reader.bit("operating-point decoder-model flag")?
413		} else {
414			false
415		};
416		if decoder_model_present {
417			reader.skip(buffer_delay_length, "decoder buffer delay")?;
418			reader.skip(buffer_delay_length, "encoder buffer delay")?;
419			reader.skip(1, "low-delay mode flag")?;
420		}
421		let initial_display_delay_minus_1 = if initial_display_delay_present {
422			reader
423				.bit("operating-point initial-display-delay flag")?
424				.then(|| reader.bits(4, "operating-point initial display delay"))
425				.transpose()?
426				.map(|value| {
427					u8::try_from(value).expect("a four-bit AV1 initial display delay always fits in u8")
428				})
429		} else {
430			None
431		};
432		operating_points.push(Av1OperatingPoint {
433			idc,
434			level,
435			high_tier,
436			decoder_model_present,
437			initial_display_delay_minus_1,
438		});
439		if reduced_still_picture_header && index != 0 {
440			return Err(Error::internal(
441				"reduced AV1 sequence header created multiple operating points",
442			));
443		}
444	}
445
446	let frame_width_bits_minus_1 = u8::try_from(reader.bits(4, "frame-width bit count")?)
447		.map_err(|_| Error::internal("AV1 frame-width bit count exceeds u8"))?;
448	let frame_height_bits_minus_1 = u8::try_from(reader.bits(4, "frame-height bit count")?)
449		.map_err(|_| Error::internal("AV1 frame-height bit count exceeds u8"))?;
450	let max_frame_width_minus_1 = u16::try_from(reader.bits(
451		u32::from(frame_width_bits_minus_1) + 1,
452		"maximum frame width",
453	)?)
454	.map_err(|_| Error::internal("AV1 maximum frame width exceeds u16"))?;
455	let max_frame_height_minus_1 = u16::try_from(reader.bits(
456		u32::from(frame_height_bits_minus_1) + 1,
457		"maximum frame height",
458	)?)
459	.map_err(|_| Error::internal("AV1 maximum frame height exceeds u16"))?;
460
461	let frame_id_numbers_present = if reduced_still_picture_header {
462		false
463	} else {
464		reader.bit("frame-ID-numbers-present flag")?
465	};
466	let (delta_frame_id_length_minus_2, additional_frame_id_length_minus_1) =
467		if frame_id_numbers_present {
468			let delta = u8::try_from(reader.bits(4, "delta frame-ID length")?)
469				.map_err(|_| Error::internal("AV1 delta frame-ID length exceeds u8"))?;
470			let additional = u8::try_from(reader.bits(3, "additional frame-ID length")?)
471				.map_err(|_| Error::internal("AV1 additional frame-ID length exceeds u8"))?;
472			if u16::from(delta) + u16::from(additional) + 6 > 16 {
473				return Err(Error::data_loss("AV1 frame-ID length exceeds 16 bits"));
474			}
475			(delta, additional)
476		} else {
477			(0, 0)
478		};
479
480	let use_128x128_superblock = reader.bit("128x128-superblock flag")?;
481	let enable_filter_intra = reader.bit("filter-intra flag")?;
482	let enable_intra_edge_filter = reader.bit("intra-edge-filter flag")?;
483	let (
484		enable_inter_intra_compound,
485		enable_masked_compound,
486		enable_warped_motion,
487		enable_dual_filter,
488		enable_order_hint,
489		enable_joint_compound,
490		enable_reference_frame_motion_vectors,
491		screen_content_tools,
492		integer_motion_vectors,
493		order_hint_bits,
494	) = if reduced_still_picture_header {
495		(
496			false,
497			false,
498			false,
499			false,
500			false,
501			false,
502			false,
503			Av1CodingToolChoice::SelectPerFrame,
504			Av1CodingToolChoice::SelectPerFrame,
505			0,
506		)
507	} else {
508		let enable_inter_intra_compound = reader.bit("inter-intra-compound flag")?;
509		let enable_masked_compound = reader.bit("masked-compound flag")?;
510		let enable_warped_motion = reader.bit("warped-motion flag")?;
511		let enable_dual_filter = reader.bit("dual-filter flag")?;
512		let enable_order_hint = reader.bit("order-hint flag")?;
513		let (enable_joint_compound, enable_reference_frame_motion_vectors) = if enable_order_hint {
514			(
515				reader.bit("joint-compound flag")?,
516				reader.bit("reference-frame-motion-vector flag")?,
517			)
518		} else {
519			(false, false)
520		};
521		let screen_content_tools = read_tool_choice(&mut reader, "screen-content tools")?;
522		let integer_motion_vectors = if screen_content_tools == Av1CodingToolChoice::Disabled {
523			Av1CodingToolChoice::SelectPerFrame
524		} else {
525			read_tool_choice(&mut reader, "integer motion vectors")?
526		};
527		let order_hint_bits = if enable_order_hint {
528			u8::try_from(reader.bits(3, "order-hint bit count")? + 1)
529				.map_err(|_| Error::internal("AV1 order-hint bit count exceeds u8"))?
530		} else {
531			0
532		};
533		(
534			enable_inter_intra_compound,
535			enable_masked_compound,
536			enable_warped_motion,
537			enable_dual_filter,
538			enable_order_hint,
539			enable_joint_compound,
540			enable_reference_frame_motion_vectors,
541			screen_content_tools,
542			integer_motion_vectors,
543			order_hint_bits,
544		)
545	};
546
547	let enable_superres = reader.bit("super-resolution flag")?;
548	let enable_cdef = reader.bit("CDEF flag")?;
549	let enable_restoration = reader.bit("restoration flag")?;
550	let color = parse_color_config(&mut reader, profile)?;
551	let film_grain_params_present = reader.bit("film-grain-present flag")?;
552
553	Ok(Av1SequenceHeader {
554		profile,
555		still_picture,
556		reduced_still_picture_header,
557		timing,
558		decoder_model_info_present,
559		initial_display_delay_present,
560		operating_points,
561		frame_width_bits_minus_1,
562		frame_height_bits_minus_1,
563		max_frame_width_minus_1,
564		max_frame_height_minus_1,
565		frame_id_numbers_present,
566		delta_frame_id_length_minus_2,
567		additional_frame_id_length_minus_1,
568		use_128x128_superblock,
569		enable_filter_intra,
570		enable_intra_edge_filter,
571		enable_inter_intra_compound,
572		enable_masked_compound,
573		enable_warped_motion,
574		enable_dual_filter,
575		enable_order_hint,
576		enable_joint_compound,
577		enable_reference_frame_motion_vectors,
578		screen_content_tools,
579		integer_motion_vectors,
580		order_hint_bits,
581		enable_superres,
582		enable_cdef,
583		enable_restoration,
584		color,
585		film_grain_params_present,
586	})
587}
588
589fn read_tool_choice(reader: &mut Av1BitReader<'_>, name: &str) -> Result<Av1CodingToolChoice> {
590	if reader.bit(&format!("{name} selection flag"))? {
591		Ok(Av1CodingToolChoice::SelectPerFrame)
592	} else if reader.bit(&format!("{name} value"))? {
593		Ok(Av1CodingToolChoice::Enabled)
594	} else {
595		Ok(Av1CodingToolChoice::Disabled)
596	}
597}
598
599fn parse_color_config(
600	reader: &mut Av1BitReader<'_>,
601	profile: Av1Profile,
602) -> Result<Av1ColorConfig> {
603	let high_bit_depth = reader.bit("high-bit-depth flag")?;
604	let bit_depth = if profile == Av1Profile::Professional && high_bit_depth {
605		if reader.bit("twelve-bit flag")? {
606			VideoComponentBitDepth::Twelve
607		} else {
608			VideoComponentBitDepth::Ten
609		}
610	} else if high_bit_depth {
611		VideoComponentBitDepth::Ten
612	} else {
613		VideoComponentBitDepth::Eight
614	};
615	let monochrome = if profile == Av1Profile::High {
616		false
617	} else {
618		reader.bit("monochrome flag")?
619	};
620	let color_description = if reader.bit("color-description-present flag")? {
621		Some(Av1ColorDescription {
622			color_primaries: u8::try_from(reader.bits(8, "color primaries")?)
623				.map_err(|_| Error::internal("AV1 color primaries exceed u8"))?,
624			transfer_characteristics: u8::try_from(reader.bits(8, "transfer characteristics")?)
625				.map_err(|_| Error::internal("AV1 transfer characteristics exceed u8"))?,
626			matrix_coefficients: u8::try_from(reader.bits(8, "matrix coefficients")?)
627				.map_err(|_| Error::internal("AV1 matrix coefficients exceed u8"))?,
628		})
629	} else {
630		None
631	};
632
633	if monochrome {
634		return Ok(Av1ColorConfig {
635			bit_depth,
636			monochrome,
637			color_description,
638			full_range: reader.bit("monochrome color range")?,
639			chroma_subsampling: VideoChromaSubsampling::Monochrome,
640			chroma_sample_position: Av1ChromaSamplePosition::Unknown,
641			separate_uv_delta_q: false,
642		});
643	}
644
645	let identity_rgb = color_description.is_some_and(|color| {
646		color.color_primaries == 1
647			&& color.transfer_characteristics == 13
648			&& color.matrix_coefficients == 0
649	});
650	let (full_range, subsampling_x, subsampling_y) = if identity_rgb {
651		(true, false, false)
652	} else {
653		let full_range = reader.bit("color range")?;
654		let (subsampling_x, subsampling_y) = match (profile, bit_depth) {
655			(Av1Profile::Main, _) => (true, true),
656			(Av1Profile::High, _) => (false, false),
657			(Av1Profile::Professional, VideoComponentBitDepth::Twelve) => {
658				let x = reader.bit("chroma-subsampling-X flag")?;
659				let y = x && reader.bit("chroma-subsampling-Y flag")?;
660				(x, y)
661			}
662			(Av1Profile::Professional, _) => (true, false),
663		};
664		(full_range, subsampling_x, subsampling_y)
665	};
666	let chroma_subsampling = match (subsampling_x, subsampling_y) {
667		(false, false) => VideoChromaSubsampling::Yuv444,
668		(true, false) => VideoChromaSubsampling::Yuv422,
669		(true, true) => VideoChromaSubsampling::Yuv420,
670		(false, true) => {
671			return Err(Error::data_loss(
672				"AV1 sequence header declares invalid chroma subsampling",
673			));
674		}
675	};
676	let chroma_sample_position = if subsampling_x && subsampling_y {
677		Av1ChromaSamplePosition::from_raw(reader.bits(2, "chroma sample position")?)
678	} else {
679		Av1ChromaSamplePosition::Unknown
680	};
681	let separate_uv_delta_q = reader.bit("separate-UV-delta-Q flag")?;
682	Ok(Av1ColorConfig {
683		bit_depth,
684		monochrome,
685		color_description,
686		full_range,
687		chroma_subsampling,
688		chroma_sample_position,
689		separate_uv_delta_q,
690	})
691}
692
693struct Av1BitReader<'a> {
694	data: &'a [u8],
695	bit_offset: usize,
696	bit_len: usize,
697}
698
699impl<'a> Av1BitReader<'a> {
700	fn new(data: &'a [u8]) -> Result<Self> {
701		let bit_len = data
702			.len()
703			.checked_mul(8)
704			.ok_or_else(|| Error::out_of_range("AV1 payload bit length overflowed"))?;
705		Ok(Self {
706			data,
707			bit_offset: 0,
708			bit_len,
709		})
710	}
711
712	fn bit(&mut self, field: &str) -> Result<bool> {
713		Ok(self.bits(1, field)? != 0)
714	}
715
716	fn bits(&mut self, count: u32, field: &str) -> Result<u32> {
717		if count > 32 {
718			return Err(Error::internal("AV1 bit reader request exceeds 32 bits"));
719		}
720		let count =
721			usize::try_from(count).map_err(|_| Error::out_of_range("AV1 bit count exceeds usize"))?;
722		let end = self
723			.bit_offset
724			.checked_add(count)
725			.ok_or_else(|| Error::out_of_range("AV1 bit-reader offset overflowed"))?;
726		if end > self.bit_len {
727			return Err(Error::data_loss(format!("truncated AV1 {field}")));
728		}
729		let mut value = 0_u32;
730		while self.bit_offset < end {
731			let byte = self.data[self.bit_offset >> 3];
732			value = (value << 1) | u32::from((byte >> (7 - (self.bit_offset & 7))) & 1);
733			self.bit_offset += 1;
734		}
735		Ok(value)
736	}
737
738	fn skip(&mut self, mut count: u32, field: &str) -> Result<()> {
739		while count > 0 {
740			let chunk = count.min(32);
741			self.bits(chunk, field)?;
742			count -= chunk;
743		}
744		Ok(())
745	}
746
747	fn uvlc(&mut self, field: &str) -> Result<u32> {
748		let mut leading_zeros = 0_u32;
749		while leading_zeros < 32 {
750			if self.bit(field)? {
751				let suffix = if leading_zeros == 0 {
752					0
753				} else {
754					self.bits(leading_zeros, field)?
755				};
756				return Ok(((1_u32 << leading_zeros) - 1) + suffix);
757			}
758			leading_zeros += 1;
759		}
760		Ok(u32::MAX)
761	}
762
763	/// Decode one `ns(n)` symbol, a uniformly distributed value in
764	/// `0..maximum`, per the AV1 `ns` descriptor.
765	fn uniform(&mut self, maximum: u32, field: &str) -> Result<u32> {
766		if maximum < 2 {
767			return Err(Error::invalid_argument("AV1 uniform range must exceed one"));
768		}
769		let length = 32 - maximum.leading_zeros();
770		let mask = (1_u32 << length) - maximum;
771		let value = self.bits(length - 1, field)?;
772		if value < mask {
773			Ok(value)
774		} else {
775			let adjusted = value
776				.checked_mul(2)
777				.and_then(|doubled| doubled.checked_sub(mask))
778				.ok_or_else(|| Error::out_of_range("AV1 uniform decode overflowed"))?;
779			adjusted
780				.checked_add(u32::from(self.bit(field)?))
781				.ok_or_else(|| Error::out_of_range("AV1 uniform decode overflowed"))
782		}
783	}
784
785	fn byte_align(&mut self) -> Result<()> {
786		let aligned = self
787			.bit_offset
788			.checked_add(7)
789			.ok_or_else(|| Error::out_of_range("AV1 byte-alignment offset overflowed"))?
790			& !7;
791		if aligned > self.bit_len {
792			return Err(Error::data_loss("truncated AV1 byte alignment"));
793		}
794		self.bit_offset = aligned;
795		Ok(())
796	}
797
798	const fn byte_offset(&self) -> usize {
799		self.bit_offset.div_ceil(8)
800	}
801}
802
803/// Split one raw AV1 access-unit payload into borrowed OBUs.
804///
805/// # Errors
806///
807/// Returns an error for forbidden/reserved header bits, truncated extensions
808/// or LEB128 sizes, payload overruns, empty input, and arithmetic overflow.
809pub fn parse_av1_obus(bytes: &[u8]) -> Result<Vec<Av1Obu<'_>>> {
810	let mut offset = 0_usize;
811	let mut obus = Vec::new();
812	while offset < bytes.len() {
813		let header_offset = offset;
814		let header = bytes[offset];
815		offset += 1;
816		if header & 0x81 != 0 {
817			return Err(Error::data_loss(
818				"invalid AV1 OBU forbidden or reserved bit",
819			));
820		}
821		let type_ = Av1ObuType::from_raw((header >> 3) & 0x0f);
822		if header & 0x04 != 0 {
823			offset = offset
824				.checked_add(1)
825				.ok_or_else(|| Error::out_of_range("AV1 OBU extension offset overflowed"))?;
826			if offset > bytes.len() {
827				return Err(Error::data_loss("truncated AV1 OBU extension header"));
828			}
829		}
830		let payload_size = if header & 0x02 != 0 {
831			read_leb128(bytes, &mut offset)?
832		} else {
833			u64::try_from(bytes.len() - offset)
834				.map_err(|_| Error::out_of_range("AV1 OBU payload size exceeds u64"))?
835		};
836		let payload_size = usize::try_from(payload_size)
837			.map_err(|_| Error::out_of_range("AV1 OBU payload size exceeds usize"))?;
838		let payload_end = offset
839			.checked_add(payload_size)
840			.ok_or_else(|| Error::out_of_range("AV1 OBU payload range overflowed"))?;
841		let payload = bytes
842			.get(offset..payload_end)
843			.ok_or_else(|| Error::data_loss("AV1 OBU payload exceeds access unit"))?;
844		obus
845			.try_reserve(1)
846			.map_err(|_| Error::resource_exhausted("AV1 OBU inventory allocation failed"))?;
847		obus.push(Av1Obu {
848			type_,
849			header_offset,
850			header_size: offset - header_offset,
851			payload,
852		});
853		offset = payload_end;
854	}
855	if obus.is_empty() {
856		return Err(Error::invalid_argument("AV1 access unit contains no OBUs"));
857	}
858	Ok(obus)
859}
860
861/// Inspect one raw access unit or the first frame of an IVF byte stream.
862///
863/// # Errors
864///
865/// Returns an error for malformed IVF framing, invalid OBU structure, count
866/// overflow, or an empty frame payload.
867pub fn inspect_av1_access_unit(bytes: &[u8]) -> Result<Av1AccessUnitInfo> {
868	let (payload, ivf_timestamp) = av1_frame_payload(bytes)?;
869	let mut info = Av1AccessUnitInfo {
870		ivf_timestamp,
871		..Av1AccessUnitInfo::default()
872	};
873	for obu in parse_av1_obus(payload)? {
874		let count = match obu.type_ {
875			Av1ObuType::SequenceHeader => &mut info.sequence_headers,
876			Av1ObuType::Frame => &mut info.frames,
877			Av1ObuType::FrameHeader => &mut info.frame_headers,
878			Av1ObuType::TileGroup => &mut info.tile_groups,
879			_ => continue,
880		};
881		*count = count
882			.checked_add(1)
883			.ok_or_else(|| Error::resource_exhausted("AV1 OBU count overflowed"))?;
884	}
885	Ok(info)
886}
887
888fn av1_frame_payload(bytes: &[u8]) -> Result<(&[u8], Option<u64>)> {
889	if bytes.len() >= 44 && bytes.get(..4) == Some(b"DKIF") && bytes.get(8..12) == Some(b"AV01") {
890		let header_size = usize::from(u16::from_le_bytes([bytes[6], bytes[7]]));
891		if header_size < 32 {
892			return Err(Error::data_loss("AV1 IVF header is shorter than 32 bytes"));
893		}
894		let frame_header_end = header_size
895			.checked_add(12)
896			.ok_or_else(|| Error::out_of_range("AV1 IVF frame-header range overflowed"))?;
897		let frame_header = bytes
898			.get(header_size..frame_header_end)
899			.ok_or_else(|| Error::data_loss("truncated AV1 IVF frame header"))?;
900		let frame_size = usize::try_from(u32::from_le_bytes([
901			frame_header[0],
902			frame_header[1],
903			frame_header[2],
904			frame_header[3],
905		]))
906		.map_err(|_| Error::out_of_range("AV1 IVF frame size exceeds usize"))?;
907		if frame_size == 0 {
908			return Err(Error::data_loss("AV1 IVF frame payload is empty"));
909		}
910		let timestamp = u64::from_le_bytes(
911			frame_header[4..12]
912				.try_into()
913				.map_err(|_| Error::internal("AV1 IVF timestamp slice has wrong length"))?,
914		);
915		let payload_end = frame_header_end
916			.checked_add(frame_size)
917			.ok_or_else(|| Error::out_of_range("AV1 IVF frame payload range overflowed"))?;
918		let payload = bytes
919			.get(frame_header_end..payload_end)
920			.ok_or_else(|| Error::data_loss("AV1 IVF frame payload exceeds input"))?;
921		return Ok((payload, Some(timestamp)));
922	}
923	if bytes.is_empty() {
924		return Err(Error::invalid_argument("AV1 access unit is empty"));
925	}
926	Ok((bytes, None))
927}
928
929fn read_leb128(bytes: &[u8], offset: &mut usize) -> Result<u64> {
930	let mut value = 0_u64;
931	for shift in (0..56).step_by(7) {
932		let byte = *bytes
933			.get(*offset)
934			.ok_or_else(|| Error::data_loss("truncated AV1 OBU LEB128 size"))?;
935		*offset = offset
936			.checked_add(1)
937			.ok_or_else(|| Error::out_of_range("AV1 OBU size-field offset overflowed"))?;
938		value |= u64::from(byte & 0x7f) << shift;
939		if byte & 0x80 == 0 {
940			return Ok(value);
941		}
942	}
943	Err(Error::data_loss("AV1 OBU LEB128 size exceeds eight bytes"))
944}