Skip to main content

moq_mux/codec/vp9/
mod.rs

1//! VP9.
2//!
3//! Parses the VP9 uncompressed frame header (VP9 bitstream spec §6.2, §7.2) to
4//! detect key frames and read the dimensions, profile, bit depth, and color
5//! config, and provides an [`Import`] that publishes a raw VP9 bitstream (one
6//! frame per buffer) to a moq broadcast.
7//!
8//! VP9 stores its codec config in a `vpcC` box, so `vpcc` builds that record
9//! for the fMP4 exporter. It's the exact inverse of the `Vp09` import mapping.
10
11mod import;
12
13pub use import::*;
14
15use hang::catalog::VP9;
16
17/// VP9 parsing errors.
18#[derive(Debug, Clone, thiserror::Error)]
19#[non_exhaustive]
20pub enum Error {
21	/// The frame header has an invalid frame marker.
22	#[error("invalid VP9 frame marker")]
23	InvalidFrameMarker,
24
25	/// The frame header has an invalid sync code.
26	#[error("invalid VP9 sync code")]
27	InvalidSyncCode,
28
29	/// The frame ends before its required header fields.
30	#[error("VP9 header truncated")]
31	Truncated,
32
33	/// The frame contains no bytes.
34	#[error("empty VP9 frame")]
35	EmptyFrame,
36}
37
38/// A Result type alias for VP9 parsing.
39pub type Result<T> = std::result::Result<T, Error>;
40
41/// VP9 key-frame sync code (VP9 spec §6.2, `frame_sync_code`).
42const SYNC_CODE: u32 = 0x49_8342;
43
44/// Fields parsed from a VP9 uncompressed frame header.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub(crate) struct FrameHeader {
47	/// True for a key frame (`frame_type == 0`).
48	pub keyframe: bool,
49	/// Encoded `(width, height)` and color config, present only on key frames.
50	pub key: Option<KeyFrame>,
51}
52
53/// The parts of a VP9 key-frame header we surface to the catalog.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) struct KeyFrame {
56	pub width: u32,
57	pub height: u32,
58	pub profile: u8,
59	pub bit_depth: u8,
60	/// `vpcC` chroma subsampling enum (0 = 4:2:0 vertical, 1 = 4:2:0 colocated,
61	/// 2 = 4:2:2, 3 = 4:4:4).
62	pub chroma_subsampling: u8,
63	/// CICP matrix coefficients derived from the VP9 `color_space`.
64	pub matrix_coefficients: u8,
65	pub full_range: bool,
66}
67
68impl FrameHeader {
69	/// Parse the VP9 uncompressed header.
70	///
71	/// Reads only as far as the frame size (the last field we care about);
72	/// everything after it is left untouched.
73	pub fn parse(data: &[u8]) -> Result<Self> {
74		use bitstream_io::BitRead;
75
76		let mut r = bitstream_io::BitReader::endian(data, bitstream_io::BigEndian);
77		let mut read = |bits: u32| r.read_var::<u32>(bits).map_err(|_| Error::Truncated);
78
79		if read(2)? != 0b10 {
80			return Err(Error::InvalidFrameMarker);
81		}
82
83		let profile_low = read(1)?;
84		let profile_high = read(1)?;
85		let profile = ((profile_high << 1) | profile_low) as u8;
86		if profile == 3 {
87			read(1)?; // reserved_zero
88		}
89
90		// show_existing_frame: displays a previously decoded frame, no header follows.
91		if read(1)? == 1 {
92			read(3)?; // frame_to_show_map_idx
93			return Ok(Self {
94				keyframe: false,
95				key: None,
96			});
97		}
98
99		let keyframe = read(1)? == 0; // frame_type: 0 = KEY_FRAME
100		read(2)?; // show_frame, error_resilient_mode
101
102		if !keyframe {
103			return Ok(Self {
104				keyframe: false,
105				key: None,
106			});
107		}
108
109		if read(24)? != SYNC_CODE {
110			return Err(Error::InvalidSyncCode);
111		}
112
113		// color_config (VP9 spec §6.2.2).
114		let bit_depth = if profile >= 2 {
115			if read(1)? == 1 { 12 } else { 10 }
116		} else {
117			8
118		};
119		let color_space = read(3)? as u8;
120
121		const CS_RGB: u8 = 7;
122		let (subsampling_x, subsampling_y, full_range);
123		if color_space != CS_RGB {
124			full_range = read(1)? == 1;
125			if profile == 1 || profile == 3 {
126				subsampling_x = read(1)? == 1;
127				subsampling_y = read(1)? == 1;
128				read(1)?; // reserved_zero
129			} else {
130				// Profiles 0 and 2 are 4:2:0 only.
131				(subsampling_x, subsampling_y) = (true, true);
132			}
133		} else {
134			// CS_RGB is full-range 4:4:4, allowed only with profile 1 or 3.
135			full_range = true;
136			(subsampling_x, subsampling_y) = (false, false);
137			if profile == 1 || profile == 3 {
138				read(1)?; // reserved_zero
139			}
140		}
141
142		// frame_size (VP9 spec §6.2.3): each field is `value - 1`.
143		let width = read(16)? + 1;
144		let height = read(16)? + 1;
145
146		Ok(Self {
147			keyframe: true,
148			key: Some(KeyFrame {
149				width,
150				height,
151				profile,
152				bit_depth,
153				chroma_subsampling: chroma_subsampling(subsampling_x, subsampling_y),
154				matrix_coefficients: matrix_coefficients(color_space),
155				full_range,
156			}),
157		})
158	}
159}
160
161impl KeyFrame {
162	/// Build the catalog VP9 config from a parsed key frame.
163	///
164	/// Color primaries and transfer characteristics aren't recoverable from the
165	/// VP9 `color_space` alone, so they're left unspecified (2), matching what
166	/// remuxers like ffmpeg do. `level` is the minimum that fits the picture
167	/// size (see [`level_for`]).
168	pub fn to_catalog(self) -> VP9 {
169		VP9 {
170			profile: self.profile,
171			level: level_for(self.width, self.height),
172			bit_depth: self.bit_depth,
173			chroma_subsampling: self.chroma_subsampling,
174			color_primaries: 2,
175			transfer_characteristics: 2,
176			matrix_coefficients: self.matrix_coefficients,
177			full_range: self.full_range,
178		}
179	}
180}
181
182/// The neutral colour a VP9 codec string carries, for one read from a key frame or a `vpcC`, whose
183/// every field is explicit. A placeholder codec string must not come through here.
184pub(crate) fn color(vp9: &VP9) -> Option<hang::catalog::Color> {
185	crate::codec::color::cicp(
186		vp9.color_primaries,
187		vp9.transfer_characteristics,
188		vp9.matrix_coefficients,
189		Some(vp9.full_range),
190	)
191}
192
193/// Build a catalog [`VideoConfig`](hang::catalog::VideoConfig) from a VP9 frame,
194/// or `None` if the frame is not a key frame.
195///
196/// Used by the enhanced-RTMP / FLV importer. VP9 carries its config in band (the
197/// uncompressed key-frame header), so unlike H.264/H.265/AV1 there is no
198/// out-of-band record to pass through as `description`; the config is read from
199/// the key frame itself.
200pub(crate) fn config_from_keyframe(data: &[u8]) -> Result<Option<hang::catalog::VideoConfig>> {
201	let Some(key) = FrameHeader::parse(data)?.key else {
202		return Ok(None);
203	};
204	let (width, height) = (key.width, key.height);
205	let vp9 = key.to_catalog();
206	let mut config = hang::catalog::VideoConfig::new(vp9.clone());
207	config.color = color(&vp9);
208	config.coded_width = Some(width);
209	config.coded_height = Some(height);
210	Ok(Some(config))
211}
212
213/// `vpcC` chroma subsampling enum from the VP9 `subsampling_x`/`subsampling_y`
214/// flags. VP9 doesn't signal chroma siting, so 4:2:0 maps to "colocated" (1),
215/// the value encoders conventionally write.
216fn chroma_subsampling(x: bool, y: bool) -> u8 {
217	match (x, y) {
218		(true, true) => 1,   // 4:2:0
219		(true, false) => 2,  // 4:2:2
220		(false, false) => 3, // 4:4:4
221		(false, true) => 0,  // 4:4:0 (rare)
222	}
223}
224
225/// CICP matrix coefficients for a VP9 `color_space` (VP9 spec Table in §7.2.2),
226/// matching ffmpeg's `vp9_colorspaces`. Unknown/reserved map to unspecified (2).
227fn matrix_coefficients(color_space: u8) -> u8 {
228	match color_space {
229		1 => 5, // CS_BT_601  -> BT.470BG
230		2 => 1, // CS_BT_709  -> BT.709
231		3 => 6, // CS_SMPTE_170 -> SMPTE 170M
232		4 => 7, // CS_SMPTE_240 -> SMPTE 240M
233		5 => 9, // CS_BT_2020 -> BT.2020 non-constant luminance
234		7 => 0, // CS_RGB     -> identity
235		_ => 2, // CS_UNKNOWN / CS_RESERVED -> unspecified
236	}
237}
238
239/// The lowest VP9 level whose `MaxLumaPictureSize` fits `width * height` (VP9
240/// spec Annex A). Framerate and bitrate aren't known from the header, so this
241/// is a picture-size lower bound rather than the exact encoded level.
242fn level_for(width: u32, height: u32) -> u8 {
243	let area = width as u64 * height as u64;
244	// (level, MaxLumaPictureSize), ascending.
245	const LEVELS: &[(u8, u64)] = &[
246		(10, 36_864),
247		(11, 73_728),
248		(20, 122_880),
249		(21, 245_760),
250		(30, 552_960),
251		(31, 983_040),
252		(40, 2_228_224),
253		(50, 8_912_896),
254		(60, 35_651_584),
255		(62, 70_254_592),
256	];
257	LEVELS
258		.iter()
259		.find(|(_, max)| area <= *max)
260		.map(|(level, _)| *level)
261		.unwrap_or(62)
262}
263
264/// Build the `vpcC` configuration record for VP9.
265///
266/// The exact inverse of the `Vp09` -> catalog mapping in the fMP4 importer.
267pub(crate) fn vpcc(vp9: &VP9) -> mp4_atom::VpcC {
268	mp4_atom::VpcC {
269		profile: vp9.profile,
270		level: vp9.level,
271		bit_depth: vp9.bit_depth,
272		chroma_subsampling: vp9.chroma_subsampling,
273		video_full_range_flag: vp9.full_range,
274		color_primaries: vp9.color_primaries,
275		transfer_characteristics: vp9.transfer_characteristics,
276		matrix_coefficients: vp9.matrix_coefficients,
277		codec_initialization_data: Vec::new(),
278	}
279}
280
281#[cfg(test)]
282mod tests {
283	use super::*;
284
285	// A real-shape VP9 key frame: profile 0, show_frame, 8-bit, CS_BT_601,
286	// studio range, 4:2:0, 320x240. Bytes after the frame size are irrelevant.
287	const KEYFRAME_320X240: &[u8] = &[0x82, 0x49, 0x83, 0x42, 0x20, 0x13, 0xf0, 0x0e, 0xf0, 0x00];
288
289	#[test]
290	fn parses_keyframe() {
291		let header = FrameHeader::parse(KEYFRAME_320X240).expect("parse key frame");
292		assert!(header.keyframe);
293		let key = header.key.expect("key frame fields");
294		assert_eq!((key.width, key.height), (320, 240));
295		assert_eq!(key.profile, 0);
296		assert_eq!(key.bit_depth, 8);
297		assert_eq!(key.chroma_subsampling, 1); // 4:2:0
298		assert_eq!(key.matrix_coefficients, 5); // CS_BT_601 -> BT.470BG
299		assert!(!key.full_range);
300	}
301
302	#[test]
303	fn dimensions_keep_the_complete_sixteen_bit_plus_one_range() {
304		for (width, height) in [
305			(1u32, 65_536u32),
306			(65_536, 1),
307			(65_535, 65_536),
308			(65_536, 65_535),
309			(65_536, 65_536),
310		] {
311			let mut frame = KEYFRAME_320X240.to_vec();
312			for (start, value) in [(36, width - 1), (52, height - 1)] {
313				for bit in 0..16 {
314					let position = start + bit;
315					let mask = 1 << (7 - position % 8);
316					frame[position / 8] = (frame[position / 8] & !mask) | (((value >> (15 - bit)) & 1) as u8 * mask);
317				}
318			}
319			let config = config_from_keyframe(&frame).unwrap().unwrap();
320			assert_eq!((config.coded_width, config.coded_height), (Some(width), Some(height)));
321		}
322	}
323
324	#[test]
325	fn keyframe_to_catalog() {
326		let key = FrameHeader::parse(KEYFRAME_320X240).unwrap().key.unwrap();
327		let vp9 = key.to_catalog();
328		assert_eq!(vp9.profile, 0);
329		assert_eq!(vp9.bit_depth, 8);
330		assert_eq!(vp9.level, 20); // 320x240 = 76800, above level 1.1's 73728
331		assert_eq!(vp9.color_primaries, 2); // unspecified
332	}
333
334	#[test]
335	fn parses_interframe() {
336		// Non-key frame: marker(10) profile(00) show_existing(0) frame_type(1) ...
337		// 0b10_00_0_1_00 = 0x84.
338		let header = FrameHeader::parse(&[0x84, 0x00, 0x00]).expect("parse interframe");
339		assert!(!header.keyframe);
340		assert!(header.key.is_none());
341	}
342
343	#[test]
344	fn parses_show_existing() {
345		// marker(10) profile(00) show_existing(1) idx(000) = 0b10_00_1_000 = 0x88.
346		let header = FrameHeader::parse(&[0x88]).expect("parse show_existing");
347		assert!(!header.keyframe);
348		assert!(header.key.is_none());
349	}
350
351	#[test]
352	fn rejects_bad_sync() {
353		let mut frame = KEYFRAME_320X240.to_vec();
354		frame[1] = 0x00; // corrupt the sync code
355		assert!(FrameHeader::parse(&frame).is_err());
356	}
357}