Skip to main content

hang/catalog/video/
av1.rs

1use serde::{Deserialize, Serialize};
2
3use crate::Error;
4
5/// AV1 codec mimetype.
6///
7/// This struct contains profile, level, tier, bit depth, and color space information
8/// for AV1 video streams. AV1 is a modern codec supporting high efficiency and
9/// advanced features like HDR and wide color gamuts.
10///
11/// Reference: <https://aomediacodec.github.io/av1-isobmff/#codecsparam>
12#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
13pub struct AV1 {
14	/// AV1 profile (0-2, determines feature support)
15	pub profile: u8,
16	/// AV1 level (determines resolution and bitrate constraints)
17	pub level: u8,
18	/// Tier ('M' for Main, 'H' for High)
19	pub tier: char,
20	/// Bit depth (8, 10, or 12 bits per sample)
21	pub bitdepth: u8,
22	/// Whether the stream is monochrome (grayscale)
23	pub mono_chrome: bool,
24	/// Horizontal chroma subsampling
25	pub chroma_subsampling_x: bool,
26	/// Vertical chroma subsampling
27	pub chroma_subsampling_y: bool,
28	/// Chroma sample position
29	pub chroma_sample_position: u8,
30	/// Color primaries specification
31	pub color_primaries: u8,
32	/// Transfer characteristics (gamma curve)
33	pub transfer_characteristics: u8,
34	/// Matrix coefficients for color conversion
35	pub matrix_coefficients: u8,
36	/// Whether video uses full range (true) or limited range (false)
37	pub full_range: bool,
38}
39
40impl AV1 {
41	/// The codec string prefix that identifies AV1.
42	pub const PREFIX: &'static str = "av01";
43}
44
45// av01.<profile>.<level><tier>.<bitDepth>.<monochrome>.<chromaSubsampling>.
46// <colorPrimaries>.<transferCharacteristics>.<matrixCoefficients>.<videoFullRangeFlag>
47impl std::fmt::Display for AV1 {
48	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49		write!(
50			f,
51			"av01.{:01}.{:02}{}.{:02}",
52			self.profile, self.level, self.tier, self.bitdepth
53		)?;
54
55		let short = AV1 {
56			profile: self.profile,
57			level: self.level,
58			tier: self.tier,
59			bitdepth: self.bitdepth,
60			..Default::default()
61		};
62
63		if self == &short {
64			return Ok(());
65		}
66
67		write!(
68			f,
69			".{:01}.{}{}{}.{:02}.{:02}.{:02}.{:01}",
70			u8::from(self.mono_chrome),
71			u8::from(self.chroma_subsampling_x),
72			u8::from(self.chroma_subsampling_y),
73			{ self.chroma_sample_position },
74			self.color_primaries,
75			self.transfer_characteristics,
76			self.matrix_coefficients,
77			u8::from(self.full_range),
78		)
79	}
80}
81
82impl std::str::FromStr for AV1 {
83	type Err = Error;
84
85	fn from_str(s: &str) -> Result<Self, Self::Err> {
86		fn number(field: Option<&str>, width: usize, max: u8) -> Result<u8, Error> {
87			let field = field.filter(|field| field.len() == width).ok_or(Error::InvalidCodec)?;
88			let value = crate::catalog::codec_number(field, 10)?;
89			if value > max {
90				return Err(Error::InvalidCodec);
91			}
92			Ok(value)
93		}
94
95		let mut fields = s.strip_prefix("av01.").ok_or(Error::InvalidCodec)?.split('.');
96		let profile = number(fields.next(), 1, 2)?;
97		let [tens @ b'0'..=b'9', ones @ b'0'..=b'9', tier @ (b'M' | b'H')] =
98			fields.next().ok_or(Error::InvalidCodec)?.as_bytes()
99		else {
100			return Err(Error::InvalidCodec);
101		};
102		let mut av1 = AV1 {
103			profile,
104			level: (tens - b'0') * 10 + (ones - b'0'),
105			tier: char::from(*tier),
106			bitdepth: number(fields.next(), 2, 99)?,
107			..Default::default()
108		};
109
110		let Some(mono) = fields.next() else {
111			return Ok(av1);
112		};
113		av1.mono_chrome = number(Some(mono), 1, 1)? == 1;
114		let [x @ b'0'..=b'1', y @ b'0'..=b'1', position @ b'0'..=b'3'] =
115			fields.next().ok_or(Error::InvalidCodec)?.as_bytes()
116		else {
117			return Err(Error::InvalidCodec);
118		};
119		av1.chroma_subsampling_x = *x == b'1';
120		av1.chroma_subsampling_y = *y == b'1';
121		av1.chroma_sample_position = position - b'0';
122		av1.color_primaries = number(fields.next(), 2, 99)?;
123		av1.transfer_characteristics = number(fields.next(), 2, 99)?;
124		av1.matrix_coefficients = number(fields.next(), 2, 99)?;
125		av1.full_range = number(fields.next(), 1, 1)? == 1;
126		if fields.next().is_some() {
127			return Err(Error::InvalidCodec);
128		}
129
130		Ok(av1)
131	}
132}
133
134impl Default for AV1 {
135	fn default() -> Self {
136		// .0.110.01.01.01.0
137		Self {
138			profile: 0,
139			level: 0,
140			tier: 'M',
141			bitdepth: 8,
142			mono_chrome: false,
143			chroma_subsampling_x: true,
144			chroma_subsampling_y: true,
145			chroma_sample_position: 0,
146			color_primaries: 1,
147			transfer_characteristics: 1,
148			matrix_coefficients: 1,
149			full_range: false,
150		}
151	}
152}
153
154#[cfg(test)]
155mod test {
156	use std::str::FromStr;
157
158	use crate::catalog::{VideoCodec, VideoConfig};
159
160	use super::*;
161
162	#[test]
163	fn test_av1() {
164		let encoded = "av01.0.04M.10.0.112.09.16.09.0";
165		let decoded = AV1 {
166			profile: 0,
167			level: 4,
168			tier: 'M',
169			bitdepth: 10,
170			mono_chrome: false,
171			chroma_subsampling_x: true,
172			chroma_subsampling_y: true,
173			chroma_sample_position: 2,
174			color_primaries: 9,
175			transfer_characteristics: 16,
176			matrix_coefficients: 9,
177			full_range: false,
178		}
179		.into();
180
181		let output = VideoCodec::from_str(encoded).expect("failed to parse");
182		assert_eq!(output, decoded);
183
184		let output = decoded.to_string();
185		assert_eq!(output, encoded);
186	}
187
188	#[test]
189	fn test_av1_short() {
190		let encoded = "av01.0.01M.08";
191		let decoded = AV1 {
192			profile: 0,
193			level: 1,
194			tier: 'M',
195			bitdepth: 8,
196			..Default::default()
197		}
198		.into();
199
200		let output = VideoCodec::from_str(encoded).expect("failed to parse");
201		assert_eq!(output, decoded);
202
203		let output = decoded.to_string();
204		assert_eq!(output, encoded);
205	}
206
207	#[test]
208	fn test_av1_profiles_roundtrip() {
209		for (encoded, profile) in [
210			("av01.0.00M.08", 0),
211			("av01.1.00M.10.0.000.01.01.01.0", 1),
212			("av01.2.00M.12", 2),
213			("av01.2.00M.08.0.100.02.02.02.0", 2),
214			("av01.2.00M.10.0.100.09.16.09.0", 2),
215			("av01.2.00M.12.0.100.09.16.09.0", 2),
216			("av01.2.00M.12.0.000.09.16.09.0", 2),
217		] {
218			let decoded = VideoCodec::from_str(encoded).expect("failed to parse");
219			assert!(matches!(&decoded, VideoCodec::AV1(av1) if av1.profile == profile));
220			assert_eq!(decoded.to_string(), encoded);
221
222			let config = VideoConfig::new(decoded);
223			let json = serde_json::to_string(&config).unwrap();
224			let output: VideoConfig = serde_json::from_str(&json).unwrap();
225			assert_eq!(output, config);
226		}
227	}
228
229	#[test]
230	fn field_boundaries() {
231		for encoded in [
232			"av01.0.04M.08.",
233			"av01.0.04M.08.0.110",
234			"av01.0.04M.08.0.110.01.01.01.0.extra",
235			"av01.0.04M.08.2.110.01.01.01.0",
236			"av01.0.04M.08.0.210.01.01.01.0",
237			"av01.0.04M.08.0.114.01.01.01.0",
238			"av01.0.04M.08.0.110.01.01.01.2",
239			"av01.0.04M.+8",
240			"av01.0.04M.٠٨",
241			"av01.0.04M.08\n",
242			"av01.0.04M.08.0.110.1.01.01.0",
243		] {
244			assert!(AV1::from_str(encoded).is_err(), "{encoded:?}");
245		}
246	}
247
248	#[test]
249	fn test_av1_invalid_profile() {
250		for profile in 3..=9 {
251			assert!(VideoCodec::from_str(&format!("av01.{profile}.00M.08")).is_err());
252		}
253	}
254}