1mod export;
18mod import;
19mod split;
20
21pub use export::*;
22pub use import::*;
23pub use split::*;
24
25use bytes::{Buf, Bytes, BytesMut};
26use h264_reader::nal::sps::{FrameMbsFlags, SeqParameterSet};
27use h264_reader::rbsp::{BitRead, BitReaderError};
28
29use crate::codec::annexb::{InBandCodec, ParameterSets};
30
31const NAL_TYPE_SEI: u8 = 6;
33const NAL_TYPE_SPS: u8 = 7;
34const NAL_TYPE_PPS: u8 = 8;
35
36pub(crate) fn avc1_frame(
44 data: impl moq_net::IntoBytes,
45 length_size: usize,
46 pts: moq_net::Timestamp,
47) -> crate::Result<crate::container::Frame> {
48 let keyframe = avc1_is_keyframe(data.as_ref(), length_size);
49 Ok(crate::container::Frame {
50 timestamp: pts,
51 decode: None,
52 payload: data.into_bytes(),
53 keyframe,
54 duration: None,
55 })
56}
57
58fn avc1_is_keyframe(data: &[u8], length_size: usize) -> bool {
60 let Ok(nals) = crate::codec::annexb::length_prefixed_nals(data, length_size) else {
61 return false;
62 };
63 nals.map_while(std::result::Result::ok)
64 .any(|nal| nal.first().is_some_and(|header| header & 0x1f == 5))
65}
66
67#[derive(Debug, Clone, thiserror::Error)]
69#[non_exhaustive]
70pub enum Error {
71 #[error("SPS NAL too short")]
73 SpsTooShort,
74
75 #[error("failed to parse SPS")]
77 SpsParse,
78
79 #[error("AVCDecoderConfigurationRecord too short")]
81 AvccTooShort,
82
83 #[error("AVCDecoderConfigurationRecord truncated")]
85 AvccTruncated,
86
87 #[error("unsupported AVCDecoderConfigurationRecord version {0}")]
89 AvccVersion(u8),
90
91 #[error("avc1 description for rendition {name:?} is missing SPS or PPS (sps={sps}, pps={pps})")]
93 MissingParamSets {
94 name: String,
96 sps: usize,
98 pps: usize,
100 },
101
102 #[error("SPS too large for avcC length field ({0} > {max})", max = u16::MAX)]
104 SpsTooLarge(usize),
105
106 #[error("PPS too large for avcC length field ({0} > {max})", max = u16::MAX)]
108 PpsTooLarge(usize),
109
110 #[error("avcC requires at least one SPS")]
112 MissingSps,
113
114 #[error("too many SPS for avcC ({0} > 31)")]
116 TooManySps(usize),
117
118 #[error("too many PPS for avcC ({0} > 255)")]
120 TooManyPps(usize),
121
122 #[error("NAL too large for 4-byte length prefix")]
124 NalTooLarge,
125
126 #[error("NAL unit is too short")]
128 NalTooShort,
129
130 #[error("forbidden zero bit is not zero")]
132 ForbiddenZeroBit,
133
134 #[error("not initialized")]
136 NotInitialized,
137
138 #[error("avc3 track not created")]
140 Avc3TrackNotCreated,
141
142 #[error("missing timestamp")]
144 MissingTimestamp,
145
146 #[error("annexb: {0}")]
148 Annexb(#[from] crate::codec::annexb::Error),
149}
150
151pub type Result<T> = std::result::Result<T, Error>;
153
154#[derive(Debug, Clone)]
160pub struct Sps {
161 pub profile: u8,
163 pub constraints: u8,
165 pub level: u8,
167 pub coded_width: u32,
169 pub coded_height: u32,
171}
172
173impl Sps {
174 pub fn parse(nal: &[u8]) -> Result<Self> {
176 if nal.len() < 4 {
177 return Err(Error::SpsTooShort);
178 }
179 let sps = read_sps(nal).ok_or(Error::SpsParse)?;
180 let (coded_width, coded_height) = sps.pixel_dimensions().map_err(|_| Error::SpsParse)?;
181 if coded_width == 0 || coded_height == 0 {
183 return Err(Error::SpsParse);
184 }
185 Ok(Self {
186 profile: sps.profile_idc.into(),
187 constraints: u8::from(sps.constraint_flags) & 0xfc,
189 level: sps.level_idc,
190 coded_width,
191 coded_height,
192 })
193 }
194}
195
196fn read_sps(nal: &[u8]) -> Option<SeqParameterSet> {
203 use crate::codec::annexb::rbsp;
204
205 SeqParameterSet::from_bits(rbsp(nal, 1)).ok().or_else(|| {
206 let sps = SeqParameterSet::from_bits(WithoutVui(rbsp(nal, 1))).ok()?;
207 tracing::debug!("H.264 SPS VUI refused by h264-reader; using the SPS without it");
208 Some(sps)
209 })
210}
211
212struct WithoutVui<R>(R);
215
216impl<R: BitRead> BitRead for WithoutVui<R> {
217 fn read_ue(&mut self, name: &'static str) -> std::result::Result<u32, BitReaderError> {
218 self.0.read_ue(name)
219 }
220
221 fn read_se(&mut self, name: &'static str) -> std::result::Result<i32, BitReaderError> {
222 self.0.read_se(name)
223 }
224
225 fn read_bit(&mut self, name: &'static str) -> std::result::Result<bool, BitReaderError> {
226 match name {
227 "vui_parameters_present_flag" => Ok(false),
228 _ => self.0.read_bit(name),
229 }
230 }
231
232 fn read<const BITS: u32, I: h264_reader::rbsp::Integer>(
233 &mut self,
234 name: &'static str,
235 ) -> std::result::Result<I, BitReaderError> {
236 self.0.read::<BITS, I>(name)
237 }
238
239 fn read_var<I: h264_reader::rbsp::Integer>(
240 &mut self,
241 bit_count: u32,
242 name: &'static str,
243 ) -> std::result::Result<I, BitReaderError> {
244 self.0.read_var(bit_count, name)
245 }
246
247 fn read_to<V: h264_reader::rbsp::Primitive>(
248 &mut self,
249 name: &'static str,
250 ) -> std::result::Result<V, BitReaderError> {
251 self.0.read_to(name)
252 }
253
254 fn skip(&mut self, bit_count: u32, name: &'static str) -> std::result::Result<(), BitReaderError> {
255 self.0.skip(bit_count, name)
256 }
257
258 fn byte_aligned(&self) -> bool {
259 self.0.byte_aligned()
260 }
261
262 fn has_more_rbsp_data(&mut self, name: &'static str) -> std::result::Result<bool, BitReaderError> {
263 self.0.has_more_rbsp_data(name)
264 }
265
266 fn finish_rbsp(self) -> std::result::Result<(), BitReaderError> {
268 Ok(())
269 }
270
271 fn finish_sei_payload(self) -> std::result::Result<(), BitReaderError> {
272 self.0.finish_sei_payload()
273 }
274}
275
276pub(crate) fn sps_reorder(nal: &[u8]) -> Option<crate::codec::video::Reorder> {
281 let vui = sps_vui(nal)?;
282 Some(crate::codec::video::Reorder {
283 depth: vui.depth?,
284 period: vui.period,
285 })
286}
287
288pub(crate) fn sps_hrd(nal: &[u8]) -> Option<crate::codec::video::Hrd> {
290 sps_vui(nal)?.hrd
291}
292
293pub(crate) fn sps_interlaced(nal: &[u8]) -> Option<bool> {
295 let sps = read_sps(nal)?;
296 Some(!matches!(sps.frame_mbs_flags, FrameMbsFlags::Frames))
297}
298
299struct Vui {
301 sample_aspect: Option<(u32, u32)>,
303 color: Option<hang::catalog::Color>,
305 frame_only: bool,
307 period: Option<(u64, u64)>,
309 depth: Option<u32>,
311 hrd: Option<crate::codec::video::Hrd>,
313}
314
315impl Vui {
316 fn new(sps: &SeqParameterSet) -> Option<Self> {
318 let vui = sps.vui_parameters.as_ref()?;
319 let sample_aspect = vui
320 .aspect_ratio_info
321 .as_ref()
322 .and_then(|info| info.get())
323 .map(|(width, height)| (u32::from(width), u32::from(height)));
324 let color = vui.video_signal_type.as_ref().and_then(|signal| {
325 let (primaries, transfer, matrix) = match &signal.colour_description {
326 Some(c) => (c.colour_primaries, c.transfer_characteristics, c.matrix_coefficients),
327 None => (2, 2, 2),
328 };
329 crate::codec::color::cicp(primaries, transfer, matrix, Some(signal.video_full_range_flag))
330 });
331 let period = vui
333 .timing_info
334 .as_ref()
335 .filter(|t| t.fixed_frame_rate_flag && t.num_units_in_tick > 0 && t.time_scale > 0)
336 .map(|t| (2 * u64::from(t.num_units_in_tick), u64::from(t.time_scale)));
337 let hrd = vui.nal_hrd_parameters.as_ref().and_then(|hrd| {
339 let spec = hrd.cpb_specs.last()?;
340 Some(crate::codec::video::Hrd {
341 bit_rate: (u64::from(spec.bit_rate_value_minus1) + 1) << (6 + hrd.bit_rate_scale),
342 cpb_size: (u64::from(spec.cpb_size_value_minus1) + 1) << (4 + hrd.cpb_size_scale),
343 })
344 });
345 Some(Self {
346 sample_aspect,
347 color,
348 frame_only: matches!(sps.frame_mbs_flags, FrameMbsFlags::Frames),
349 period,
350 depth: vui.bitstream_restrictions.as_ref().map(|b| b.max_num_reorder_frames),
351 hrd,
352 })
353 }
354
355 fn framerate(&self) -> Option<f64> {
358 if !self.frame_only {
359 return None;
360 }
361 let (units, scale) = self.period?;
362 Some(scale as f64 / units as f64)
363 }
364
365 fn apply(&self, config: &mut hang::catalog::VideoConfig) {
366 config.framerate = self.framerate();
367 let display_aspect = match (config.coded_width, config.coded_height, self.sample_aspect) {
368 (Some(width), Some(height), Some(sample)) => crate::codec::video::display_aspect(width, height, sample),
369 _ => None,
370 };
371 config.display_aspect_width = display_aspect.map(|(width, _)| width);
372 config.display_aspect_height = display_aspect.map(|(_, height)| height);
373 config.color = self.color.clone();
374 config.reorder = self
376 .depth
377 .filter(|depth| self.frame_only && *depth <= crate::codec::video::max_reorder(config))
378 .and_then(|depth| u8::try_from(depth).ok());
379 }
380}
381
382fn sps_vui(nal: &[u8]) -> Option<Vui> {
384 Vui::new(&read_sps(nal)?)
385}
386
387#[derive(Debug, Clone)]
393#[non_exhaustive]
394pub struct Avcc {
395 pub profile: u8,
397 pub constraints: u8,
399 pub level: u8,
401 pub length_size: usize,
403 pub sps: Vec<Bytes>,
405 pub pps: Vec<Bytes>,
407 pub coded_width: Option<u32>,
409 pub coded_height: Option<u32>,
411}
412
413pub(crate) const AVCC_MAX_LEN: usize = 6 + 1 + 4 + (31 + 255 + 255) * (2 + u16::MAX as usize);
417
418impl Avcc {
419 pub fn parse(avcc: &[u8]) -> Result<Self> {
421 if avcc.len() < 7 {
422 return Err(Error::AvccTooShort);
423 }
424
425 let record = decode_avcc(avcc)?;
426 let sps: Vec<Bytes> = record.sequence_parameter_sets.into_iter().map(Bytes::from).collect();
427 let pps = record.picture_parameter_sets.into_iter().map(Bytes::from).collect();
428
429 let parsed = sps.iter().find_map(|nal| Sps::parse(nal).ok());
431 let coded_width = parsed.as_ref().map(|sps| sps.coded_width);
432 let coded_height = parsed.as_ref().map(|sps| sps.coded_height);
433
434 Ok(Self {
435 profile: record.avc_profile_indication,
436 constraints: record.profile_compatibility,
437 level: record.avc_level_indication,
438 length_size: record.length_size.into(),
439 sps,
440 pps,
441 coded_width,
442 coded_height,
443 })
444 }
445}
446
447fn decode_avcc(avcc: &[u8]) -> Result<mp4_atom::Avcc> {
452 use mp4_atom::Atom;
453 mp4_atom::Avcc::decode_body(&mut &avcc[..]).map_err(|err| match err {
454 mp4_atom::Error::UnknownVersion(version) => Error::AvccVersion(version),
455 _ => Error::AvccTruncated,
456 })
457}
458
459fn encode_avcc(record: &mp4_atom::Avcc) -> Bytes {
461 use mp4_atom::Atom;
462 let mut out = BytesMut::new();
463 record
464 .encode_body(&mut out)
465 .expect("a length size of 4 and an 8-bit 4:2:0 extension encode");
466 out.freeze()
467}
468
469pub(crate) fn build_avcc(sps_nals: &[Bytes], pps_nals: &[Bytes]) -> Result<Bytes> {
475 let first_sps = sps_nals.first().ok_or(Error::MissingSps)?;
476 if first_sps.len() < 4 {
477 return Err(Error::SpsTooShort);
478 }
479 if sps_nals.len() > 0x1f {
482 return Err(Error::TooManySps(sps_nals.len()));
483 }
484 if pps_nals.len() > u8::MAX as usize {
485 return Err(Error::TooManyPps(pps_nals.len()));
486 }
487 for sps in sps_nals {
488 if sps.len() > u16::MAX as usize {
489 return Err(Error::SpsTooLarge(sps.len()));
490 }
491 }
492 for pps in pps_nals {
493 if pps.len() > u16::MAX as usize {
494 return Err(Error::PpsTooLarge(pps.len()));
495 }
496 }
497
498 Ok(encode_avcc(&mp4_atom::Avcc {
499 configuration_version: 1,
500 avc_profile_indication: first_sps[1],
501 profile_compatibility: first_sps[2],
502 avc_level_indication: first_sps[3],
503 length_size: 4,
504 sequence_parameter_sets: sps_nals.iter().map(|nal| nal.to_vec()).collect(),
505 picture_parameter_sets: pps_nals.iter().map(|nal| nal.to_vec()).collect(),
506 ext: None,
507 }))
508}
509
510pub(crate) fn catalog_avcc(h264: &hang::catalog::H264) -> Option<Bytes> {
519 if !h264.inline {
520 return None;
521 }
522 let ext = match h264.profile {
523 66 | 77 | 88 => None,
524 100 => Some(mp4_atom::AvccExt::default()),
526 _ => return None,
527 };
528
529 Some(encode_avcc(&mp4_atom::Avcc {
530 configuration_version: 1,
531 avc_profile_indication: h264.profile,
532 profile_compatibility: h264.constraints,
533 avc_level_indication: h264.level,
534 length_size: 4,
535 sequence_parameter_sets: Vec::new(),
536 picture_parameter_sets: Vec::new(),
537 ext,
538 }))
539}
540
541pub(crate) fn avcc_params(avcc: &[u8]) -> Result<(usize, Vec<Bytes>)> {
545 let record = decode_avcc(avcc)?;
546 let params = record
547 .sequence_parameter_sets
548 .into_iter()
549 .chain(record.picture_parameter_sets)
550 .map(Bytes::from)
551 .collect();
552 Ok((record.length_size.into(), params))
553}
554
555pub struct Avc1 {
567 avcc: Option<Bytes>,
568 sps: Vec<Bytes>,
570 pps: Vec<Bytes>,
572}
573
574impl Default for Avc1 {
575 fn default() -> Self {
576 Self::new()
577 }
578}
579
580impl Avc1 {
581 pub fn new() -> Self {
583 Self {
584 avcc: None,
585 sps: Vec::new(),
586 pps: Vec::new(),
587 }
588 }
589
590 pub fn avcc(&self) -> Option<&Bytes> {
592 self.avcc.as_ref()
593 }
594
595 pub fn transform(&mut self, payload: Bytes) -> Result<Option<Bytes>> {
603 let mut buf = payload.clone();
607 let mut nal_iter = crate::codec::annexb::NalIterator::new(&mut buf);
608
609 let mut out = BytesMut::with_capacity(payload.remaining());
610 let mut frame_sps = ParameterSets::new();
611 let mut frame_pps = ParameterSets::new();
612 let mut emitted_any_slice = false;
613
614 loop {
615 let nal = match nal_iter.next() {
616 Some(Ok(n)) => n,
617 Some(Err(e)) => return Err(e.into()),
618 None => break,
619 };
620 if process_nal(&nal, &mut out, &mut frame_sps, &mut frame_pps)? {
621 emitted_any_slice = true;
622 }
623 }
624
625 if let Some(nal) = nal_iter.flush()?
626 && process_nal(&nal, &mut out, &mut frame_sps, &mut frame_pps)?
627 {
628 emitted_any_slice = true;
629 }
630
631 let mut changed = false;
636 let frame_sps: Vec<Bytes> = frame_sps.into_values().collect();
637 if !frame_sps.is_empty() && frame_sps != self.sps {
638 self.sps = frame_sps;
639 changed = true;
640 }
641 let frame_pps: Vec<Bytes> = frame_pps.into_values().collect();
642 if !frame_pps.is_empty() && frame_pps != self.pps {
643 self.pps = frame_pps;
644 changed = true;
645 }
646 if changed {
647 self.rebuild_avcc()?;
648 }
649
650 if !emitted_any_slice {
651 return Ok(None);
652 }
653
654 Ok(Some(out.freeze()))
655 }
656
657 fn rebuild_avcc(&mut self) -> Result<()> {
658 if self.sps.is_empty() || self.pps.is_empty() {
659 return Ok(());
660 }
661 self.avcc = Some(build_avcc(&self.sps, &self.pps)?);
662 Ok(())
663 }
664}
665
666fn process_nal(
670 nal: &Bytes,
671 out: &mut BytesMut,
672 frame_sps: &mut ParameterSets,
673 frame_pps: &mut ParameterSets,
674) -> Result<bool> {
675 if nal.is_empty() {
676 return Ok(false);
677 }
678 match nal[0] & 0x1f {
679 NAL_TYPE_SPS => {
680 InBandCodec::H264.insert_parameter_set(frame_sps, nal)?;
681 Ok(false)
682 }
683 NAL_TYPE_PPS => {
684 InBandCodec::H264.insert_parameter_set(frame_pps, nal)?;
685 Ok(false)
686 }
687 _ => {
688 let len = u32::try_from(nal.len()).map_err(|_| Error::NalTooLarge)?;
689 out.extend_from_slice(&len.to_be_bytes());
690 out.extend_from_slice(nal);
691 Ok(true)
692 }
693 }
694}
695
696#[cfg(test)]
699pub(crate) mod fixtures {
700 pub(crate) const SPS_ANAMORPHIC: &[u8] = &[
702 0x67, 0x64, 0x00, 0x28, 0xac, 0xd9, 0x40, 0x5a, 0x02, 0x27, 0xe5, 0xc3, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
703 0x00, 0x00, 0x03, 0x00, 0xca, 0x3c, 0x60, 0xc6, 0x58,
704 ];
705 pub(crate) const SPS_EXTENDED_SAR: &[u8] = &[
707 0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x44, 0x7b, 0xff, 0x00, 0x07, 0x00, 0x05, 0x10, 0x00, 0x00, 0x03, 0x00,
708 0x10, 0x00, 0x00, 0x03, 0x03, 0x28, 0xf1, 0x22, 0x59, 0x60,
709 ];
710 pub(crate) const SPS_IPB: &[u8] = &[
713 0x67, 0x64, 0x00, 0x0a, 0xac, 0xe4, 0x10, 0x9b, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03,
714 0x03, 0x28, 0xf1, 0x22, 0x51, 0x20,
715 ];
716 pub(crate) const SPS_PYRAMID: &[u8] = &[
719 0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x44, 0x26, 0xc0, 0x44, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03,
720 0x00, 0xca, 0x3c, 0x48, 0x96, 0x58,
721 ];
722 pub(crate) const SPS_IPB_VARIABLE: &[u8] = &[
724 0x67, 0x64, 0x00, 0x0a, 0xac, 0xe4, 0x10, 0x9b, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03,
725 0x03, 0x20, 0xf1, 0x22, 0x51, 0x20,
726 ];
727 pub(crate) const SPS_FIELD: &[u8] = &[
730 0x67, 0xf4, 0x00, 0x15, 0x91, 0x9d, 0x02, 0x82, 0x1f, 0x89, 0xc0, 0x44, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00,
731 0x00, 0x03, 0x00, 0xca, 0x7c, 0x50, 0xaa, 0x80,
732 ];
733 pub(crate) const SPS_HRD: &[u8] = &[
736 0x67, 0x64, 0x00, 0x1e, 0xac, 0xe4, 0x10, 0x9b, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03,
737 0x03, 0x2e, 0x04, 0x00, 0x00, 0x89, 0x54, 0x40, 0x00, 0x11, 0x2a, 0x8e, 0x4c, 0x30, 0x07, 0x8b, 0x16, 0x89,
738 ];
739 pub(crate) const PPS: &[u8] = &[0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0];
740 pub(crate) const SPS_BT709: &[u8] = &[
743 0x67, 0x42, 0xc0, 0x0a, 0xda, 0x10, 0x9b, 0x01, 0x6a, 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x03, 0x00, 0x80,
744 0x00, 0x00, 0x19, 0x07, 0x89, 0x13, 0x50,
745 ];
746 pub(crate) const SPS_HDR10: &[u8] = &[
748 0x67, 0x42, 0xc0, 0x0a, 0xda, 0x10, 0x9b, 0x01, 0x6a, 0x12, 0x20, 0x12, 0x80, 0x00, 0x00, 0x03, 0x00, 0x80,
749 0x00, 0x00, 0x19, 0x07, 0x89, 0x13, 0x50,
750 ];
751 pub(crate) const SEI_MASTERING: &[u8] = &[
754 0x06, 0x89, 0x18, 0x21, 0x34, 0x9b, 0xaa, 0x19, 0x96, 0x08, 0xfc, 0x8a, 0x48, 0x39, 0x08, 0x3d, 0x13, 0x40,
755 0x42, 0x00, 0x98, 0x96, 0x80, 0x00, 0x00, 0x03, 0x00, 0x32, 0x80,
756 ];
757 pub(crate) const SEI_CONTENT_LIGHT: &[u8] = &[0x06, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80];
759}
760
761#[cfg(test)]
762mod tests {
763 use super::*;
764
765 #[test]
767 fn sps_color_reads_the_video_signal_type() {
768 let sps_color = |nal: &[u8]| sps_vui(nal)?.color;
769 let sdr = sps_color(fixtures::SPS_BT709).unwrap();
770 assert_eq!(
771 (sdr.primaries, sdr.transfer, sdr.matrix, sdr.range),
772 (Some(1), Some(1), Some(1), Some(hang::catalog::ColorRange::Limited))
773 );
774 let hdr = sps_color(fixtures::SPS_HDR10).unwrap();
775 assert_eq!(
776 (hdr.primaries, hdr.transfer, hdr.matrix, hdr.range),
777 (Some(9), Some(16), Some(9), Some(hang::catalog::ColorRange::Limited))
778 );
779 assert_eq!(sps_color(fixtures::SPS_IPB), None, "a VUI without a video signal type");
780 }
781
782 #[test]
784 fn sps_with_a_short_vui_keeps_the_fields_before_it() {
785 let sps: &[u8] = &[
786 0x67, 0x42, 0xc0, 0x1f, 0xda, 0x01, 0x40, 0x16, 0xe9, 0xb8, 0x08, 0x08, 0x0a, 0x00, 0x00, 0x07, 0xd0, 0x00,
787 0x01, 0xd4, 0xc0, 0x80,
788 ];
789 assert!(SeqParameterSet::from_bits(crate::codec::annexb::rbsp(sps, 1)).is_err());
790 let parsed = Sps::parse(sps).unwrap();
791 assert_eq!((parsed.profile, parsed.constraints, parsed.level), (0x42, 0xc0, 0x1f));
792 assert_eq!((parsed.coded_width, parsed.coded_height), (1280, 720));
793 assert!(sps_vui(sps).is_none());
794 assert_eq!(sps_interlaced(sps), Some(false));
795 }
796
797 #[test]
799 fn sps_ignores_trailing_zero_bytes() {
800 let mut padded = fixtures::SPS_IPB.to_vec();
801 padded.extend_from_slice(&[0, 0, 0, 0]);
802 assert_eq!(sps_reorder(&padded), sps_reorder(fixtures::SPS_IPB));
803 assert!(sps_reorder(&padded).is_some());
804 }
805
806 const SC4: &[u8] = &[0, 0, 0, 1];
807
808 #[test]
809 fn sps_reorder_reads_the_vui() {
810 use crate::codec::video::Reorder;
811
812 let fixed = Some((2, 50));
813 assert_eq!(
814 sps_reorder(fixtures::SPS_IPB),
815 Some(Reorder {
816 depth: 1,
817 period: fixed
818 })
819 );
820 assert_eq!(
821 sps_reorder(fixtures::SPS_PYRAMID),
822 Some(Reorder {
823 depth: 2,
824 period: fixed
825 })
826 );
827 assert_eq!(
828 sps_reorder(fixtures::SPS_IPB_VARIABLE),
829 Some(Reorder { depth: 1, period: None })
830 );
831 assert_eq!(
834 sps_reorder(fixtures::SPS_FIELD),
835 Some(Reorder {
836 depth: 0,
837 period: Some((2, 50))
838 })
839 );
840 assert_eq!(sps_reorder(&[0x67, 0x42, 0xc0, 0x1f, 0xde]), None);
842 assert_eq!(sps_reorder(&fixtures::SPS_IPB[..fixtures::SPS_IPB.len() - 3]), None);
844 }
845
846 #[test]
847 fn sps_framerate_needs_a_fixed_rate() {
848 assert_eq!(sps_vui(fixtures::SPS_IPB).unwrap().framerate(), Some(25.0));
849 assert_eq!(sps_vui(fixtures::SPS_IPB_VARIABLE).unwrap().framerate(), None);
851 assert_eq!(sps_vui(fixtures::SPS_FIELD).unwrap().framerate(), None);
853 assert!(sps_vui(&[0x67, 0x42, 0xc0, 0x1f, 0xde]).is_none());
854 }
855
856 #[test]
857 fn sps_hrd_reads_the_nal_hrd() {
858 use crate::codec::video::{Hrd, Reorder};
859
860 assert_eq!(
861 sps_hrd(fixtures::SPS_HRD),
862 Some(Hrd {
863 bit_rate: 9_000_000,
864 cpb_size: 9_000_000
865 })
866 );
867 assert_eq!(
869 sps_reorder(fixtures::SPS_HRD),
870 Some(Reorder {
871 depth: 1,
872 period: Some((2, 50))
873 })
874 );
875 assert_eq!(sps_hrd(fixtures::SPS_IPB), None);
876 }
877
878 fn annexb_frame(nals: &[&[u8]]) -> Bytes {
879 let mut buf = BytesMut::new();
880 for nal in nals {
881 buf.extend_from_slice(SC4);
882 buf.extend_from_slice(nal);
883 }
884 buf.freeze()
885 }
886
887 #[test]
890 fn avc1_frame_keyframe() {
891 let idr: &[u8] = &[0x65, 0x88, 0x84, 0x21];
892 let mut au = BytesMut::new();
893 au.extend_from_slice(&(idr.len() as u32).to_be_bytes());
894 au.extend_from_slice(idr);
895
896 let frame = avc1_frame(&au, 4, moq_net::Timestamp::from_micros(0).unwrap()).unwrap();
897 assert!(frame.keyframe);
898 assert_eq!(frame.payload[4..], *idr);
899 }
900
901 #[test]
903 fn avc1_frame_delta() {
904 let pslice: &[u8] = &[0x61, 0xe0, 0x12, 0x34];
905 let mut au = BytesMut::new();
906 au.extend_from_slice(&(pslice.len() as u32).to_be_bytes());
907 au.extend_from_slice(pslice);
908
909 let frame = avc1_frame(&au, 4, moq_net::Timestamp::from_micros(0).unwrap()).unwrap();
910 assert!(!frame.keyframe);
911 }
912
913 #[test]
914 fn avc3_strips_sps_pps_and_builds_avcc() {
915 let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
916 let pps = &[0x68, 0xce, 0x3c, 0x80][..];
917 let idr = &[0x65, 0x88, 0x84, 0x21][..];
918
919 let mut tx = Avc1::new();
920 assert!(tx.avcc().is_none());
921
922 let frame = annexb_frame(&[sps, pps, idr]);
923 let out = tx.transform(frame).expect("transform").expect("expected output");
924
925 let avcc = tx.avcc().expect("avcC available").clone();
926 assert_eq!(avcc[0], 1);
927 assert_eq!(avcc[1], sps[1]);
928 assert_eq!(avcc[3], sps[3]);
929
930 let mut expected = BytesMut::new();
931 expected.extend_from_slice(&(idr.len() as u32).to_be_bytes());
932 expected.extend_from_slice(idr);
933 assert_eq!(out.as_ref(), expected.as_ref());
934 }
935
936 #[test]
937 fn avcc_params_roundtrips_build_avcc() {
938 let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
939 let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
940
941 let avcc = build_avcc(std::slice::from_ref(&sps), std::slice::from_ref(&pps)).unwrap();
942 let (length_size, params) = avcc_params(&avcc).unwrap();
943
944 assert_eq!(length_size, 4);
945 assert_eq!(params.len(), 2);
946 assert_eq!(params[0], sps);
947 assert_eq!(params[1], pps);
948 }
949
950 #[test]
951 fn build_avcc_layout_is_unchanged() {
952 let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
953 let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
954
955 let avcc = build_avcc(std::slice::from_ref(&sps), std::slice::from_ref(&pps)).unwrap();
956 assert_eq!(
957 avcc.as_ref(),
958 &[
959 0x01, 0x42, 0xc0, 0x1f, 0xff, 0xe1, 0x00, 0x05, 0x67, 0x42, 0xc0, 0x1f, 0xde, 0x01, 0x00, 0x04, 0x68,
960 0xce, 0x3c, 0x80,
961 ]
962 );
963 }
964
965 #[test]
966 fn avcc_parse_reads_past_the_high_extension() {
967 let sps = fixtures::SPS_ANAMORPHIC;
968 let avcc = encode_avcc(&mp4_atom::Avcc {
969 configuration_version: 1,
970 avc_profile_indication: sps[1],
971 profile_compatibility: sps[2],
972 avc_level_indication: sps[3],
973 length_size: 4,
974 sequence_parameter_sets: vec![sps.to_vec()],
975 picture_parameter_sets: vec![fixtures::PPS.to_vec()],
976 ext: Some(mp4_atom::AvccExt::default()),
977 });
978
979 let parsed = Avcc::parse(&avcc).unwrap();
980 assert_eq!(parsed.profile, 100);
981 assert_eq!(parsed.length_size, 4);
982 assert_eq!(parsed.sps, vec![Bytes::from_static(sps)]);
983 assert_eq!(parsed.pps, vec![Bytes::from_static(fixtures::PPS)]);
984 assert_eq!((parsed.coded_width, parsed.coded_height), (Some(1440), Some(1080)));
985 }
986
987 #[test]
988 fn avcc_parse_refuses_other_versions_and_partial_extensions() {
989 let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
990 let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
991 let avcc = build_avcc(std::slice::from_ref(&sps), std::slice::from_ref(&pps)).unwrap();
992
993 let mut version = avcc.to_vec();
994 version[0] = 0;
995 assert!(matches!(Avcc::parse(&version), Err(Error::AvccVersion(0))));
996
997 let mut partial = avcc.to_vec();
999 partial.push(0xfd);
1000 assert!(matches!(Avcc::parse(&partial), Err(Error::AvccTruncated)));
1001
1002 assert!(matches!(
1003 Avcc::parse(&avcc[..avcc.len() - 1]),
1004 Err(Error::AvccTruncated)
1005 ));
1006 assert!(matches!(Avcc::parse(&avcc[..6]), Err(Error::AvccTooShort)));
1007 }
1008
1009 #[test]
1010 fn build_avcc_carries_multiple_pps() {
1011 let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
1014 let pps0 = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
1015 let pps1 = Bytes::from_static(&[0x68, 0x4e, 0x3c, 0x80]);
1016
1017 let avcc = build_avcc(std::slice::from_ref(&sps), &[pps0.clone(), pps1.clone()]).unwrap();
1018 assert_eq!(avcc[5] & 0x1f, 1);
1020
1021 let (_, params) = avcc_params(&avcc).unwrap();
1022 assert_eq!(params, vec![sps, pps0, pps1]);
1023 }
1024
1025 #[test]
1026 fn avc3_keyframe_with_two_pps_keeps_both() {
1027 let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1029 let pps0 = &[0x68, 0xce, 0x3c, 0x80][..];
1030 let pps1 = &[0x68, 0x4e, 0x3c, 0x80][..];
1031 let idr = &[0x65, 0x88][..];
1032
1033 let mut tx = Avc1::new();
1034 tx.transform(annexb_frame(&[sps, pps0, pps1, idr])).unwrap();
1035
1036 let avcc = tx.avcc().expect("avcC available");
1037 let (_, params) = avcc_params(avcc).unwrap();
1038 assert_eq!(
1039 params.iter().map(|p| p.as_ref()).collect::<Vec<_>>(),
1040 vec![sps, pps0, pps1]
1041 );
1042 }
1043
1044 #[test]
1045 fn avc3_reinit_drops_superseded_pps() {
1046 let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1049 let pps0 = &[0x68, 0xce, 0x3c, 0x80][..];
1050 let pps1 = &[0x68, 0x4e, 0x3c, 0x80][..];
1051 let idr = &[0x65, 0x88][..];
1052
1053 let mut tx = Avc1::new();
1054 tx.transform(annexb_frame(&[sps, pps0, idr])).unwrap();
1055 tx.transform(annexb_frame(&[sps, pps1, idr])).unwrap();
1056
1057 let avcc = tx.avcc().expect("avcC available");
1058 let (_, params) = avcc_params(avcc).unwrap();
1059 assert_eq!(
1060 params.iter().map(|p| p.as_ref()).collect::<Vec<_>>(),
1061 vec![sps, pps1],
1062 "reinit must drop the superseded PPS"
1063 );
1064 }
1065
1066 #[test]
1067 fn avc3_repeated_pps_id_keeps_the_last() {
1068 let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1070 let pps_a = &[0x68, 0xce, 0x3c, 0x80][..];
1071 let pps_b = &[0x68, 0xce, 0x38, 0x80][..];
1072 let idr = &[0x65, 0x88][..];
1073
1074 let mut tx = Avc1::new();
1075 tx.transform(annexb_frame(&[sps, pps_a, pps_b, idr])).unwrap();
1076
1077 let (_, params) = avcc_params(tx.avcc().expect("avcC available")).unwrap();
1078 assert_eq!(params.iter().map(|p| p.as_ref()).collect::<Vec<_>>(), vec![sps, pps_b]);
1079 }
1080
1081 #[test]
1082 fn avc3_parameter_only_frame_returns_none() {
1083 let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1084 let pps = &[0x68, 0xce, 0x3c, 0x80][..];
1085
1086 let mut tx = Avc1::new();
1087 let frame = annexb_frame(&[sps, pps]);
1088 assert!(tx.transform(frame).unwrap().is_none());
1089 assert!(tx.avcc().is_some());
1090 }
1091
1092 #[test]
1093 fn avc3_subsequent_frame_uses_cached_avcc() {
1094 let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1095 let pps = &[0x68, 0xce, 0x3c, 0x80][..];
1096 let idr = &[0x65, 0x88][..];
1097 let p = &[0x61, 0xe0, 0x12][..];
1098
1099 let mut tx = Avc1::new();
1100 tx.transform(annexb_frame(&[sps, pps, idr])).unwrap();
1101 let avcc_v1 = tx.avcc().unwrap().clone();
1102
1103 let out = tx.transform(annexb_frame(&[p])).unwrap().unwrap();
1104 assert_eq!(tx.avcc().unwrap(), &avcc_v1);
1105 let mut expected = BytesMut::new();
1106 expected.extend_from_slice(&(p.len() as u32).to_be_bytes());
1107 expected.extend_from_slice(p);
1108 assert_eq!(out.as_ref(), expected.as_ref());
1109 }
1110
1111 fn decode_avcc(bytes: &Bytes) -> mp4_atom::Avcc {
1112 use mp4_atom::Atom;
1113 mp4_atom::Avcc::decode_body(&mut std::io::Cursor::new(bytes.as_ref())).unwrap()
1114 }
1115
1116 #[test]
1117 fn catalog_avcc_baseline_has_no_extension() {
1118 let h264 = hang::catalog::H264 {
1119 profile: 0x42,
1120 constraints: 0xc0,
1121 level: 0x1f,
1122 inline: true,
1123 };
1124 let avcc = decode_avcc(&catalog_avcc(&h264).unwrap());
1125 assert_eq!(avcc.avc_profile_indication, 0x42);
1126 assert_eq!(avcc.profile_compatibility, 0xc0);
1127 assert_eq!(avcc.avc_level_indication, 0x1f);
1128 assert_eq!(avcc.length_size, 4);
1129 assert!(avcc.sequence_parameter_sets.is_empty());
1130 assert!(avcc.picture_parameter_sets.is_empty());
1131 assert!(avcc.ext.is_none());
1132 }
1133
1134 #[test]
1135 fn catalog_avcc_high_states_420_8bit() {
1136 let h264 = hang::catalog::H264 {
1137 profile: 100,
1138 constraints: 0,
1139 level: 0x28,
1140 inline: true,
1141 };
1142 let avcc = decode_avcc(&catalog_avcc(&h264).unwrap());
1143 assert_eq!(avcc.avc_profile_indication, 100);
1144 assert!(avcc.sequence_parameter_sets.is_empty());
1145 assert_eq!(
1146 avcc.ext,
1147 Some(mp4_atom::AvccExt {
1148 chroma_format: 1,
1149 bit_depth_luma: 8,
1150 bit_depth_chroma: 8,
1151 sequence_parameter_sets_ext: Vec::new(),
1152 })
1153 );
1154 }
1155
1156 #[test]
1157 fn catalog_avcc_refuses_profiles_the_string_cannot_describe() {
1158 for profile in [110, 122, 244, 44, 144] {
1159 let h264 = hang::catalog::H264 {
1160 profile,
1161 constraints: 0,
1162 level: 0x1f,
1163 inline: true,
1164 };
1165 assert!(catalog_avcc(&h264).is_none(), "profile {profile}");
1166 }
1167 let out_of_band = hang::catalog::H264 {
1168 profile: 0x42,
1169 constraints: 0xc0,
1170 level: 0x1f,
1171 inline: false,
1172 };
1173 assert!(catalog_avcc(&out_of_band).is_none());
1174 }
1175}