Skip to main content

moq_mux/codec/av1/
mod.rs

1//! AV1.
2//!
3//! Maps the AV1CodecConfigurationRecord (av1C) flag bits into the
4//! catalog's AV1 codec struct, and provides an [`Import`] that publishes
5//! raw AV1 bitstreams (OBU-framed) to a moq broadcast.
6//!
7//! The sequence header has no sample aspect. AV1's per-frame
8//! [`render_size`](https://aomediacodec.github.io/av1-spec/#render-size-syntax)
9//! hint can change between frames, so it does not establish a display aspect for the whole rendition.
10
11mod import;
12mod split;
13
14pub use import::*;
15pub use split::*;
16
17use hang::catalog::AV1;
18
19/// AV1 parsing errors.
20#[derive(Debug, Clone, thiserror::Error)]
21#[non_exhaustive]
22pub enum Error {
23	/// The OBU or codec configuration has an incomplete or invalid header.
24	#[error("OBU is too short")]
25	ObuTooShort,
26
27	/// The OBU size exceeds the supported length.
28	#[error("OBU size too large")]
29	ObuSizeTooLarge,
30
31	/// The stream has not supplied its decoder configuration.
32	#[error("not initialized")]
33	NotInitialized,
34
35	/// A frame arrived before the sequence header.
36	#[error("expected sequence header before any frames")]
37	MissingSequenceHeader,
38
39	/// The frame has no timestamp.
40	#[error("missing timestamp")]
41	MissingTimestamp,
42
43	/// The OBU header could not be parsed.
44	#[error("OBU header parse: {0}")]
45	ObuHeaderParse(std::sync::Arc<std::io::Error>),
46}
47
48impl From<std::io::Error> for Error {
49	fn from(err: std::io::Error) -> Self {
50		Error::ObuHeaderParse(std::sync::Arc::new(err))
51	}
52}
53
54/// A result using this module's error type.
55pub type Result<T> = std::result::Result<T, Error>;
56
57/// Whether `data` is an AV1CodecConfigurationRecord (av1C) rather than raw OBUs: it starts with
58/// the `0x81` marker and version, which no OBU header can, since its top bit is forbidden, and
59/// holds at least the fixed 4-byte header.
60pub(crate) fn is_av1c(data: &[u8]) -> bool {
61	data.len() >= 4 && data[0] == 0x81
62}
63
64/// Build a catalog [`VideoConfig`](hang::catalog::VideoConfig) for the `av01`
65/// shape from an AV1CodecConfigurationRecord (av1C).
66///
67/// Used by the enhanced-RTMP / FLV importer, where the av1C arrives out of band
68/// in the sequence-header tag (leading `0x81` marker) and the coded samples are
69/// raw OBU temporal units, so the record passes straight through as the catalog
70/// `description`. Resolution and color live in the inline sequence header, not
71/// the av1C, so `coded_width`/`coded_height` are left unset here.
72pub(crate) fn config_from_av1c(av1c: &[u8]) -> Result<hang::catalog::VideoConfig> {
73	// av1C: byte 0 = marker(1)|version(7) = 0x81, byte 1 = seq_profile(3)|seq_level_idx_0(5),
74	// byte 2 = seq_tier_0|high_bitdepth|twelve_bit|monochrome|subsampling_x|subsampling_y|sample_position(2).
75	if !is_av1c(av1c) {
76		return Err(Error::ObuTooShort);
77	}
78	let high_bitdepth = ((av1c[2] >> 6) & 0x01) == 1;
79	let twelve_bit = ((av1c[2] >> 5) & 0x01) == 1;
80
81	let mut config = hang::catalog::VideoConfig::new(AV1 {
82		profile: (av1c[1] >> 5) & 0x07,
83		level: av1c[1] & 0x1f,
84		tier: if ((av1c[2] >> 7) & 0x01) == 1 { 'H' } else { 'M' },
85		bitdepth: bitdepth(twelve_bit, high_bitdepth),
86		mono_chrome: ((av1c[2] >> 4) & 0x01) == 1,
87		chroma_subsampling_x: ((av1c[2] >> 3) & 0x01) == 1,
88		chroma_subsampling_y: ((av1c[2] >> 2) & 0x01) == 1,
89		chroma_sample_position: av1c[2] & 0x03,
90		..Default::default()
91	});
92	// configOBUs follow the four header bytes, usually with the sequence header.
93	config.color = color(&av1c[4..]);
94	config.description = Some(bytes::Bytes::copy_from_slice(av1c));
95	Ok(config)
96}
97
98/// Map a parsed `mp4_atom::Av1c` (AV1CodecConfigurationRecord) to the
99/// hang catalog's AV1 codec struct.
100///
101/// Fills in profile, level, bit depth, and chroma sampling info. Color/HDR
102/// fields default to unspecified.
103pub(crate) fn av1_from_av1c(av1c: &mp4_atom::Av1c) -> AV1 {
104	AV1 {
105		profile: av1c.seq_profile,
106		level: av1c.seq_level_idx_0,
107		tier: if av1c.seq_tier_0 { 'H' } else { 'M' },
108		bitdepth: bitdepth(av1c.twelve_bit, av1c.high_bitdepth),
109		mono_chrome: av1c.monochrome,
110		chroma_subsampling_x: av1c.chroma_subsampling_x,
111		chroma_subsampling_y: av1c.chroma_subsampling_y,
112		chroma_sample_position: av1c.chroma_sample_position,
113		..Default::default()
114	}
115}
116
117/// Build an `mp4_atom::Av1c` (AV1CodecConfigurationRecord) from the hang
118/// catalog's AV1 codec struct, the inverse of [`av1_from_av1c`].
119///
120/// `config_obus` is left empty: moq-video publishes AV1 with the sequence
121/// header inline in the bitstream (the `.av01` in-band case, analogous to
122/// `hev1`/`avc3`), so the decoder reads it from the keyframe rather than the
123/// out-of-band config record. The catalog's color fields (color primaries,
124/// transfer characteristics, matrix coefficients, full range) have no slot in
125/// av1C; they live in the sequence header OBU instead.
126pub(crate) fn av1c_from_av1(av1: &AV1) -> mp4_atom::Av1c {
127	let (twelve_bit, high_bitdepth) = bitdepth_flags(av1.bitdepth);
128	mp4_atom::Av1c {
129		seq_profile: av1.profile,
130		seq_level_idx_0: av1.level,
131		seq_tier_0: av1.tier == 'H',
132		high_bitdepth,
133		twelve_bit,
134		monochrome: av1.mono_chrome,
135		chroma_subsampling_x: av1.chroma_subsampling_x,
136		chroma_subsampling_y: av1.chroma_subsampling_y,
137		chroma_sample_position: av1.chroma_sample_position,
138		initial_presentation_delay: None,
139		config_obus: Vec::new(),
140	}
141}
142
143/// Bit depth from the (twelve_bit, high_bitdepth) av1C flag pair
144/// (ISO/IEC 14496-15 + av1-isobmff ยง2.3.3).
145///
146/// Computes `8 + 2*high_bitdepth + 2*twelve_bit`.
147pub(crate) fn bitdepth(twelve_bit: bool, high_bitdepth: bool) -> u8 {
148	8 + 2 * u8::from(high_bitdepth) + 2 * u8::from(twelve_bit)
149}
150
151/// The (twelve_bit, high_bitdepth) av1C flag pair for a given bit depth, the
152/// inverse of [`bitdepth`]. 8-bit -> (false, false), 10-bit -> (false, true),
153/// 12-bit -> (true, true).
154pub(crate) fn bitdepth_flags(bitdepth: u8) -> (bool, bool) {
155	(bitdepth >= 12, bitdepth >= 10)
156}
157
158#[cfg(test)]
159mod tests {
160	use super::{av1_from_av1c, av1c_from_av1, bitdepth, bitdepth_flags};
161	use hang::catalog::AV1;
162
163	#[test]
164	fn maps_bitdepth_flags() {
165		assert_eq!(bitdepth(false, false), 8);
166		assert_eq!(bitdepth(false, true), 10);
167		assert_eq!(bitdepth(true, true), 12);
168		// twelve_bit=true with high_bitdepth=false is not a valid combination
169		// per the spec, but the additive formula still gives a defined answer.
170		assert_eq!(bitdepth(true, false), 10);
171	}
172
173	#[test]
174	fn bitdepth_flags_round_trip() {
175		for (depth, flags) in [(8, (false, false)), (10, (false, true)), (12, (true, true))] {
176			assert_eq!(bitdepth_flags(depth), flags);
177			let (twelve_bit, high_bitdepth) = flags;
178			assert_eq!(bitdepth(twelve_bit, high_bitdepth), depth);
179		}
180	}
181
182	#[test]
183	fn av1c_round_trips_catalog_fields() {
184		let av1 = AV1 {
185			profile: 0,
186			level: 8,
187			tier: 'H',
188			bitdepth: 10,
189			mono_chrome: false,
190			chroma_subsampling_x: true,
191			chroma_subsampling_y: true,
192			chroma_sample_position: 2,
193			// Color fields have no av1C slot; they live in the sequence header.
194			..Default::default()
195		};
196
197		let av1c = av1c_from_av1(&av1);
198		assert_eq!(av1c.seq_profile, 0);
199		assert_eq!(av1c.seq_level_idx_0, 8);
200		assert!(av1c.seq_tier_0);
201		assert!(av1c.high_bitdepth);
202		assert!(!av1c.twelve_bit);
203		assert!(av1c.chroma_subsampling_x);
204		assert!(av1c.chroma_subsampling_y);
205		assert_eq!(av1c.chroma_sample_position, 2);
206		assert!(av1c.config_obus.is_empty());
207
208		// The av1C-backed fields survive a round trip back to the catalog.
209		let back = av1_from_av1c(&av1c);
210		assert_eq!(back.profile, av1.profile);
211		assert_eq!(back.level, av1.level);
212		assert_eq!(back.tier, av1.tier);
213		assert_eq!(back.bitdepth, av1.bitdepth);
214		assert_eq!(back.mono_chrome, av1.mono_chrome);
215		assert_eq!(back.chroma_subsampling_x, av1.chroma_subsampling_x);
216		assert_eq!(back.chroma_subsampling_y, av1.chroma_subsampling_y);
217		assert_eq!(back.chroma_sample_position, av1.chroma_sample_position);
218	}
219}