1mod import;
12
13pub use import::*;
14
15use hang::catalog::VP9;
16
17#[derive(Debug, Clone, thiserror::Error)]
19#[non_exhaustive]
20pub enum Error {
21 #[error("invalid VP9 frame marker")]
23 InvalidFrameMarker,
24
25 #[error("invalid VP9 sync code")]
27 InvalidSyncCode,
28
29 #[error("VP9 header truncated")]
31 Truncated,
32
33 #[error("empty VP9 frame")]
35 EmptyFrame,
36}
37
38pub type Result<T> = std::result::Result<T, Error>;
40
41const SYNC_CODE: u32 = 0x49_8342;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub(crate) struct FrameHeader {
47 pub keyframe: bool,
49 pub key: Option<KeyFrame>,
51}
52
53#[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 pub chroma_subsampling: u8,
63 pub matrix_coefficients: u8,
65 pub full_range: bool,
66}
67
68impl FrameHeader {
69 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)?; }
89
90 if read(1)? == 1 {
92 read(3)?; return Ok(Self {
94 keyframe: false,
95 key: None,
96 });
97 }
98
99 let keyframe = read(1)? == 0; read(2)?; 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 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)?; } else {
130 (subsampling_x, subsampling_y) = (true, true);
132 }
133 } else {
134 full_range = true;
136 (subsampling_x, subsampling_y) = (false, false);
137 if profile == 1 || profile == 3 {
138 read(1)?; }
140 }
141
142 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 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
182pub(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
193pub(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
213fn chroma_subsampling(x: bool, y: bool) -> u8 {
217 match (x, y) {
218 (true, true) => 1, (true, false) => 2, (false, false) => 3, (false, true) => 0, }
223}
224
225fn matrix_coefficients(color_space: u8) -> u8 {
228 match color_space {
229 1 => 5, 2 => 1, 3 => 6, 4 => 7, 5 => 9, 7 => 0, _ => 2, }
237}
238
239fn level_for(width: u32, height: u32) -> u8 {
243 let area = width as u64 * height as u64;
244 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
264pub(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 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); assert_eq!(key.matrix_coefficients, 5); 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); assert_eq!(vp9.color_primaries, 2); }
333
334 #[test]
335 fn parses_interframe() {
336 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 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; assert!(FrameHeader::parse(&frame).is_err());
356 }
357}