From 4f4dcb4470b562ebbd04c16d70195327ecf3071c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 05:48:30 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(demux):=20a=20codec's=20supp?= =?UTF-8?q?ort=20is=20probed=20per=20container,=20not=20inferred=20from=20?= =?UTF-8?q?a=20neighbour?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit VP9 was decodable out of an mp4 and refused out of a .webm — `V_VP9` fell through the Matroska track dispatch into `OtherVideo` and came back as "V_VP9 video in a Matroska file is not supported", with the VA-API VP9 decoder wired in `engine-hw` the whole time. A browser-downloaded .mkv was one of those files. Both dispatches now read one table (`CODEC_IDS`), and the Matroska arm matches on `Codec` with no wildcard, so a codec added to the enum fails to compile until it has been routed rather than falling through to a refusal. A cell that is deliberately absent is a row in `UNSUPPORTED` with a reason, and the refusal quotes that reason instead of listing what is supported and leaving the user to guess. The mp4 video track comes out of `moov.traks` in file order, not a `HashMap` walk of `Mp4Reader::tracks()`: a file with two video tracks opened on a different picture from one run to the next, and a saved .edith reopened on the other one. `audio::audio_track_ids` fixed the same trap for sound; the naming half of `AudioSession::unsupported` had it too. VP9 states its bit depth in no container record — an mkv `TrackEntry` carries none and an mp4's `vpcC` is optional — so it is read off the first keyframe's uncompressed header. Assumed 8-bit, a profile 2 stream would decode into an NV12 pool and come back as garbage; 12-bit is refused by name like 12-bit AV1 and HEVC. The audio refusals said "AAC and AC-3 only" long after FLAC, MP3, Vorbis, ALAC and PCM decoded out of a Matroska file. They name the real set now, per container, because an mp4 video's sound never reaches symphonia and reads fewer codecs than an mkv does. tests/capability_matrix.rs holds all of it against real files. --- crates/engine-hw/src/lib.rs | 10 +- crates/engine/examples/probe_fps.rs | 53 +-- crates/engine/src/audio.rs | 40 ++- crates/engine/src/demux.rs | 407 ++++++++++++++++++++--- crates/engine/tests/capability_matrix.rs | 168 ++++++++++ scripts/gen_fixtures.sh | 35 ++ 6 files changed, 627 insertions(+), 86 deletions(-) create mode 100644 crates/engine/tests/capability_matrix.rs diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 1f884b4..0ded8cf 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -59,8 +59,8 @@ type Handle = as StatelessVideoDecoder>::Handle; /// still loads and still decodes H.264 (it simply refuses the newer codecs' /// files at `Demuxer`). /// -/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main at -/// either depth. +/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0 and 2, AV1 +/// Main at either depth. /// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit /// I420 every frame here is ([`Session::emit`]). /// @@ -68,8 +68,10 @@ type Handle = as StatelessVideoDecoder>::Handle; /// interface all the way to the renderer. That costs the low two bits of a Main /// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every /// stage between here and the texture upload, not to this file. -/// VP9 profile 2 is still refused by `Demuxer`: a VP9 stream does not state its -/// depth where that reads it (an `av1C` and an `hvcC` both do). +/// VP9 profile 2 reaches the P010 pool like the rest: a VP9 stream states its +/// depth in no container record the way an `av1C` or an `hvcC` does, so +/// `Demuxer` reads it off the first keyframe's uncompressed header +/// (`demux::vp9_bit_depth`) rather than assuming the 8 bits of profile 0. enum Decoder { H264(Dec), Hevc(Dec), diff --git a/crates/engine/examples/probe_fps.rs b/crates/engine/examples/probe_fps.rs index defc078..8680df3 100644 --- a/crates/engine/examples/probe_fps.rs +++ b/crates/engine/examples/probe_fps.rs @@ -2,11 +2,11 @@ //! frame the master clock asks for ten minutes in -- the arithmetic behind A/V //! desync on NTSC-rate files, on a file too big to keep as a fixture. //! -//! `cargo run --release -p engine --example probe_fps -- [secs] [play]` +//! `cargo run --release -p engine --example probe_fps -- [secs] [play] [play_secs]` //! -//! With `play` it also seeks there, plays two seconds against the real audio -//! device and reports the skew between the picture on screen and the master -//! clock -- the machine-checkable half of "lip sync holds". +//! With `play` it also seeks there, plays `play_secs` (two by default) against the +//! real audio device and reports the skew between the picture on screen and the +//! master clock -- the machine-checkable half of "lip sync holds". use std::path::PathBuf; use std::time::{Duration, Instant}; @@ -36,7 +36,34 @@ fn main() { secs * (meta.frame_rate - 23.0) ); // Straight from the container, to show what the demuxer's frame 0 skipped. - let file = std::fs::File::open(&path).expect("open"); + // mp4 only: a Matroska file has no `moov` and reading one out of it is a + // panic, which used to make this tool unusable on exactly the films in a + // library that the demuxer most needs checking against. + if !engine::demux::is_matroska(&path) { + mp4_boxes(&path); + } + match engine::AudioSession::open(&path) { + Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels), + Ok(None) => println!( + " audio: none usable ({:?})", + engine::AudioSession::unsupported(&path) + ), + Err(e) => println!(" audio: refused ({e})"), + } + + // `play [secs]`: how long to play for, two seconds by default. + if args.next().is_some_and(|a| a == *"play") { + let seconds = args + .next() + .and_then(|s| s.to_str().and_then(|s| s.parse().ok())) + .unwrap_or(2.0); + play(&path, secs, meta.frame_rate, seconds); + } +} + +/// The edit list and sample counts of an mp4, per track. +fn mp4_boxes(path: &std::path::Path) { + let file = std::fs::File::open(path).expect("open"); let size = file.metadata().expect("stat").len(); let reader = mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("read header"); @@ -76,31 +103,19 @@ fn main() { track.sample_count(), ); } - match engine::AudioSession::open(&path) { - Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels), - Ok(None) => println!( - " audio: none usable ({:?})", - engine::AudioSession::unsupported(&path) - ), - Err(e) => println!(" audio: refused ({e})"), - } - - if args.next().is_some_and(|a| a == *"play") { - play(&path, secs, meta.frame_rate); - } } /// Seeks in, plays two seconds against the real device, and reports where the /// picture stands against the master clock. The clock counts audio samples, so /// `frame / fps - clock` *is* the A/V skew: a truncated frame rate shows up /// here as tens of seconds of it, ten minutes in. -fn play(path: &std::path::Path, secs: f64, fps: f64) { +fn play(path: &std::path::Path, secs: f64, fps: f64, seconds: f64) { let mut session = engine::PlaybackSession::open(path).expect("open for playback"); session.seek(secs); session.play(); let mut last = None; let mut held: Option = None; - let deadline = Instant::now() + Duration::from_secs(2); + let deadline = Instant::now() + Duration::from_secs_f64(seconds); while Instant::now() < deadline { session.tick(); // The app's own drop-when-behind rule (`Player::pump`): show every frame diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index bb2cc16..80db4b7 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -61,6 +61,23 @@ const DEFAULT_PRIMING: u64 = 1024; /// An edit list entry that only shifts the timeline, carrying no media. const EMPTY_EDIT: u64 = u32::MAX as u64; +/// What the sound of a *Matroska* file is read with, named for a refusal: +/// symphonia's registry as this project enables it (see the feature list in +/// `Cargo.toml`) plus the AC-3 family, which no symphonia version carries and +/// `oxideav-ac3` does ([`MkvAc3Track`]). +/// +/// Written down per container because capability is not one set: an mp4 video's +/// sound never reaches symphonia ([`Track::open`] answers before it), so it +/// reads fewer codecs than a Matroska file does. Both strings were "AAC only" +/// long after that stopped being true, which is how a user came to re-encode a +/// film whose FLAC track already played; `capability_matrix` opens one file per +/// codec named here. +const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, PCM and Vorbis"; + +/// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video +/// file's sound is read and where it stops. +const MP4_DECODED: &str = "AAC-LC and AC-3/E-AC-3"; + /// Packets decoded and thrown away ahead of a seek target: one for the MDCT /// overlap-add that reconstructs the target packet, one to warm the decoder. const PRE_ROLL: u32 = 2; @@ -653,8 +670,8 @@ impl AudioSession { } /// Why [`open`](Self::open) came back silent for a file that *has* sound: - /// `Some(reason)` when there is an audio track and it is not the AAC-LC - /// this decodes (an AC-3 remux, say). `None` when the file is simply silent + /// `Some(reason)` when there is an audio track in a codec this does not + /// decode (an Opus web rip, say). `None` when the file is simply silent /// -- nothing to tell the user there. Header only, and only worth calling /// once the open has already returned no audio. pub fn unsupported(path: impl AsRef) -> crate::Result> { @@ -674,7 +691,7 @@ impl AudioSession { return Ok(Some(match MkvAc3Track::open(path.as_ref()) { Ok(Some(_)) => return Ok(None), Ok(None) => format!( - "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" + "the {codec} track of this Matroska file cannot be decoded — {MKV_DECODED} are" ), Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), })); @@ -682,14 +699,19 @@ impl AudioSession { let file = File::open(path.as_ref())?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; - Ok(reader - .tracks() - .values() - .find(|t| matches!(t.track_type(), Ok(TrackType::Audio))) + // File order, out of `moov.traks`: naming a codec off a `HashMap` walk + // would tell the user about a different track from one run to the next + // on a film with two ([`audio_track_ids`], and the same trap the video + // pick had in `demux::Mp4Demuxer::open`). + Ok(audio_track_ids(&reader) + .first() + .and_then(|id| reader.tracks().get(id)) .map(|t| match t.media_type() { - Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"), + Ok(media) => { + format!("the {media} audio track cannot be decoded — {MP4_DECODED} are") + } Err(_) => { - "the audio track is in a codec we cannot decode (AAC-LC only)".to_string() + format!("the audio track is in a codec we cannot decode — {MP4_DECODED} are") } })) } diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index ac08cbe..26bc301 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -16,7 +16,7 @@ use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::Path; -use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType}; +use mp4::{Mp4Reader, Mp4Track, TrackType}; use crate::audio::{edit_media_time, packet_at, stts_pairs}; use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags}; @@ -67,6 +67,65 @@ impl Codec { } } +/// The capability matrix: every [`Codec`] the decoder layer can be handed, with +/// the id that names it in each container -- the Matroska `CodecID` and the mp4 +/// `stsd` sample entry fourcc. Both dispatches read *this*, so a codec is +/// reachable from both containers or from neither, never from one because +/// somebody wrote an arm and forgot its twin (VP9 was exactly that: decoded out +/// of an mp4, refused out of a `.webm`, with the VA-API decoder wired all along). +/// +/// A cell that is deliberately absent is a row in [`UNSUPPORTED`] with a reason, +/// never a silent fall-through; `every_codec_is_reachable_from_both_containers` +/// holds both halves. +const CODEC_IDS: &[(Codec, &str, &[u8; 4])] = &[ + (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"), + (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"), + (Codec::Vp9, "V_VP9", b"vp09"), + (Codec::Av1, "V_AV1", b"av01"), +]; + +/// The written-down gaps: container ids -- a Matroska `CodecID` or a four-byte +/// mp4 fourcc -- this reads no picture out of, and why. Asserted to be genuinely +/// unreachable by the same test that asserts [`CODEC_IDS`] is reachable, so a gap +/// that gets closed has to be moved out of here rather than left lying as a false +/// claim. +const UNSUPPORTED: &[(&str, &str)] = &[ + // The mp4 path re-injects the parameter sets out of the `avcC` ahead of + // every sync sample and has nothing to inject for an `avc3` track, which + // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all + // either, so `sequence_parameter_set()` would come back empty-handed. + ("avc3", "H.264 with parameter sets in-band only"), + ("vp08", "no VP8 decoder: cros-codecs carries none"), + ("V_VP8", "no VP8 decoder: cros-codecs carries none"), + ("V_MPEG2", "no MPEG-2 decoder, hardware or software"), + ( + "V_MS/VFW/FOURCC", + "a codec inside a BITMAPINFOHEADER; nothing here unwraps one", + ), +]; + +/// Which codec a Matroska `CodecID` names, or `None` for a track this reads no +/// picture out of. The mkv half of [`CODEC_IDS`]. +fn mkv_codec(id: &str) -> Option { + CODEC_IDS + .iter() + .find(|(_, mkv, _)| *mkv == id) + .map(|&(codec, ..)| codec) +} + +/// Which codec an mp4 `stsd` sample entry fourcc names. The mp4 half of +/// [`CODEC_IDS`], plus `hev1`: HEVC arrives under either fourcc and the record +/// the parameter sets come out of is the same `hvcC` either way. +fn mp4_codec(fourcc: &[u8; 4]) -> Option { + if fourcc == b"hev1" { + return Some(Codec::Hevc); + } + CODEC_IDS + .iter() + .find(|(_, _, mp4)| *mp4 == fourcc) + .map(|&(codec, ..)| codec) +} + #[derive(Debug, Clone, Copy, PartialEq)] pub struct VideoMeta { pub width: u32, @@ -98,6 +157,7 @@ impl Demuxer { (meta, Self::Mp4(mp4)) }; demuxer.fill_sei_light(); + demuxer.fill_vp9_depth()?; Ok((meta, demuxer)) } @@ -146,6 +206,42 @@ impl Demuxer { } } + /// The bitstream tier of [`Self::bit_depth`] for VP9, which is *all* of it: + /// an HEVC track states its depth in an `hvcC` and an AV1 one in an `av1C`, + /// and a VP9 track states it nowhere either demuxer reads -- a Matroska + /// `TrackEntry` carries no configuration record at all, and the `vpcC` an mp4 + /// writes is optional and describes the file rather than the frame. So it is + /// read where it is always true: the uncompressed header of the first + /// keyframe, which is what [`vp9_bit_depth`] parses. + /// + /// Assuming 8 instead is how a profile 2 stream would decode into an NV12 + /// pool and come back as garbage -- the plugin picks its surface pool off + /// this number ([`crate::hw`]). + fn fill_vp9_depth(&mut self) -> crate::Result<()> { + let codec = match self { + Self::Mp4(d) => d.codec, + Self::Mkv(d) => d.codec, + }; + if codec != Codec::Vp9 { + return Ok(()); + } + let first = self.next_access_unit(); + self.seek_to_sync_at_or_before(0); + let Ok(Some(au)) = first else { + return Ok(()); + }; + // A 12-bit stream is refused by name here, exactly as a 12-bit AV1 is in + // `parse_av1c`: the plugin has an NV12 pool and a P010 one and no third. + let Some(depth) = vp9_bit_depth(&au)? else { + return Ok(()); + }; + match self { + Self::Mp4(d) => d.bit_depth = depth, + Self::Mkv(d) => d.bit_depth = depth, + } + Ok(()) + } + /// Next access unit in decode order, `None` at end of track. pub fn next_access_unit(&mut self) -> crate::Result>> { match self { @@ -221,35 +317,39 @@ impl Mp4Demuxer { let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; - let track = reader - .tracks() - .values() - .find_map(|t| match t.media_type() { - Ok(MediaType::H264) => Some((t, Codec::H264)), - Ok(MediaType::H265) => Some((t, Codec::Hevc)), - Ok(MediaType::VP9) => Some((t, Codec::Vp9)), - // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry - // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC - // track -- what Apple and ffmpeg's mov muxer write in practice - // -- and every AV1 track report no media type, and such a file - // used to read back as having no video. Its sample tables - // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the - // entry the crate dropped, so only the fourcc has to be read - // here by hand. hvc1 differs from hev1 in that the parameter - // sets may not repeat in-band, which costs nothing: they are - // re-injected out of `hvcC` ahead of every sync sample either - // way, exactly as an AV1 sequence header is out of `av1C`. - _ => matches!(t.track_type(), Ok(TrackType::Video)) + // In *file* order, out of `moov.traks` rather than `Mp4Reader::tracks`, + // which is a `HashMap`: iterating that would make "the video track" a + // different one from one run to the next on a file carrying two, and a + // saved `.edith` would reopen on the other picture. The audio side reads + // the same box for the same reason ([`crate::audio::audio_track_ids`]). + // + // The fourcc of the sample entry is what names the codec, read out of the + // file by hand: `mp4 0.14`'s `stsd` parser knows only a `hev1` entry + // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC track -- + // what Apple and ffmpeg's mov muxer write in practice -- and every AV1 + // track report no media type through `media_type()`, and such a file used + // to read back as having no video. Its sample tables + // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the entry the + // crate dropped, so the fourcc is all that is missing. hvc1 differs from + // hev1 in that the parameter sets may not repeat in-band, which costs + // nothing: they are re-injected out of `hvcC` ahead of every sync sample + // either way, exactly as an AV1 sequence header is out of `av1C`. + let (track, codec) = reader + .moov + .traks + .iter() + .filter_map(|trak| reader.tracks().get(&trak.tkhd.track_id)) + .find_map(|t| { + matches!(t.track_type(), Ok(TrackType::Video)) .then(|| sample_entry(path, t.track_id()).ok()) .flatten() - .and_then(|(kind, _)| match &kind { - b"hvc1" => Some((t, Codec::Hevc)), - b"av01" => Some((t, Codec::Av1)), - _ => None, - }), + .and_then(|(kind, _)| mp4_codec(&kind)) + .map(|codec| (t, codec)) }) - .ok_or("no H.264, HEVC, VP9 or AV1 video track in file")?; - let (track, codec) = track; + // Named, for the same reason the Matroska door names it: "no video + // track" is a lie about a file that has one in a codec this does not + // read, and the fourcc is what tells a user which. + .ok_or_else(|| mp4_no_video(path, &reader))?; let track_id = track.track_id(); let meta = VideoMeta { @@ -467,9 +567,16 @@ impl MkvDemuxer { // in a codec this does not read. None => { return Err(match other { - Some(codec) => format!( - "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are" - ), + // By the reason the table gives where there is one, so the + // refusal says what is missing rather than only what is not. + Some(codec) => match UNSUPPORTED.iter().find(|(id, _)| *id == codec) { + Some((_, why)) => { + format!("{codec} video in a Matroska file is not supported — {why}") + } + None => format!( + "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are" + ), + }, None => "this Matroska file has no video track".to_string(), } .into()); @@ -544,8 +651,9 @@ impl MkvDemuxer { } /// Next access unit in decode order: the block verbatim for AV1, which is - /// one temporal unit already, and Annex-B for HEVC, whose block holds the - /// same length-prefixed NALs an mp4 sample does. + /// one temporal unit already, and for VP9, whose block is one (super)frame; + /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed + /// NALs an mp4 sample does. fn next_access_unit(&mut self) -> crate::Result>> { let Some(&block) = self.blocks.get(self.next) else { return Ok(None); @@ -564,7 +672,7 @@ impl MkvDemuxer { // the bytes as a codec's: a stripped block is not a NAL and an inflated // one is not where it was read from. unpack.frame(scratch)?; - if self.codec == Codec::Av1 { + if matches!(self.codec, Codec::Av1 | Codec::Vp9) { let mut au = Vec::with_capacity(head + self.scratch.len()); au.extend_from_slice(&self.config[..head]); au.extend_from_slice(&self.scratch); @@ -1097,39 +1205,59 @@ fn mkv_track_entry( // A Matroska `CodecPrivate` is the codec's own configuration record -- // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 // sample entry carries, so it parses with the very same reader. - let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) { - (1, "V_AV1") => { + // + // Which codec the id names is [`mkv_codec`]'s answer and not a match arm of + // its own, so this cannot know a codec the mp4 side does not; the match below + // is exhaustive over [`Codec`] for the other half of it -- a variant added to + // the enum fails to compile here rather than falling through to a refusal. + if kind == 2 { + return Ok(MkvEntry::Audio(MkvAudioTrack { + number, + codec, + // What a `TrackEntry` without a `Language` element means, by spec -- + // the same default the subtitle walk applies. + language: if language.is_empty() { + "und".into() + } else { + language + }, + name, + unpack, + })); + } + if kind != 1 { + return Ok(MkvEntry::Other); + } + // The inner match carries no wildcard on purpose: a codec added to [`Codec`] + // fails to compile here rather than falling through to a refusal, which is + // how a VP9 `.webm` came to be refused by a build whose VA-API VP9 decoder + // was wired. + let Some(known) = mkv_codec(&codec) else { + return Ok(MkvEntry::OtherVideo(codec)); + }; + let (codec, nal_length, config, bit_depth) = match known { + Codec::Av1 => { let (sets, bit_depth) = parse_av1c(&config)?; (Codec::Av1, 4, sets, bit_depth) } - (1, "V_MPEGH/ISO/HEVC") => { + Codec::Hevc => { let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; (Codec::Hevc, nal_length, sets, bit_depth) } // The `avcC` beside them, and the same story: length-prefixed blocks and // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole // H.264 path here assumes of an mp4's `avc1` too. - (1, "V_MPEG4/ISO/AVC") => { + Codec::H264 => { let (nal_length, sets) = parse_avcc(&config)?; (Codec::H264, nal_length, sets, 8) } - (1, _) => return Ok(MkvEntry::OtherVideo(codec)), - (2, _) => { - return Ok(MkvEntry::Audio(MkvAudioTrack { - number, - codec, - // What a `TrackEntry` without a `Language` element means, by - // spec -- the same default the subtitle walk applies. - language: if language.is_empty() { - "und".into() - } else { - language - }, - name, - unpack, - })); - } - _ => return Ok(MkvEntry::Other), + // A VP9 block is one self-contained (super)frame: no length prefixes to + // strip and no configuration record to re-inject -- a `.webm` writes no + // `CodecPrivate` at all, and the `vpcC` an mp4 writes is not bitstream + // and would corrupt the frame if it were prepended. The depth is not in + // the container either, so it is read off the first keyframe by + // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from. + Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8), }; Ok(MkvEntry::Video(MkvVideo { number, @@ -1222,6 +1350,94 @@ fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec, u8)> { Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) } +/// Why an mp4 came back with no picture, by the fourcc of the video track it +/// does carry: `avc3` and `mp4v` are files with video in them, and telling their +/// owner there is none sends them looking for a fault that is not in the file. +/// [`UNSUPPORTED`]'s reason where the table has one, the fourcc itself where it +/// does not. +fn mp4_no_video(path: &Path, reader: &Mp4Reader) -> crate::Error { + let found = reader + .moov + .traks + .iter() + .filter(|trak| { + matches!( + TrackType::try_from(&trak.mdia.hdlr.handler_type), + Ok(TrackType::Video) + ) + }) + .find_map(|trak| sample_entry(path, trak.tkhd.track_id).ok()) + .map(|(kind, _)| String::from_utf8_lossy(&kind).trim().to_string()); + match found { + Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) { + Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"), + None => { + format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are") + } + }, + None => "no H.264, HEVC, VP9 or AV1 video track in file".to_string(), + } + .into() +} + +/// Bits per luma sample out of a VP9 keyframe's uncompressed header (VP9 +/// bitstream spec §6.2 `uncompressed_header` and §6.4.1 `color_config`), which is +/// the one place a VP9 stream states its own depth -- see +/// [`Demuxer::fill_vp9_depth`] for why neither container is asked. +/// +/// `None` when this access unit cannot answer -- not a keyframe, a +/// `show_existing_frame`, a truncated block -- which leaves the caller's 8-bit +/// default standing rather than guessing; profile 0 and 1 *are* 8-bit by +/// definition, and they are all a `.webm` off the web ever is. +fn vp9_bit_depth(au: &[u8]) -> crate::Result> { + /// `count` bits, MSB first, from bit offset `at`. Up to 24 at a time, which + /// is the frame sync code and the widest field read here. + fn bits(au: &[u8], at: &mut usize, count: usize) -> Option { + let mut value = 0; + for _ in 0..count { + let byte = *au.get(*at / 8)?; + value = value << 1 | u32::from(byte >> (7 - *at % 8) & 1); + *at += 1; + } + Some(value) + } + let at = &mut 0; + // frame_marker, then the profile as two bits written low one first; profile 3 + // spends a reserved bit before the rest. + if bits(au, at, 2) != Some(2) { + return Ok(None); + } + let (Some(low), Some(high)) = (bits(au, at, 1), bits(au, at, 1)) else { + return Ok(None); + }; + let profile = high << 1 | low; + if profile == 3 && bits(au, at, 1).is_none() { + return Ok(None); + } + // show_existing_frame: such a frame is a reference already decoded and its + // header stops right here. Then frame_type (0 is a keyframe), show_frame and + // error_resilient_mode, and only a keyframe carries the colour config. + if bits(au, at, 1) != Some(0) || bits(au, at, 1) != Some(0) { + return Ok(None); + } + if bits(au, at, 2).is_none() { + return Ok(None); + } + if bits(au, at, 24) != Some(0x49_8342) { + return Ok(None); + } + if profile < 2 { + return Ok(Some(8)); + } + match bits(au, at, 1) { + Some(0) => Ok(Some(10)), + Some(_) => { + Err("12-bit VP9 is not supported — 8- and 10-bit are what the decoder carries".into()) + } + None => Ok(None), + } +} + /// Every block of track `number`, in storage order, with the presentation span /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback /// needs. @@ -2099,6 +2315,89 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result { mod tests { use super::*; + /// The capability matrix, as an assert: every codec the decoder layer can be + /// handed is reachable from *both* container dispatches, and every gap is a + /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into + /// `engine-hw` and reachable from one container only is the defect this + /// exists for -- VP9 was decodable out of an mp4 and refused out of a + /// `.webm`, with the VA-API VP9 decoder compiled in the whole time. + /// + /// The `Codec::` list is written out rather than iterated because there is no + /// variant list to iterate: what makes it stay complete is that both + /// dispatches match on [`Codec`] with no wildcard, so a new variant fails to + /// compile until it has been routed. + #[test] + fn every_codec_is_reachable_from_both_containers() { + for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Av1] { + let row = CODEC_IDS + .iter() + .find(|(c, ..)| *c == codec) + .unwrap_or_else(|| panic!("{} has no row in CODEC_IDS", codec.name())); + assert_eq!( + mkv_codec(row.1), + Some(codec), + "{} is not reachable from a Matroska file", + codec.name() + ); + assert_eq!( + mp4_codec(row.2), + Some(codec), + "{} is not reachable from an mp4", + codec.name() + ); + } + // hev1 and hvc1 are one codec in two fourccs; both are HEVC. + assert_eq!(mp4_codec(b"hev1"), Some(Codec::Hevc)); + + for (id, why) in UNSUPPORTED { + assert_eq!(mkv_codec(id), None, "{id} is supported after all ({why})"); + if let Ok(fourcc) = <&[u8; 4]>::try_from(id.as_bytes()) { + assert_eq!( + mp4_codec(fourcc), + None, + "{id} is supported after all ({why})" + ); + } + } + // ...and a codec nothing here reads is refused rather than mistaken for + // its neighbour in the table. + assert_eq!(mkv_codec("V_MPEG4/ISO/ASP"), None); + assert_eq!(mp4_codec(b"jpeg"), None); + } + + /// The one place a VP9 stream states its own depth. Byte-aligned by + /// construction: the fields ahead of the frame sync code are exactly 8 bits + /// for profiles 0-2. + #[test] + fn a_vp9_keyframe_states_its_own_bit_depth() { + // frame_marker 10, profile bits, show_existing 0, frame_type 0 (key), + // show_frame 1, error_resilient 0, then the sync code 49 83 42. + let profile0 = [0b1000_0010, 0x49, 0x83, 0x42]; + assert_eq!(vp9_bit_depth(&profile0).unwrap(), Some(8)); + // profile 2 (low 0, high 1), then ten_or_twelve_bit = 0. + let profile2 = [0b1001_0010, 0x49, 0x83, 0x42, 0b0000_0000]; + assert_eq!(vp9_bit_depth(&profile2).unwrap(), Some(10)); + // ...and with it set: 12-bit, which has no surface pool here and is + // refused by name rather than decoded into garbage. + let twelve = [0b1001_0010, 0x49, 0x83, 0x42, 0b1000_0000]; + let refused = vp9_bit_depth(&twelve).unwrap_err().to_string(); + assert!(refused.contains("12-bit VP9"), "{refused}"); + // Nothing to answer with is not an answer: an inter frame, a + // show_existing_frame, a truncated block and a non-VP9 payload all leave + // the caller's default standing. + assert_eq!( + vp9_bit_depth(&[0b1000_0110, 0x49, 0x83, 0x42]).unwrap(), + None + ); + assert_eq!( + vp9_bit_depth(&[0b1000_1010, 0x49, 0x83, 0x42]).unwrap(), + None + ); + assert_eq!(vp9_bit_depth(&profile2[..3]).unwrap(), None); + assert_eq!(vp9_bit_depth(&[0, 0, 0, 1, 0x65]).unwrap(), None); + assert_eq!(vp9_bit_depth(&[]).unwrap(), None); + } + #[test] fn splits_two_nals() { let mut out = Vec::new(); diff --git a/crates/engine/tests/capability_matrix.rs b/crates/engine/tests/capability_matrix.rs new file mode 100644 index 0000000..e5786ab --- /dev/null +++ b/crates/engine/tests/capability_matrix.rs @@ -0,0 +1,168 @@ +//! The capability matrix against real files: what the unit test in +//! `demux::tests` asserts about the dispatch tables, this asserts about the +//! containers themselves — every codec the decoder layer can be handed opens +//! from *both* an mp4 and a Matroska file, and says its own name. +//! +//! The defect class it exists for: VP9 shipped decodable out of an mp4 and +//! refused out of a `.webm` with the VA-API VP9 decoder compiled in, because one +//! dispatch arm was missing while the refusal string claimed the capability was +//! absent. A gap must be a written-down row (`demux::UNSUPPORTED`), never a +//! silent fall-through. +//! +//! Nothing installed is needed: these are container reads, not decodes. + +use std::path::PathBuf; + +use engine::AudioSession; +use engine::demux::{Codec, Demuxer}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// One row per cell of (codec × container). A cell with no fixture is a hole in +/// the evidence, so every one of them is filled here. +const MATRIX: &[(Codec, &str, &str)] = &[ + (Codec::H264, "test_baseline.mp4", "test_h264.mkv"), + (Codec::Hevc, "test_hevc.mp4", "test_hevc.mkv"), + (Codec::Vp9, "test_vp9.mp4", "test_vp9.webm"), + // `mp4 0.14` writes no `av01` sample entry, so there is no AV1 mp4 fixture + // to open; the mp4 half of that row is `av01`'s presence in the dispatch + // table, which `demux::tests` holds. + (Codec::Av1, "", "test_av1.mkv"), +]; + +#[test] +fn every_codec_opens_from_every_container_it_arrives_in() { + for (codec, mp4, mkv) in MATRIX { + for file in [mp4, mkv].into_iter().filter(|f| !f.is_empty()) { + let (meta, _) = Demuxer::open(&asset(file)) + .unwrap_or_else(|e| panic!("{file} carries {} and was refused: {e}", codec.name())); + assert_eq!(meta.codec, *codec, "{file}"); + assert!(meta.frame_count > 0, "{file} came back with no frames"); + assert_eq!((meta.width, meta.height), (1280, 720), "{file}"); + } + } +} + +/// The depth cell of the matrix: 10-bit is a property of the stream, and VP9 +/// states it in the one place neither container repeats — the keyframe's +/// uncompressed header. Assumed 8-bit, a profile 2 stream decodes into an NV12 +/// pool and comes back as garbage. +#[test] +fn a_ten_bit_vp9_webm_is_read_as_ten_bit() { + let (meta, demuxer) = Demuxer::open(&asset("test_vp9_10.webm")).expect("open a profile 2 webm"); + assert_eq!(meta.codec, Codec::Vp9); + assert_eq!(demuxer.bit_depth(), 10, "profile 2 is 10-bit"); + + let (_, eight) = Demuxer::open(&asset("test_vp9.webm")).expect("open a profile 0 webm"); + assert_eq!(eight.bit_depth(), 8, "profile 0 is 8-bit by definition"); + + // ...and the probe put the read cursor back where it opened: frame 0 is the + // first picture out, not frame 1. + let (meta, mut demuxer) = Demuxer::open(&asset("test_vp9.webm")).expect("open"); + let mut count = 0; + while demuxer.next_access_unit().expect("read").is_some() { + count += 1; + } + assert_eq!( + count, meta.frame_count, + "the depth probe ate an access unit" + ); +} + +/// The audio half, and the claim a refusal makes: every codec the "cannot be +/// decoded" notice names as readable really opens, per container. It read "AAC +/// and AC-3 only" while FLAC, MP3, Vorbis, ALAC and PCM all decoded out of a +/// Matroska file — a refusal that undersells sends a user re-encoding a film +/// whose sound already plays. +#[test] +fn every_audio_codec_the_refusal_names_really_decodes() { + // The five in one fixture, in the order `gen_fixtures.sh` muxes them, plus + // the AAC and AC-3 the older fixtures carry. + for (stream, codec) in [ + (0, "flac"), + (1, "mp3"), + (2, "vorbis"), + (3, "alac"), + (4, "pcm"), + ] { + let probe = AudioSession::probe(asset("test_mkv_audio.mkv"), stream) + .unwrap_or_else(|e| panic!("{codec} in a Matroska file: {e}")) + .unwrap_or_else(|| panic!("{codec} in a Matroska file came back silent")); + assert_eq!(probe.sample_rate, 44_100, "{codec}"); + } + for (file, codec) in [("test_av1.mkv", "aac"), ("test_ac3.mkv", "ac-3")] { + assert!( + AudioSession::probe(asset(file), 0).expect(codec).is_some(), + "{codec} in a Matroska file came back silent" + ); + } + for (file, codec) in [("test_av.mp4", "aac-lc"), ("test_ac3.mp4", "ac-3")] { + assert!( + AudioSession::probe(asset(file), 0).expect(codec).is_some(), + "{codec} in an mp4 came back silent" + ); + } + + // ...and the gap the refusal is *for*: Opus has no decoder here at any + // version, so the notice names the track and then names what would work. + let refused = AudioSession::unsupported(asset("test_vp9.webm")) + .expect("read the header") + .expect("an Opus track is a reason, not silence"); + assert!(refused.contains("A_OPUS"), "{refused}"); + for named in ["FLAC", "MP3", "Vorbis"] { + assert!( + refused.contains(named), + "the refusal hides a codec that decodes ({named}): {refused}" + ); + } +} + +/// Which of two video tracks an mp4 opens on may not depend on hash order: it is +/// the first in `moov.traks`, file order, the same box the audio side numbers its +/// streams out of. A `HashMap` walk here made a saved `.edith` reopen on the +/// other picture from one launch to the next. +#[test] +fn the_video_track_of_an_mp4_is_the_first_one_in_file_order() { + let path = asset("test_two_video.mp4"); + let file = std::fs::File::open(&path).expect("open the fixture"); + let size = file.metadata().expect("stat").len(); + let reader = mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("header"); + + // What file order says, read straight off the box rather than through the + // map: the test may not share the code it is checking. + let first = reader + .moov + .traks + .iter() + .find(|trak| { + matches!( + mp4::TrackType::try_from(&trak.mdia.hdlr.handler_type), + Ok(mp4::TrackType::Video) + ) + }) + .expect("the fixture has two video tracks"); + let expected = ( + u32::from(first.tkhd.width.value()), + u32::from(first.tkhd.height.value()), + ); + assert_eq!( + expected, + (1280, 720), + "the fixture is the one it says it is" + ); + + // Repeated, because the failure this guards against is a *random* one: the + // hash order that picked the 320x240 track is a different order each run. + for _ in 0..8 { + let (meta, _) = Demuxer::open(&path).expect("open the two-track fixture"); + assert_eq!( + (meta.width, meta.height), + expected, + "the demuxer opened the second video track" + ); + } +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 42afd4d..d45bb58 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -81,6 +81,41 @@ 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 libvpx-vp9 -b:v 2M -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_vp9.mp4 +# The same VP9 stream in Matroska, which is where a yt-dlp download and every +# other VP9 file in the wild actually arrives: `V_VP9` used to fall through the +# mkv track dispatch and be refused by name while the mp4 twin above decoded. +# Opus audio because that is what a .webm carries; the sound is a separate +# refusal (no Opus decoder here) and the picture must not depend on it. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \ + -c:a libopus -b:a 96k assets/test_vp9.webm +# ...and profile 2, 10-bit, which no container states: an mkv `TrackEntry` +# carries no configuration record for VP9 at all and the `vpcC` in an mp4 is +# optional, so the depth is read off the keyframe's uncompressed header +# (`demux::vp9_bit_depth`) -- the difference between a P010 surface pool and a +# picture of garbage. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -c:v libvpx-vp9 -b:v 2M -g 30 -profile:v 2 -pix_fmt yuv420p10le \ + -an assets/test_vp9_10.webm +# One Matroska file per audio codec the refusal string in `audio.rs` claims is +# decodable, as five tracks of one file: FLAC, MP3, Vorbis, ALAC and PCM. The +# string said "AAC and AC-3 only" long after every one of these decoded, which is +# the shape of refusal this suite exists to stop (`tests/capability_matrix.rs`). +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -map 0:v -map 1:a -map 1:a -map 1:a -map 1:a -map 1:a \ + -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a:0 flac -c:a:1 libmp3lame -c:a:2 libvorbis -c:a:3 alac -c:a:4 pcm_s16le \ + assets/test_mkv_audio.mkv +# Two video tracks in one mp4, at different sizes so a test can tell which one +# the demuxer picked. `Mp4Reader::tracks()` is a HashMap and iterating it made +# "the video track" a different one from one run to the next; the pick comes out +# of `moov.traks` (file order) and this is what holds it there. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i testsrc=size=320x240:rate=30:duration=2 \ + -map 0:v -map 1:v -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + assets/test_two_video.mp4 # HEVC fixture: the same A/V shape again, so the tests measure the codec and # nothing else. 8-bit Main profile, because the plugin's NV12 read-back cannot # carry Main 10.