1mod export;
11mod import;
12mod split;
13mod sps;
14
15pub use export::*;
16pub use import::*;
17pub use split::*;
18pub use sps::{Sps, VideoSignal};
19
20use bytes::{Buf, Bytes, BytesMut};
21
22use crate::codec::annexb::{InBandCodec, ParameterSets};
23pub(crate) use sps::id as sps_id;
24
25pub(crate) fn hvc1_frame(
33 data: impl moq_net::IntoBytes,
34 length_size: usize,
35 pts: moq_net::Timestamp,
36) -> crate::Result<crate::container::Frame> {
37 let keyframe = hvc1_is_keyframe(data.as_ref(), length_size);
38 Ok(crate::container::Frame {
39 timestamp: pts,
40 decode: None,
41 payload: data.into_bytes(),
42 keyframe,
43 duration: None,
44 })
45}
46
47fn hvc1_is_keyframe(data: &[u8], length_size: usize) -> bool {
49 let Ok(nals) = crate::codec::annexb::length_prefixed_nals(data, length_size) else {
50 return false;
51 };
52 nals.map_while(std::result::Result::ok)
53 .any(|nal| nal.first().is_some_and(|header| NalType::of(*header).is_irap()))
54}
55
56pub(crate) fn hvc1_is_radl(data: &[u8], length_size: usize) -> bool {
59 let Ok(nals) = crate::codec::annexb::length_prefixed_nals(data, length_size) else {
60 return false;
61 };
62 let mut slices = (nals.map_while(std::result::Result::ok))
64 .filter_map(|nal| nal.first().map(|header| (header >> 1) & 0x3f))
65 .filter(|kind| *kind < 32)
66 .peekable();
67 slices.peek().is_some() && slices.all(|kind| matches!(kind, 6 | 7))
68}
69
70pub(crate) fn layer_id(nal: &[u8]) -> Option<u8> {
73 match nal {
74 [first, second, ..] => Some(((first & 0x01) << 5) | (second >> 3)),
75 _ => None,
76 }
77}
78
79pub(crate) fn is_base_layer(nal: &[u8]) -> bool {
82 layer_id(nal) == Some(0)
83}
84
85pub(crate) fn base_sps<'a, T: AsRef<[u8]> + ?Sized + 'a>(
88 sps: impl IntoIterator<Item = &'a T>,
89) -> Result<Option<&'a T>> {
90 let mut any = false;
91 for nal in sps {
92 if is_base_layer(nal.as_ref()) {
93 return Ok(Some(nal));
94 }
95 any = true;
96 }
97 match any {
98 true => Err(Error::NoBaseLayerSps),
99 false => Ok(None),
100 }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub(crate) struct NalType(pub u8);
106
107impl NalType {
108 pub const VPS: Self = Self(32);
109 pub const SPS: Self = Self(33);
110 pub const PPS: Self = Self(34);
111 pub const AUD: Self = Self(35);
112 pub const PREFIX_SEI: Self = Self(39);
113 pub const SUFFIX_SEI: Self = Self(40);
114
115 pub fn of(header: u8) -> Self {
117 Self((header >> 1) & 0x3f)
118 }
119
120 pub fn is_irap(self) -> bool {
124 (16..=21).contains(&self.0)
125 }
126}
127
128#[derive(Debug, Clone, thiserror::Error)]
130#[non_exhaustive]
131pub enum Error {
132 #[error("NAL unit is too short")]
134 NalTooShort,
135
136 #[error("{0} too large for hvcC length field ({1} > {max})", max = u16::MAX)]
138 NalTooLargeForHvcc(&'static str, usize),
139
140 #[error("too many {0} for hvcC ({1} > {max})", max = u16::MAX)]
142 TooManyNals(&'static str, usize),
143
144 #[error("NAL too large for 4-byte length prefix")]
146 NalTooLarge,
147
148 #[error("failed to parse SPS NAL unit")]
150 SpsParse,
151
152 #[error("missing level_idc in SPS")]
154 MissingLevelIdc,
155
156 #[error("forbidden zero bit is not zero")]
158 ForbiddenZeroBit,
159
160 #[error("not initialized")]
162 NotInitialized,
163
164 #[error("expected SPS before any frames")]
166 MissingSps,
167
168 #[error("missing timestamp")]
170 MissingTimestamp,
171
172 #[error("HEVCDecoderConfigurationRecord too short")]
174 HvccTooShort,
175
176 #[error("HEVCDecoderConfigurationRecord truncated")]
178 HvccTruncated,
179
180 #[error("hvc1 description for rendition {name:?} is missing VPS, SPS, or PPS (vps={vps}, sps={sps}, pps={pps})")]
182 MissingParamSets {
183 name: String,
185 vps: usize,
187 sps: usize,
189 pps: usize,
191 },
192
193 #[error("annexb: {0}")]
195 Annexb(#[from] crate::codec::annexb::Error),
196
197 #[error("no base-layer SPS: every SPS has nuh_layer_id > 0")]
199 NoBaseLayerSps,
200}
201
202pub type Result<T> = std::result::Result<T, Error>;
204
205#[derive(Debug, Clone)]
208#[non_exhaustive]
209pub struct Hvcc {
210 pub length_size: usize,
212 pub vps: Vec<Bytes>,
214 pub sps: Vec<Bytes>,
216 pub pps: Vec<Bytes>,
218}
219
220impl Hvcc {
221 pub fn parse(hvcc: &[u8]) -> Result<Self> {
224 let record = decode_hvcc(hvcc)?;
225
226 let mut vps = Vec::new();
227 let mut sps = Vec::new();
228 let mut pps = Vec::new();
229 for array in record.arrays {
230 let list = match NalType(array.nal_unit_type) {
231 NalType::VPS => &mut vps,
232 NalType::SPS => &mut sps,
233 NalType::PPS => &mut pps,
234 _ => continue,
235 };
236 list.extend(array.nalus.into_iter().map(Bytes::from));
237 }
238
239 Ok(Self {
240 length_size: usize::from(record.length_size_minus_one) + 1,
241 vps,
242 sps,
243 pps,
244 })
245 }
246}
247
248pub(crate) fn config_from_hvcc(hvcc: &[u8]) -> Result<hang::catalog::VideoConfig> {
257 let params = Hvcc::parse(hvcc)?;
258 let sps_nal = base_sps(¶ms.sps)?.ok_or(Error::MissingSps)?;
259 let mut config = config_from_sps(sps_nal, false)?;
260 config.description = Some(Bytes::copy_from_slice(hvcc));
261 Ok(config)
262}
263
264pub(crate) fn apply_hvcc_sps(hvcc: &mp4_atom::Hvcc, config: &mut hang::catalog::VideoConfig) -> Result<()> {
269 let sps = hvcc
270 .arrays
271 .iter()
272 .filter(|array| NalType(array.nal_unit_type) == NalType::SPS)
273 .flat_map(|array| &array.nalus);
274 let Some(sps) = base_sps(sps)? else {
275 return Ok(());
276 };
277 let metadata = config_from_sps(sps, false)?;
278 config.framerate = metadata.framerate;
279 config.display_aspect_width = metadata.display_aspect_width;
280 config.display_aspect_height = metadata.display_aspect_height;
281 config.color = metadata.color;
282 config.reorder = metadata.reorder;
283 Ok(())
284}
285
286pub(crate) fn config_from_sps(sps_nal: &[u8], in_band: bool) -> Result<hang::catalog::VideoConfig> {
288 let sps = Sps::parse_or_head(sps_nal)?;
289 let color = sps.color();
290 let Sps { head, tail } = sps;
291 let mut config = hang::catalog::VideoConfig::new(hang::catalog::H265 {
292 in_band,
293 profile_space: head.profile_space,
294 profile_idc: head.profile_idc,
295 profile_compatibility_flags: head.profile_compatibility_flags,
296 tier_flag: head.tier_flag,
297 level_idc: head.level_idc,
298 constraint_flags: head.constraint_flags,
299 });
300 config.coded_width = Some(head.width);
301 config.coded_height = Some(head.height);
302 let vui = tail.as_ref().map(|tail| &tail.vui);
303 config.framerate = vui
304 .and_then(sps::Vui::period)
305 .map(|(units, scale)| scale as f64 / units as f64);
306 let display_aspect = vui
307 .and_then(|vui| vui.sample_aspect)
308 .and_then(|sample| crate::codec::video::display_aspect(head.width, head.height, sample));
309 config.display_aspect_width = display_aspect.map(|(width, _)| width);
310 config.display_aspect_height = display_aspect.map(|(_, height)| height);
311 config.color = color;
312 config.reorder = tail
313 .and_then(|tail| u8::try_from(tail.max_num_reorder_pics).ok())
314 .filter(|depth| u32::from(*depth) <= crate::codec::video::max_reorder(&config));
315 Ok(config)
316}
317
318pub(crate) fn sps_size(nal: &[u8]) -> Option<(u32, u32)> {
321 let head = Sps::parse_or_head(nal).ok()?.head;
322 Some((head.width, head.height))
323}
324
325pub(crate) fn sps_reorder(nal: &[u8]) -> Option<crate::codec::video::Reorder> {
331 let tail = Sps::parse(nal).ok()?.tail?;
332 Some(crate::codec::video::Reorder {
333 depth: tail.max_num_reorder_pics,
334 period: tail.vui.period(),
335 })
336}
337
338pub(crate) fn sps_hrd(nal: &[u8]) -> Option<crate::codec::video::Hrd> {
341 Sps::parse(nal).ok()?.tail?.vui.timing?.hrd?.schedule
342}
343
344pub struct Hvc1 {
352 hvcc: Option<Bytes>,
353 vps: ParameterSets,
355 sps: ParameterSets,
357 pps: ParameterSets,
359}
360
361impl Default for Hvc1 {
362 fn default() -> Self {
363 Self::new()
364 }
365}
366
367impl Hvc1 {
368 pub fn new() -> Self {
370 Self {
371 hvcc: None,
372 vps: ParameterSets::new(),
373 sps: ParameterSets::new(),
374 pps: ParameterSets::new(),
375 }
376 }
377
378 pub fn hvcc(&self) -> Option<&Bytes> {
380 self.hvcc.as_ref()
381 }
382
383 pub fn transform(&mut self, payload: Bytes) -> Result<Option<Bytes>> {
391 let mut buf = payload.clone();
392 let mut nal_iter = crate::codec::annexb::NalIterator::new(&mut buf);
393
394 let mut out = BytesMut::with_capacity(payload.remaining());
395 let mut frame_vps = ParameterSets::new();
396 let mut frame_sps = ParameterSets::new();
397 let mut frame_pps = ParameterSets::new();
398 let mut emitted_any_slice = false;
399
400 loop {
401 let nal = match nal_iter.next() {
402 Some(Ok(n)) => n,
403 Some(Err(e)) => return Err(e.into()),
404 None => break,
405 };
406 if process_nal(&nal, &mut out, &mut frame_vps, &mut frame_sps, &mut frame_pps)? {
407 emitted_any_slice = true;
408 }
409 }
410
411 if let Some(nal) = nal_iter.flush()?
412 && process_nal(&nal, &mut out, &mut frame_vps, &mut frame_sps, &mut frame_pps)?
413 {
414 emitted_any_slice = true;
415 }
416
417 let mut changed = false;
422 for (active, frame) in [
423 (&mut self.vps, frame_vps),
424 (&mut self.sps, frame_sps),
425 (&mut self.pps, frame_pps),
426 ] {
427 let before = active.clone();
428 crate::codec::annexb::adopt_parameter_sets(active, frame);
429 changed |= *active != before;
430 }
431 if changed {
432 self.rebuild_hvcc()?;
433 }
434
435 if !emitted_any_slice {
436 return Ok(None);
437 }
438
439 Ok(Some(out.freeze()))
440 }
441
442 fn rebuild_hvcc(&mut self) -> Result<()> {
443 if self.vps.is_empty() || self.sps.is_empty() || self.pps.is_empty() {
444 return Ok(());
445 }
446 let [vps, sps, pps] = [&self.vps, &self.sps, &self.pps].map(|sets| sets.values().cloned().collect::<Vec<_>>());
447 self.hvcc = Some(build_hvcc(&vps, &sps, &pps)?);
448 Ok(())
449 }
450}
451
452fn process_nal(
456 nal: &Bytes,
457 out: &mut BytesMut,
458 frame_vps: &mut ParameterSets,
459 frame_sps: &mut ParameterSets,
460 frame_pps: &mut ParameterSets,
461) -> Result<bool> {
462 if nal.is_empty() {
463 return Ok(false);
464 }
465 match NalType::of(nal[0]) {
467 NalType::VPS => {
468 InBandCodec::H265.insert_parameter_set(frame_vps, nal)?;
469 Ok(false)
470 }
471 NalType::SPS => {
472 InBandCodec::H265.insert_parameter_set(frame_sps, nal)?;
473 Ok(false)
474 }
475 NalType::PPS => {
476 InBandCodec::H265.insert_parameter_set(frame_pps, nal)?;
477 Ok(false)
478 }
479 _ => {
480 let len = u32::try_from(nal.len()).map_err(|_| Error::NalTooLarge)?;
481 out.extend_from_slice(&len.to_be_bytes());
482 out.extend_from_slice(nal);
483 Ok(true)
484 }
485 }
486}
487
488pub(crate) fn build_hvcc(vps_nals: &[Bytes], sps_nals: &[Bytes], pps_nals: &[Bytes]) -> Result<Bytes> {
493 let first_sps = base_sps(sps_nals)?.ok_or(Error::MissingSps)?;
494 for (label, nals) in [("VPS", vps_nals), ("SPS", sps_nals), ("PPS", pps_nals)] {
496 if nals.len() > u16::MAX as usize {
497 return Err(Error::TooManyNals(label, nals.len()));
498 }
499 for nal in nals {
500 if nal.len() > u16::MAX as usize {
501 return Err(Error::NalTooLargeForHvcc(label, nal.len()));
502 }
503 }
504 }
505
506 let sps = Sps::parse_or_head(first_sps)?.head;
507 let arrays = [
508 (NalType::VPS, vps_nals),
509 (NalType::SPS, sps_nals),
510 (NalType::PPS, pps_nals),
511 ]
512 .into_iter()
513 .map(|(nal_type, nals)| mp4_atom::HvcCArray {
514 completeness: true,
515 nal_unit_type: nal_type.0,
516 nalus: nals.iter().map(|nal| nal.to_vec()).collect(),
517 })
518 .collect();
519
520 Ok(encode_hvcc(&mp4_atom::Hvcc {
521 configuration_version: 1,
522 general_profile_space: sps.profile_space,
523 general_tier_flag: sps.tier_flag,
524 general_profile_idc: sps.profile_idc,
525 general_profile_compatibility_flags: sps.profile_compatibility_flags,
526 general_constraint_indicator_flags: sps.constraint_flags,
527 general_level_idc: sps.level_idc,
528 min_spatial_segmentation_idc: 0, parallelism_type: 0, chroma_format_idc: sps.chroma_format_idc,
531 bit_depth_luma_minus8: sps.bit_depth_luma_minus8,
532 bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8,
533 avg_frame_rate: 0, constant_frame_rate: 0,
535 num_temporal_layers: sps.max_sub_layers_minus1 + 1,
536 temporal_id_nested: sps.temporal_id_nesting_flag,
537 length_size_minus_one: 3,
538 arrays,
539 }))
540}
541
542pub(crate) fn catalog_hvcc(h265: &hang::catalog::H265) -> Option<Bytes> {
548 if !h265.in_band || h265.profile_space != 0 || !matches!(h265.profile_idc, 1 | 3) {
549 return None;
550 }
551
552 Some(encode_hvcc(&mp4_atom::Hvcc {
553 configuration_version: 1,
554 general_profile_space: h265.profile_space,
555 general_tier_flag: h265.tier_flag,
556 general_profile_idc: h265.profile_idc,
557 general_profile_compatibility_flags: h265.profile_compatibility_flags,
558 general_constraint_indicator_flags: h265.constraint_flags,
559 general_level_idc: h265.level_idc,
560 chroma_format_idc: 1, length_size_minus_one: 3,
563 ..Default::default()
564 }))
565}
566
567fn encode_hvcc(record: &mp4_atom::Hvcc) -> Bytes {
569 use mp4_atom::Atom;
570 let mut out = BytesMut::new();
571 record
572 .encode_body(&mut out)
573 .expect("mp4-atom masks every hvcC field to its width");
574 out.freeze()
575}
576
577pub(crate) fn hvcc_params(hvcc: &[u8]) -> Result<(usize, Vec<Bytes>)> {
582 let record = decode_hvcc(hvcc)?;
583 let params = record
584 .arrays
585 .into_iter()
586 .flat_map(|array| array.nalus)
587 .map(Bytes::from)
588 .collect();
589 Ok((usize::from(record.length_size_minus_one) + 1, params))
590}
591
592fn decode_hvcc(hvcc: &[u8]) -> Result<mp4_atom::Hvcc> {
594 use mp4_atom::Atom;
595 if hvcc.len() < 23 {
596 return Err(Error::HvccTooShort);
597 }
598 mp4_atom::Hvcc::decode_body(&mut &hvcc[..]).map_err(|_| Error::HvccTruncated)
599}
600
601#[cfg(any(test, feature = "fuzz"))]
604#[cfg_attr(
605 not(test),
606 allow(dead_code, reason = "the fuzz seeds use only the Main parameter sets")
607)]
608pub(crate) mod fixtures {
609 use bytes::Bytes;
610
611 pub(crate) const VPS: &[u8] = &[
612 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00,
613 0x03, 0x00, 0x5d, 0x95, 0x98, 0x09,
614 ];
615 pub(crate) const SPS: &[u8] = &[
616 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x5d,
617 0xa0, 0x02, 0x80, 0x80, 0x2d, 0x16, 0x59, 0x59, 0xa4, 0x93, 0x2b, 0xc0, 0x5a, 0x02, 0x00, 0x00, 0x03, 0x00,
618 0x02, 0x00, 0x00, 0x03, 0x00, 0x3c, 0x10,
619 ];
620 pub(crate) const PPS: &[u8] = &[0x44, 0x01, 0xc1, 0x72, 0xb4, 0x62, 0x40];
621
622 pub(crate) const MV_SPS: &[u8] = &[
624 0x42, 0x01, 0x01, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x9f, 0xa8, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1e, 0xa0,
625 0x10, 0x20, 0x41, 0x65, 0xba, 0x92, 0x4c, 0xae, 0x01, 0x00, 0x00, 0x03, 0x03, 0xe8, 0x00, 0x00, 0x61, 0xa8,
626 0x14, 0x04,
627 ];
628 pub(crate) const MV_SPS_LAYER1: &[u8] = &[0x42, 0x09, 0x0e, 0x85, 0x92, 0x4c, 0xae, 0x00, 0x50, 0x30];
631 pub(crate) const MV_PPS_LAYER1: &[u8] = &[0x44, 0x09, 0x48, 0x57, 0x2b, 0x02, 0x2a, 0x01, 0x40];
633
634 pub(crate) const SPS_HDR10: &[u8] = &[
636 0x42, 0x01, 0x01, 0x02, 0x20, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x1e,
637 0xa0, 0x20, 0x81, 0x04, 0xd9, 0x65, 0x65, 0x4a, 0x4c, 0x2f, 0x01, 0x6a, 0x12, 0x20, 0x12, 0x08, 0x00, 0x00,
638 0x03, 0x00, 0x08, 0x00, 0x00, 0x03, 0x00, 0xc8, 0x40,
639 ];
640 pub(crate) const SEI_CONTENT_LIGHT: &[u8] = &[0x4e, 0x01, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80];
642 pub(crate) const SEI_MASTERING: &[u8] = &[
644 0x4e, 0x01, 0x89, 0x18, 0x21, 0x34, 0x9b, 0xaa, 0x19, 0x96, 0x08, 0xfc, 0x8a, 0x48, 0x39, 0x08, 0x3d, 0x13,
645 0x40, 0x42, 0x00, 0x98, 0x96, 0x80, 0x00, 0x00, 0x03, 0x00, 0x32, 0x80,
646 ];
647 pub(crate) const SPS_PYRAMID: &[u8] = &[
650 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x3c,
651 0xa0, 0x20, 0x81, 0x05, 0x96, 0x56, 0x59, 0x24, 0xca, 0xf0, 0x16, 0x80, 0x80, 0x00, 0x00, 0x03, 0x00, 0x80,
652 0x00, 0x00, 0x0c, 0xb0, 0x0a, 0x48, 0x2f, 0x00, 0x07, 0xa1, 0x20, 0x00, 0xf4, 0x24, 0x40,
653 ];
654
655 pub(crate) const SPS_ZERO_COLOUR: &[u8] = &[
660 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00,
661 0x96, 0xa0, 0x03, 0xc0, 0x80, 0x11, 0x07, 0xcb, 0x8a, 0xad, 0x3b, 0xa2, 0x4b, 0xb9, 0x08, 0x00, 0x00, 0x03,
662 0x00, 0x20, 0x05, 0x26, 0x5c, 0x00, 0x33, 0x7f, 0x98, 0x01,
663 ];
664
665 pub(crate) const SPS_NVENC: &[u8] = &[
668 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x78,
669 0xa0, 0x02, 0x80, 0x80, 0x2e, 0x1f, 0x13, 0x96, 0x5d, 0x29, 0x08, 0x46, 0x45, 0xd5, 0x0c, 0x04, 0x04, 0x00,
670 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xf1, 0x80, 0x17, 0x79, 0x44, 0x00, 0x02, 0xdc, 0x6c, 0x00,
671 0x00, 0x2d, 0xc6, 0xc0, 0x40,
672 ];
673
674 pub(crate) const SPS_ANAMORPHIC: &[u8] = &[
676 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x78,
677 0xa0, 0x02, 0xd0, 0x80, 0x11, 0x07, 0xcb, 0x96, 0x5d, 0x29, 0x08, 0x46, 0x45, 0xd5, 0x0c, 0x38, 0x04, 0x00,
678 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x79, 0x80, 0x17, 0x79, 0x44, 0x00, 0x02, 0xdc, 0x6c, 0x00,
679 0x00, 0xf4, 0x24, 0x04,
680 ];
681
682 pub(crate) fn hvcc() -> Bytes {
684 super::build_hvcc(
685 &[Bytes::from_static(VPS)],
686 &[Bytes::from_static(SPS)],
687 &[Bytes::from_static(PPS)],
688 )
689 .expect("real parameter sets must build an hvcC")
690 }
691}
692
693#[cfg(test)]
694mod tests {
695 use super::*;
696 use bytes::BufMut;
697
698 fn length_prefixed(nals: &[&[u8]]) -> Vec<u8> {
700 let mut au = Vec::new();
701 for nal in nals {
702 au.extend_from_slice(&(nal.len() as u32).to_be_bytes());
703 au.extend_from_slice(nal);
704 }
705 au
706 }
707
708 fn ts() -> moq_net::Timestamp {
709 moq_net::Timestamp::from_micros(0).unwrap()
710 }
711
712 #[test]
713 fn sps_reorder_reads_the_highest_sub_layer() {
714 let reorder = sps_reorder(fixtures::SPS_PYRAMID).unwrap();
715 assert_eq!(reorder.depth, 2);
716 assert_eq!(reorder.period, Some((1, 25)));
717 assert_eq!(sps_reorder(&fixtures::SPS[..8]), None);
718 }
719
720 #[test]
722 fn hvc1_keeps_the_base_layer_beside_an_enhancement_update() {
723 let annexb = |nals: &[&[u8]]| {
724 let mut buf = BytesMut::new();
725 for nal in nals {
726 buf.extend_from_slice(&[0, 0, 0, 1]);
727 buf.extend_from_slice(nal);
728 }
729 buf.freeze()
730 };
731 let idr: &[u8] = &[0x26, 0x01, 0x80, 0xaa];
732 let mut hvc1 = Hvc1::new();
733 hvc1.transform(annexb(&[fixtures::VPS, fixtures::MV_SPS, fixtures::PPS, idr]))
734 .unwrap();
735 hvc1.transform(annexb(&[fixtures::MV_SPS_LAYER1, fixtures::MV_PPS_LAYER1, idr]))
736 .unwrap();
737 let params = Hvcc::parse(hvc1.hvcc().unwrap()).unwrap();
738 assert_eq!(params.sps, [fixtures::MV_SPS, fixtures::MV_SPS_LAYER1]);
739 assert_eq!(params.pps, [fixtures::PPS, fixtures::MV_PPS_LAYER1]);
740 }
741
742 #[test]
746 fn hvc1_frame_keyframe() {
747 let sei: &[u8] = &[0x4e, 0x01, 0x05, 0xff]; let idr: &[u8] = &[0x26, 0x01, 0x80, 0xaa]; let au = length_prefixed(&[sei, idr]);
750
751 let frame = hvc1_frame(&au, 4, ts()).unwrap();
752 assert!(frame.keyframe);
753 assert_eq!(frame.payload, au);
754 }
755
756 #[test]
758 fn hvc1_frame_cra_keyframe() {
759 let cra: &[u8] = &[0x2a, 0x01, 0x80, 0x55]; let au = length_prefixed(&[cra]);
761
762 let frame = hvc1_frame(&au, 4, ts()).unwrap();
763 assert!(frame.keyframe);
764 }
765
766 #[test]
768 fn hvc1_frame_delta() {
769 let trail: &[u8] = &[0x02, 0x01, 0x80, 0x33]; let au = length_prefixed(&[trail]);
771
772 let frame = hvc1_frame(&au, 4, ts()).unwrap();
773 assert!(!frame.keyframe);
774 }
775
776 #[test]
780 fn hvc1_frame_tsa_delta_not_h264_idr() {
781 let tsa: &[u8] = &[0x05, 0x01, 0x80, 0x33]; let au = length_prefixed(&[tsa]);
783
784 let frame = hvc1_frame(&au, 4, ts()).unwrap();
785 assert!(!frame.keyframe);
786 }
787
788 #[test]
792 fn hvcc_config_reads_the_sps_colour() {
793 let hvcc = |sps: &'static [u8]| {
794 build_hvcc(
795 &[Bytes::from_static(fixtures::VPS)],
796 &[Bytes::from_static(sps)],
797 &[Bytes::from_static(fixtures::PPS)],
798 )
799 .unwrap()
800 };
801 let color = config_from_hvcc(&hvcc(fixtures::SPS_HDR10)).unwrap().color.unwrap();
802 assert_eq!(
803 (color.primaries, color.transfer, color.matrix, color.range),
804 (Some(9), Some(16), Some(9), Some(hang::catalog::ColorRange::Limited))
805 );
806 assert_eq!(config_from_hvcc(&hvcc(fixtures::SPS)).unwrap().color, None);
807 assert_eq!(config_from_hvcc(&hvcc(fixtures::SPS_ZERO_COLOUR)).unwrap().color, None);
808 }
809
810 #[test]
811 fn config_from_hvcc_resolves_real_sps() {
812 let hvcc = fixtures::hvcc();
813 let config = config_from_hvcc(&hvcc).unwrap();
814
815 let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
816 panic!("expected H.265 codec")
817 };
818 assert!(!h265.in_band, "hvcC config is out-of-band");
819 assert_eq!(config.coded_width, Some(1280));
820 assert_eq!(config.coded_height, Some(720));
821 assert_eq!(config.description.as_deref(), Some(hvcc.as_ref()));
822 }
823
824 #[test]
828 fn hvcc_params_parses_vps_sps_pps() {
829 let vps = &[0x40, 0x01, 0x0c][..]; let sps = &[0x42, 0x01, 0x01, 0x60][..]; let pps = &[0x44, 0x01, 0xc0][..]; let mut hvcc = BytesMut::new();
834 hvcc.extend_from_slice(&[0u8; 21]); hvcc.put_u8(0xfc | 0x03); hvcc.put_u8(3); for (nal_type, nal) in [(NalType::VPS.0, vps), (NalType::SPS.0, sps), (NalType::PPS.0, pps)] {
838 hvcc.put_u8(0x80 | (nal_type & 0x3f));
839 hvcc.put_u16(1); hvcc.put_u16(nal.len() as u16);
841 hvcc.put_slice(nal);
842 }
843
844 let (length_size, params) = hvcc_params(&hvcc).unwrap();
845 assert_eq!(length_size, 4);
846 assert_eq!(params.len(), 3);
847 assert_eq!(params[0].as_ref(), vps);
848 assert_eq!(params[1].as_ref(), sps);
849 assert_eq!(params[2].as_ref(), pps);
850 }
851
852 #[test]
855 fn hev1_config_tolerates_zeroed_colour_description() {
856 let mut annexb = Vec::new();
857 for nal in [fixtures::VPS, fixtures::SPS_ZERO_COLOUR, fixtures::PPS] {
858 annexb.extend_from_slice(&[0, 0, 0, 1]);
859 annexb.extend_from_slice(nal);
860 }
861 let config = config(&annexb).expect("the SPS head is well-formed");
862 let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
863 panic!("expected H.265 codec")
864 };
865 assert!(h265.in_band);
866 assert_eq!(h265.to_string(), "hev1.1.6.L150");
867 assert_eq!((config.coded_width, config.coded_height), (Some(1920), Some(1080)));
868 }
869
870 #[test]
873 fn hvcc_tolerates_zeroed_colour_description() {
874 let hvcc = build_hvcc(
875 &[Bytes::from_static(fixtures::VPS)],
876 &[Bytes::from_static(fixtures::SPS_ZERO_COLOUR)],
877 &[Bytes::from_static(fixtures::PPS)],
878 )
879 .expect("the SPS head is well-formed");
880 assert_eq!(
881 &hvcc[..23],
882 &[
883 0x01, 0x01, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x96, 0xf0, 0x00, 0xfc, 0xfd,
884 0xf8, 0xf8, 0x00, 0x00, 0x0f, 0x03,
885 ]
886 );
887 let config = config_from_hvcc(&hvcc).unwrap();
888 assert_eq!((config.coded_width, config.coded_height), (Some(1920), Some(1080)));
889 }
890
891 #[test]
894 fn bitstream_and_catalog_paths_agree() {
895 use std::str::FromStr;
896
897 let config = config_from_hvcc(&fixtures::hvcc()).unwrap();
898 let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
899 panic!("expected H.265 codec")
900 };
901
902 assert_eq!(h265.profile_compatibility_flags, [0x60, 0, 0, 0]);
904
905 let encoded = h265.to_string();
906 assert_eq!(encoded, "hvc1.1.6.L93.90");
907
908 let parsed = hang::catalog::H265::from_str(&encoded).unwrap();
909 assert_eq!(parsed.profile_compatibility_flags, h265.profile_compatibility_flags);
910 }
911
912 fn hevc(profile_idc: u8, in_band: bool, profile_space: u8) -> hang::catalog::H265 {
913 hang::catalog::H265 {
914 in_band,
915 profile_space,
916 profile_idc,
917 profile_compatibility_flags: [0x60, 0, 0, 0],
918 tier_flag: false,
919 level_idc: 93,
920 constraint_flags: [0x90, 0, 0, 0, 0, 0],
921 }
922 }
923
924 fn decode_hvcc(bytes: &Bytes) -> mp4_atom::Hvcc {
925 use mp4_atom::Atom;
926 mp4_atom::Hvcc::decode_body(&mut std::io::Cursor::new(bytes.as_ref())).unwrap()
927 }
928
929 #[test]
930 fn catalog_hvcc_main_and_still_picture_round_trip() {
931 for profile_idc in [1, 3] {
932 let hvcc = decode_hvcc(&catalog_hvcc(&hevc(profile_idc, true, 0)).unwrap());
933 assert_eq!(hvcc.general_profile_idc, profile_idc);
934 assert_eq!(hvcc.general_profile_space, 0);
935 assert!(!hvcc.general_tier_flag);
936 assert_eq!(hvcc.general_profile_compatibility_flags, [0x60, 0, 0, 0]);
937 assert_eq!(hvcc.general_constraint_indicator_flags, [0x90, 0, 0, 0, 0, 0]);
938 assert_eq!(hvcc.general_level_idc, 93);
939 assert_eq!(hvcc.chroma_format_idc, 1);
940 assert_eq!(hvcc.bit_depth_luma_minus8, 0);
941 assert_eq!(hvcc.bit_depth_chroma_minus8, 0);
942 assert_eq!(hvcc.length_size_minus_one, 3);
943 assert_eq!(hvcc.num_temporal_layers, 0);
944 assert!(!hvcc.temporal_id_nested);
945 assert!(hvcc.arrays.is_empty());
946 }
947 }
948
949 #[test]
950 fn catalog_hvcc_refuses_profiles_the_string_cannot_describe() {
951 assert!(catalog_hvcc(&hevc(2, true, 0)).is_none(), "Main 10");
952 assert!(catalog_hvcc(&hevc(1, true, 1)).is_none(), "profile space");
953 assert!(catalog_hvcc(&hevc(1, false, 0)).is_none(), "out of band");
954 }
955
956 #[test]
960 fn hvcc_reads_only_the_base_layer_sps() {
961 let layered = build_hvcc(
962 &[Bytes::from_static(fixtures::VPS)],
963 &[
964 Bytes::from_static(fixtures::MV_SPS_LAYER1),
965 Bytes::from_static(fixtures::MV_SPS),
966 ],
967 &[Bytes::from_static(fixtures::PPS)],
968 )
969 .unwrap();
970 let config = config_from_hvcc(&layered).unwrap();
971 assert_eq!((config.coded_width, config.coded_height), (Some(128), Some(64)));
972 let mut applied = config.clone();
973 applied.reorder = Some(9);
974 apply_hvcc_sps(&decode_hvcc(&layered), &mut applied).unwrap();
975 assert_eq!(applied.reorder, config.reorder);
976
977 let mut record = decode_hvcc(&layered);
978 let with_sps = |record: &mp4_atom::Hvcc, sps: Vec<Vec<u8>>| {
979 let mut record = record.clone();
980 for array in &mut record.arrays {
981 if NalType(array.nal_unit_type) == NalType::SPS {
982 array.nalus = sps.clone();
983 }
984 }
985 record
986 };
987 let enhancement = with_sps(&record, vec![fixtures::MV_SPS_LAYER1.to_vec()]);
988 assert!(matches!(
989 config_from_hvcc(&encode_hvcc(&enhancement)),
990 Err(Error::NoBaseLayerSps)
991 ));
992 assert!(matches!(
993 apply_hvcc_sps(&enhancement, &mut config.clone()),
994 Err(Error::NoBaseLayerSps)
995 ));
996 assert!(matches!(
997 build_hvcc(
998 &[Bytes::from_static(fixtures::VPS)],
999 &[Bytes::from_static(fixtures::MV_SPS_LAYER1)],
1000 &[Bytes::from_static(fixtures::PPS)],
1001 ),
1002 Err(Error::NoBaseLayerSps)
1003 ));
1004
1005 record
1006 .arrays
1007 .retain(|array| NalType(array.nal_unit_type) != NalType::SPS);
1008 let mut untouched = config.clone();
1009 apply_hvcc_sps(&record, &mut untouched).unwrap();
1010 assert_eq!(untouched, config);
1011 }
1012}