diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 00584e7..83466e1 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -291,7 +291,7 @@ struct Block { key: bool, } -/// AV1 out of a Matroska file (`.mkv`/`.webm`). +/// AV1 or H.264 out of a Matroska file (`.mkv`/`.webm`). /// /// The whole segment is walked once at open -- element *headers* only, the block /// payloads are seeked over -- because Matroska carries no sample table: the @@ -305,7 +305,12 @@ pub struct MkvDemuxer { /// repeats its sequence header at every keyframe anyway, and cros-codecs /// ignores one identical to the sequence in force (`av1.rs:381`), so this is /// free when the encoder already wrote one and load-bearing when it did not. + /// For H.264 it is the Annex-B SPS/PPS out of `avcC` instead, re-injected the + /// same way and for the same reason. config: Vec, + /// Bytes of the NAL length prefix an H.264 block is written with, off + /// `avcC`. Zero for AV1, whose blocks are handed over as they lie. + nal_length: usize, next: usize, } @@ -316,11 +321,15 @@ impl MkvDemuxer { let segment = mkv_segment(&mut file, end)?; let (video, _) = mkv_tracks(&mut file, segment)?; let video = video.ok_or( - "no AV1 video track in this Matroska file โ€” AV1 is the only codec read from one", + "no AV1 or H.264 video track in this Matroska file โ€” those are the codecs read from one", )?; let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; if blocks.is_empty() { - return Err("the AV1 track in this Matroska file has no frames".into()); + return Err(format!( + "the {} track in this Matroska file has no frames", + video.codec.name() + ) + .into()); } // Timing, in this order: what the track declares, then what its own // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333 @@ -350,7 +359,7 @@ impl MkvDemuxer { height: video.height, frame_rate, frame_count: blocks.len() as u32, - codec: Codec::Av1, + codec: video.codec, }; Ok(( meta, @@ -358,6 +367,7 @@ impl MkvDemuxer { file, blocks, config: video.config, + nal_length: video.nal_length, next: 0, }, )) @@ -369,6 +379,17 @@ impl MkvDemuxer { }; self.next += 1; let head = if block.key { self.config.len() } else { 0 }; + // An H.264 block is `avcC`-framed like an mp4 sample, so it is reframed + // to Annex-B behind the parameter sets exactly as `Mp4Demuxer` does. An + // AV1 one is a temporal unit already and goes over as it lies, below. + if self.nal_length > 0 { + let mut block_bytes = vec![0u8; block.len]; + read_exact_at(&mut self.file, block.at, &mut block_bytes)?; + let mut au = Vec::with_capacity(head + block.len + 16); + au.extend_from_slice(&self.config[..head]); + append_annex_b(&block_bytes, self.nal_length, &mut au)?; + return Ok(Some(au)); + } let mut au = vec![0u8; head + block.len]; au[..head].copy_from_slice(&self.config[..head]); read_exact_at(&mut self.file, block.at, &mut au[head..])?; @@ -401,14 +422,16 @@ pub fn matroska_audio_codec(path: &Path) -> crate::Result> { Ok(mkv_tracks(&mut file, segment)?.1) } -/// What the `Tracks` element says about the AV1 track. +/// What the `Tracks` element says about the video track. struct MkvVideo { number: u64, width: u32, height: u32, default_duration: Option, timestamp_scale: u64, + codec: Codec, config: Vec, + nal_length: usize, } // Matroska element IDs, written with the leading length marker they carry in @@ -490,8 +513,8 @@ fn mkv_tracks( Ok((video, audio)) } -/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id -/// of an audio track otherwise. +/// One `TrackEntry`: `Some` video only for an 8-bit AV1 or an H.264 track, and +/// the codec id of an audio track otherwise. fn mkv_track_entry( file: &mut File, body: u64, @@ -528,21 +551,72 @@ fn mkv_track_entry( at = stop; } // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here. - match (kind, codec.as_str()) { - (1, "V_AV1") => Ok(( - Some(MkvVideo { - number, - width, - height, - default_duration, - timestamp_scale, - config: parse_av1c(&config)?, - }), - None, - )), - (2, _) => Ok((None, Some(codec))), - _ => Ok((None, None)), + let (codec, config, nal_length) = match (kind, codec.as_str()) { + (1, "V_AV1") => (Codec::Av1, parse_av1c(&config)?, 0), + // The same `avcC` an mp4 carries, `CodecPrivate` being where Matroska + // puts it: length-prefixed blocks and the SPS/PPS out of the record. + (1, "V_MPEG4/ISO/AVC") => { + let (nal_length, sets) = parse_avcc(&config)?; + (Codec::H264, sets, nal_length) + } + (2, _) => return Ok((None, Some(codec))), + _ => return Ok((None, None)), + }; + Ok(( + Some(MkvVideo { + number, + width, + height, + default_duration, + timestamp_scale, + codec, + config, + nal_length, + }), + None, + )) +} + +/// AVCDecoderConfigurationRecord (ISO 14496-15 ยง5.3.3.1) -> the NAL length +/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s +/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a +/// Matroska file carries the identical record in `CodecPrivate`, unparsed. +fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec)> { + // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets. + let (&flags, &sps_count) = rec + .get(4) + .zip(rec.get(5)) + .ok_or("avcC record shorter than its fixed header")?; + let mut sets = Vec::new(); + let mut src = &rec[6..]; + // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS + // array, whose count is a byte of its own. + let mut count = usize::from(sps_count & 0x1f); + for array in 0..2 { + if array == 1 { + let (&pps_count, rest) = src + .split_first() + .ok_or("avcC record ends before its PPS count")?; + count = usize::from(pps_count); + src = rest; + } + for _ in 0..count { + let len = usize::from(u16::from_be_bytes( + src.get(..2) + .ok_or("avcC NAL length past the record")? + .try_into() + .unwrap(), + )); + let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?; + sets.extend_from_slice(&START_CODE); + sets.extend_from_slice(nal); + src = &src[2 + len..]; + } } + if sets.is_empty() { + return Err("avcC record carries no SPS/PPS".into()); + } + Ok((usize::from(flags & 0x3) + 1, sets)) } /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF @@ -1073,6 +1147,37 @@ mod tests { assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); } + /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS + /// count is five bits of byte 5, the PPS count a byte of its own, and taking + /// the second for the first is the mistake this checks against. + #[test] + fn reads_parameter_sets_out_of_an_avcc_record() { + let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2]; + for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] { + rec.extend_from_slice(&2u16.to_be_bytes()); + rec.extend_from_slice(&[kind, nal]); + } + rec.push(1); // numOfPictureParameterSets + rec.extend_from_slice(&2u16.to_be_bytes()); + rec.extend_from_slice(&[8, 0xCC]); + + let (len, sets) = parse_avcc(&rec).unwrap(); + assert_eq!(len, 2, "lengthSizeMinusOne == 1"); + assert_eq!( + sets, + [ + 0, 0, 0, 1, 7, 0xAA, // SPS + 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses + 0, 0, 0, 1, 8, 0xCC, // PPS + ] + ); + // Nothing is read past the end of a truncated record, and a Matroska + // file with no `CodecPrivate` at all is refused rather than started. + assert!(parse_avcc(&rec[..5]).is_err()); + assert!(parse_avcc(&rec[..rec.len() - 1]).is_err()); + assert!(parse_avcc(&[]).is_err()); + } + /// EBML's variable-length integers, which every Matroska read starts with: /// the leading zeros of the first byte are the length, an *id* keeps its /// marker bit and a *size* loses it, and an all-ones size is "unknown". diff --git a/crates/engine/tests/h264_mkv.rs b/crates/engine/tests/h264_mkv.rs new file mode 100644 index 0000000..78728f4 --- /dev/null +++ b/crates/engine/tests/h264_mkv.rs @@ -0,0 +1,143 @@ +//! H.264 in Matroska: the codec this project has always decoded, in the +//! container that used to refuse it by name. Nothing new decodes here -- the +//! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the +//! same dispatch an mp4's samples go to -- so the whole file runs with nothing +//! installed, on `rusty_h264` if the plugin is absent. +//! +//! ```text +//! cargo test -p engine --test h264_mkv +//! ``` + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::demux::{Codec, Demuxer}; +use engine::{AudioSession, PlaybackSession}; + +/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`. +const FRAMES: u32 = 60; +const KEYFRAME: u32 = 30; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The Annex-B NAL types of an access unit, in order: `nal_unit_type` is the low +/// 5 bits of the byte after each start code. +fn nal_types(au: &[u8]) -> Vec { + au.windows(4) + .enumerate() + .filter(|(_, w)| *w == [0, 0, 0, 1]) + .filter_map(|(i, _)| au.get(i + 4).map(|b| b & 0x1f)) + .collect() +} + +/// The container half, and the refusal this slice exists to delete: the file +/// opens, and it says H.264 rather than "not supported". +#[test] +fn the_demuxer_reports_an_h264_track_in_matroska() { + let (meta, _) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv"); + assert_eq!(meta.codec, Codec::H264); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!( + (meta.frame_rate - 30.0).abs() < 1e-6, + "DefaultDuration must not truncate: {}", + meta.frame_rate + ); + assert_eq!(meta.frame_count, FRAMES); + + // The invariant, stated as an assert: the other containers and codecs read + // back exactly as they did before this arm existed. + let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); + assert_eq!(av1.codec, Codec::Av1); + assert_eq!(av1.frame_count, FRAMES); + let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4"); + assert_eq!(h264.codec, Codec::H264); +} + +/// Matroska stores H.264 in `avcC` framing -- length prefixes, and the SPS/PPS +/// out of band in `CodecPrivate` -- so an access unit is only decodable if both +/// were handled: reframed to Annex-B, parameter sets ahead of every keyframe. +#[test] +fn keyframes_carry_the_parameter_sets_and_every_block_comes_back() { + let (_, mut demuxer) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv"); + let first = demuxer + .next_access_unit() + .expect("read") + .expect("a first access unit"); + assert_eq!(first[..4], [0, 0, 0, 1], "Annex-B, not a length prefix"); + let types = nal_types(&first); + assert_eq!( + &types[..2], + &[7, 8], + "the keyframe leads with SPS and PPS: {types:?}" + ); + assert!(types.contains(&5), "and then the IDR picture: {types:?}"); + + let second = demuxer.next_access_unit().expect("read").expect("a unit"); + let types = nal_types(&second); + assert!( + !types.contains(&7) && types.contains(&1), + "a non-keyframe is a plain slice: {types:?}" + ); + + let mut count = 2; + while demuxer.next_access_unit().expect("read").is_some() { + count += 1; + } + assert_eq!(count, FRAMES, "every block came back out"); + + // Keyed every 30 frames, and a seek may only land on one. + assert_eq!( + demuxer.seek_to_sync_at_or_before(KEYFRAME + 15), + i64::from(KEYFRAME) + ); + assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0); + // The unit after a seek carries the parameter sets too: a decoder restarted + // mid-file needs them exactly as much as one started at frame 0. + let after = demuxer.next_access_unit().expect("read").expect("a unit"); + assert_eq!(&nal_types(&after)[..2], &[7, 8]); +} + +/// The user-facing end of it, through the very call the window's open door makes +/// (`app/src/main.rs:2242`): the file becomes a timeline and that timeline shows +/// a picture. No plugin is required -- H.264 is the one codec with a software +/// decoder here -- so this is what says the reframed access units are really +/// decodable and not just well-shaped. +#[test] +fn opening_an_h264_matroska_file_shows_frames() { + let mut session = PlaybackSession::open(asset("test_h264.mkv")).expect("open test_h264.mkv"); + assert_eq!(session.meta().codec, Codec::H264); + assert_eq!(session.meta().frame_count, FRAMES); + + // The decoder is a thread behind the door, so a frame is waited for exactly + // as the window's own pump waits for one. + let deadline = Instant::now() + Duration::from_secs(60); + let frame = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + assert!(Instant::now() < deadline, "no frame in 60 s"); + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!((frame.width, frame.height), (1280, 720)); + // A picture, not a flat surface: a decoder handed garbage would satisfy + // every count above. + assert!( + frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]), + "the first frame is a single colour -- no picture was decoded" + ); +} + +/// The delivered scope, unchanged by this arm: a Matroska file's *sound* is +/// still not read, and the notice names the track rather than half-playing it. +#[test] +fn matroska_audio_is_still_not_wired_and_says_so() { + let reason = AudioSession::unsupported(&asset("test_h264.mkv")) + .expect("unsupported") + .expect("the fixture has an AAC track to name"); + assert!(reason.contains("A_AAC"), "{reason}"); + assert!(reason.contains("not wired"), "{reason}"); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 12106b6..76bcc2c 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -113,6 +113,16 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av1.mkv +# H.264 in Matroska: the same stream the mp4 fixtures carry, in the container +# that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing +# installed, `-g 30` for the second keyframe the sync index is checked against, +# and the AAC track again so the "not wired" audio notice has one to name. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_h264.mkv # Sync fixture: one flash and one beep, at the same instant. Black picture with # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that # stretch โ€” so a test can find each of them and say how far apart they came out.