forge
Explore
Log in

Don't you dare go Hollow

An H.264 mkv opens like any other file

Browse files at this commit

87953e0bc07928b103e4f263424c601856a88e5bAhmet Kaan GümüşParent: 88fbed0
  • feat
    • an H.264 mkv opens like any other file
Show full message
✨ feat(demux): an H.264 mkv opens like any other file

Matroska carried the codec this project decodes best and refused it at the
door: only V_AV1 had an arm. The avcC in CodecPrivate is the same record an
mp4 carries, so the parameter sets come out of it and the length-prefixed
blocks are reframed to Annex-B behind them -- the H.264 dispatch below is
untouched, and so is the AV1 path, whose blocks still go over as they lie.
crates/engine/src/demux.rsmodified+126 -21
@@ -291,7 +291,7 @@ struct Block {
291291 key: bool,
292292 }
293293
294-/// AV1 out of a Matroska file (`.mkv`/`.webm`).
294+/// AV1 or H.264 out of a Matroska file (`.mkv`/`.webm`).
295295 ///
296296 /// The whole segment is walked once at open -- element *headers* only, the block
297297 /// payloads are seeked over -- because Matroska carries no sample table: the
@@ -305,7 +305,12 @@ pub struct MkvDemuxer {
305305 /// repeats its sequence header at every keyframe anyway, and cros-codecs
306306 /// ignores one identical to the sequence in force (`av1.rs:381`), so this is
307307 /// free when the encoder already wrote one and load-bearing when it did not.
308+ /// For H.264 it is the Annex-B SPS/PPS out of `avcC` instead, re-injected the
309+ /// same way and for the same reason.
308310 config: Vec<u8>,
311+ /// Bytes of the NAL length prefix an H.264 block is written with, off
312+ /// `avcC`. Zero for AV1, whose blocks are handed over as they lie.
313+ nal_length: usize,
309314 next: usize,
310315 }
311316
@@ -316,11 +321,15 @@ impl MkvDemuxer {
316321 let segment = mkv_segment(&mut file, end)?;
317322 let (video, _) = mkv_tracks(&mut file, segment)?;
318323 let video = video.ok_or(
319- "no AV1 video track in this Matroska file — AV1 is the only codec read from one",
324+ "no AV1 or H.264 video track in this Matroska file — those are the codecs read from one",
320325 )?;
321326 let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;
322327 if blocks.is_empty() {
323- return Err("the AV1 track in this Matroska file has no frames".into());
328+ return Err(format!(
329+ "the {} track in this Matroska file has no frames",
330+ video.codec.name()
331+ )
332+ .into());
324333 }
325334 // Timing, in this order: what the track declares, then what its own
326335 // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333
@@ -350,7 +359,7 @@ impl MkvDemuxer {
350359 height: video.height,
351360 frame_rate,
352361 frame_count: blocks.len() as u32,
353- codec: Codec::Av1,
362+ codec: video.codec,
354363 };
355364 Ok((
356365 meta,
@@ -358,6 +367,7 @@ impl MkvDemuxer {
358367 file,
359368 blocks,
360369 config: video.config,
370+ nal_length: video.nal_length,
361371 next: 0,
362372 },
363373 ))
@@ -369,6 +379,17 @@ impl MkvDemuxer {
369379 };
370380 self.next += 1;
371381 let head = if block.key { self.config.len() } else { 0 };
382+ // An H.264 block is `avcC`-framed like an mp4 sample, so it is reframed
383+ // to Annex-B behind the parameter sets exactly as `Mp4Demuxer` does. An
384+ // AV1 one is a temporal unit already and goes over as it lies, below.
385+ if self.nal_length > 0 {
386+ let mut block_bytes = vec![0u8; block.len];
387+ read_exact_at(&mut self.file, block.at, &mut block_bytes)?;
388+ let mut au = Vec::with_capacity(head + block.len + 16);
389+ au.extend_from_slice(&self.config[..head]);
390+ append_annex_b(&block_bytes, self.nal_length, &mut au)?;
391+ return Ok(Some(au));
392+ }
372393 let mut au = vec![0u8; head + block.len];
373394 au[..head].copy_from_slice(&self.config[..head]);
374395 read_exact_at(&mut self.file, block.at, &mut au[head..])?;
@@ -401,14 +422,16 @@ pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
401422 Ok(mkv_tracks(&mut file, segment)?.1)
402423 }
403424
404-/// What the `Tracks` element says about the AV1 track.
425+/// What the `Tracks` element says about the video track.
405426 struct MkvVideo {
406427 number: u64,
407428 width: u32,
408429 height: u32,
409430 default_duration: Option<u64>,
410431 timestamp_scale: u64,
432+ codec: Codec,
411433 config: Vec<u8>,
434+ nal_length: usize,
412435 }
413436
414437 // Matroska element IDs, written with the leading length marker they carry in
@@ -490,8 +513,8 @@ fn mkv_tracks(
490513 Ok((video, audio))
491514 }
492515
493-/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id
494-/// of an audio track otherwise.
516+/// One `TrackEntry`: `Some` video only for an 8-bit AV1 or an H.264 track, and
517+/// the codec id of an audio track otherwise.
495518 fn mkv_track_entry(
496519 file: &mut File,
497520 body: u64,
@@ -528,21 +551,72 @@ fn mkv_track_entry(
528551 at = stop;
529552 }
530553 // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.
531- match (kind, codec.as_str()) {
532- (1, "V_AV1") => Ok((
533- Some(MkvVideo {
534- number,
535- width,
536- height,
537- default_duration,
538- timestamp_scale,
539- config: parse_av1c(&config)?,
540- }),
541- None,
542- )),
543- (2, _) => Ok((None, Some(codec))),
544- _ => Ok((None, None)),
554+ let (codec, config, nal_length) = match (kind, codec.as_str()) {
555+ (1, "V_AV1") => (Codec::Av1, parse_av1c(&config)?, 0),
556+ // The same `avcC` an mp4 carries, `CodecPrivate` being where Matroska
557+ // puts it: length-prefixed blocks and the SPS/PPS out of the record.
558+ (1, "V_MPEG4/ISO/AVC") => {
559+ let (nal_length, sets) = parse_avcc(&config)?;
560+ (Codec::H264, sets, nal_length)
561+ }
562+ (2, _) => return Ok((None, Some(codec))),
563+ _ => return Ok((None, None)),
564+ };
565+ Ok((
566+ Some(MkvVideo {
567+ number,
568+ width,
569+ height,
570+ default_duration,
571+ timestamp_scale,
572+ codec,
573+ config,
574+ nal_length,
575+ }),
576+ None,
577+ ))
578+}
579+
580+/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length
581+/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s
582+/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a
583+/// Matroska file carries the identical record in `CodecPrivate`, unparsed.
584+fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
585+ // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets.
586+ let (&flags, &sps_count) = rec
587+ .get(4)
588+ .zip(rec.get(5))
589+ .ok_or("avcC record shorter than its fixed header")?;
590+ let mut sets = Vec::new();
591+ let mut src = &rec[6..];
592+ // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS
593+ // array, whose count is a byte of its own.
594+ let mut count = usize::from(sps_count & 0x1f);
595+ for array in 0..2 {
596+ if array == 1 {
597+ let (&pps_count, rest) = src
598+ .split_first()
599+ .ok_or("avcC record ends before its PPS count")?;
600+ count = usize::from(pps_count);
601+ src = rest;
602+ }
603+ for _ in 0..count {
604+ let len = usize::from(u16::from_be_bytes(
605+ src.get(..2)
606+ .ok_or("avcC NAL length past the record")?
607+ .try_into()
608+ .unwrap(),
609+ ));
610+ let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?;
611+ sets.extend_from_slice(&START_CODE);
612+ sets.extend_from_slice(nal);
613+ src = &src[2 + len..];
614+ }
545615 }
616+ if sets.is_empty() {
617+ return Err("avcC record carries no SPS/PPS".into());
618+ }
619+ Ok((usize::from(flags & 0x3) + 1, sets))
546620 }
547621
548622 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
@@ -1073,6 +1147,37 @@ mod tests {
10731147 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
10741148 }
10751149
1150+ /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS
1151+ /// count is five bits of byte 5, the PPS count a byte of its own, and taking
1152+ /// the second for the first is the mistake this checks against.
1153+ #[test]
1154+ fn reads_parameter_sets_out_of_an_avcc_record() {
1155+ let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2];
1156+ for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] {
1157+ rec.extend_from_slice(&2u16.to_be_bytes());
1158+ rec.extend_from_slice(&[kind, nal]);
1159+ }
1160+ rec.push(1); // numOfPictureParameterSets
1161+ rec.extend_from_slice(&2u16.to_be_bytes());
1162+ rec.extend_from_slice(&[8, 0xCC]);
1163+
1164+ let (len, sets) = parse_avcc(&rec).unwrap();
1165+ assert_eq!(len, 2, "lengthSizeMinusOne == 1");
1166+ assert_eq!(
1167+ sets,
1168+ [
1169+ 0, 0, 0, 1, 7, 0xAA, // SPS
1170+ 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses
1171+ 0, 0, 0, 1, 8, 0xCC, // PPS
1172+ ]
1173+ );
1174+ // Nothing is read past the end of a truncated record, and a Matroska
1175+ // file with no `CodecPrivate` at all is refused rather than started.
1176+ assert!(parse_avcc(&rec[..5]).is_err());
1177+ assert!(parse_avcc(&rec[..rec.len() - 1]).is_err());
1178+ assert!(parse_avcc(&[]).is_err());
1179+ }
1180+
10761181 /// EBML's variable-length integers, which every Matroska read starts with:
10771182 /// the leading zeros of the first byte are the length, an *id* keeps its
10781183 /// marker bit and a *size* loses it, and an all-ones size is "unknown".
crates/engine/tests/h264_mkv.rsadded+143 -0
@@ -0,0 +1,143 @@
1+//! H.264 in Matroska: the codec this project has always decoded, in the
2+//! container that used to refuse it by name. Nothing new decodes here -- the
3+//! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the
4+//! same dispatch an mp4's samples go to -- so the whole file runs with nothing
5+//! installed, on `rusty_h264` if the plugin is absent.
6+//!
7+//! ```text
8+//! cargo test -p engine --test h264_mkv
9+//! ```
10+
11+use std::path::PathBuf;
12+use std::time::{Duration, Instant};
13+
14+use engine::demux::{Codec, Demuxer};
15+use engine::{AudioSession, PlaybackSession};
16+
17+/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`.
18+const FRAMES: u32 = 60;
19+const KEYFRAME: u32 = 30;
20+
21+fn asset(name: &str) -> PathBuf {
22+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
23+ .join("../../assets")
24+ .join(name)
25+}
26+
27+/// The Annex-B NAL types of an access unit, in order: `nal_unit_type` is the low
28+/// 5 bits of the byte after each start code.
29+fn nal_types(au: &[u8]) -> Vec<u8> {
30+ au.windows(4)
31+ .enumerate()
32+ .filter(|(_, w)| *w == [0, 0, 0, 1])
33+ .filter_map(|(i, _)| au.get(i + 4).map(|b| b & 0x1f))
34+ .collect()
35+}
36+
37+/// The container half, and the refusal this slice exists to delete: the file
38+/// opens, and it says H.264 rather than "not supported".
39+#[test]
40+fn the_demuxer_reports_an_h264_track_in_matroska() {
41+ let (meta, _) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv");
42+ assert_eq!(meta.codec, Codec::H264);
43+ assert_eq!((meta.width, meta.height), (1280, 720));
44+ assert!(
45+ (meta.frame_rate - 30.0).abs() < 1e-6,
46+ "DefaultDuration must not truncate: {}",
47+ meta.frame_rate
48+ );
49+ assert_eq!(meta.frame_count, FRAMES);
50+
51+ // The invariant, stated as an assert: the other containers and codecs read
52+ // back exactly as they did before this arm existed.
53+ let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
54+ assert_eq!(av1.codec, Codec::Av1);
55+ assert_eq!(av1.frame_count, FRAMES);
56+ let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
57+ assert_eq!(h264.codec, Codec::H264);
58+}
59+
60+/// Matroska stores H.264 in `avcC` framing -- length prefixes, and the SPS/PPS
61+/// out of band in `CodecPrivate` -- so an access unit is only decodable if both
62+/// were handled: reframed to Annex-B, parameter sets ahead of every keyframe.
63+#[test]
64+fn keyframes_carry_the_parameter_sets_and_every_block_comes_back() {
65+ let (_, mut demuxer) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv");
66+ let first = demuxer
67+ .next_access_unit()
68+ .expect("read")
69+ .expect("a first access unit");
70+ assert_eq!(first[..4], [0, 0, 0, 1], "Annex-B, not a length prefix");
71+ let types = nal_types(&first);
72+ assert_eq!(
73+ &types[..2],
74+ &[7, 8],
75+ "the keyframe leads with SPS and PPS: {types:?}"
76+ );
77+ assert!(types.contains(&5), "and then the IDR picture: {types:?}");
78+
79+ let second = demuxer.next_access_unit().expect("read").expect("a unit");
80+ let types = nal_types(&second);
81+ assert!(
82+ !types.contains(&7) && types.contains(&1),
83+ "a non-keyframe is a plain slice: {types:?}"
84+ );
85+
86+ let mut count = 2;
87+ while demuxer.next_access_unit().expect("read").is_some() {
88+ count += 1;
89+ }
90+ assert_eq!(count, FRAMES, "every block came back out");
91+
92+ // Keyed every 30 frames, and a seek may only land on one.
93+ assert_eq!(
94+ demuxer.seek_to_sync_at_or_before(KEYFRAME + 15),
95+ i64::from(KEYFRAME)
96+ );
97+ assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0);
98+ // The unit after a seek carries the parameter sets too: a decoder restarted
99+ // mid-file needs them exactly as much as one started at frame 0.
100+ let after = demuxer.next_access_unit().expect("read").expect("a unit");
101+ assert_eq!(&nal_types(&after)[..2], &[7, 8]);
102+}
103+
104+/// The user-facing end of it, through the very call the window's open door makes
105+/// (`app/src/main.rs:2242`): the file becomes a timeline and that timeline shows
106+/// a picture. No plugin is required -- H.264 is the one codec with a software
107+/// decoder here -- so this is what says the reframed access units are really
108+/// decodable and not just well-shaped.
109+#[test]
110+fn opening_an_h264_matroska_file_shows_frames() {
111+ let mut session = PlaybackSession::open(asset("test_h264.mkv")).expect("open test_h264.mkv");
112+ assert_eq!(session.meta().codec, Codec::H264);
113+ assert_eq!(session.meta().frame_count, FRAMES);
114+
115+ // The decoder is a thread behind the door, so a frame is waited for exactly
116+ // as the window's own pump waits for one.
117+ let deadline = Instant::now() + Duration::from_secs(60);
118+ let frame = loop {
119+ if let Some(frame) = session.try_frame() {
120+ break frame;
121+ }
122+ assert!(Instant::now() < deadline, "no frame in 60 s");
123+ std::thread::sleep(Duration::from_millis(10));
124+ };
125+ assert_eq!((frame.width, frame.height), (1280, 720));
126+ // A picture, not a flat surface: a decoder handed garbage would satisfy
127+ // every count above.
128+ assert!(
129+ frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]),
130+ "the first frame is a single colour -- no picture was decoded"
131+ );
132+}
133+
134+/// The delivered scope, unchanged by this arm: a Matroska file's *sound* is
135+/// still not read, and the notice names the track rather than half-playing it.
136+#[test]
137+fn matroska_audio_is_still_not_wired_and_says_so() {
138+ let reason = AudioSession::unsupported(&asset("test_h264.mkv"))
139+ .expect("unsupported")
140+ .expect("the fixture has an AAC track to name");
141+ assert!(reason.contains("A_AAC"), "{reason}");
142+ assert!(reason.contains("not wired"), "{reason}");
143+}
scripts/gen_fixtures.shmodified+10 -0
@@ -113,6 +113,16 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
113113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115115 -c:a aac -b:a 128k assets/test_av1.mkv
116+# H.264 in Matroska: the same stream the mp4 fixtures carry, in the container
117+# that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing
118+# installed, `-g 30` for the second keyframe the sync index is checked against,
119+# and the AAC track again so the "not wired" audio notice has one to name.
120+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
121+ -f lavfi -i "sine=frequency=440:duration=2" \
122+ -f lavfi -i "sine=frequency=880:duration=2" \
123+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
124+ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \
125+ -c:a aac -b:a 128k assets/test_h264.mkv
116126 # Sync fixture: one flash and one beep, at the same instant. Black picture with
117127 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
118128 # stretch — so a test can find each of them and say how far apart they came out.