A codec's support is probed per container, not inferred from a neighbour
Browse files at this commit4f4dcb4470b562ebbd04c16d70195327ecf3071cParent: 5909fc9- fix
- a codec's support is probed per container, not inferred from a neighbour
6 changed files +627 -86
- crates/engine-hw/src/lib.rs +6 -4
- crates/engine/examples/probe_fps.rs +34 -19
- crates/engine/src/audio.rs +31 -9
- crates/engine/src/demux.rs +353 -54
- crates/engine/tests/capability_matrix.rs +168 -0
- scripts/gen_fixtures.sh +35 -0
crates/engine-hw/src/lib.rsmodified+6 -4
| @@ -59,8 +59,8 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle; | |||
| 59 | /// still loads and still decodes H.264 (it simply refuses the newer codecs' | 59 | /// still loads and still decodes H.264 (it simply refuses the newer codecs' |
| 60 | /// files at `Demuxer`). | 60 | /// files at `Demuxer`). |
| 61 | /// | 61 | /// |
| 62 | -/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main at | 62 | +/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0 and 2, AV1 |
| 63 | -/// either depth. | 63 | +/// Main at either depth. |
| 64 | /// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit | 64 | /// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit |
| 65 | /// I420 every frame here is ([`Session::emit`]). | 65 | /// I420 every frame here is ([`Session::emit`]). |
| 66 | /// | 66 | /// |
| @@ -68,8 +68,10 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle; | |||
| 68 | /// interface all the way to the renderer. That costs the low two bits of a Main | 68 | /// interface all the way to the renderer. That costs the low two bits of a Main |
| 69 | /// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every | 69 | /// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every |
| 70 | /// stage between here and the texture upload, not to this file. | 70 | /// stage between here and the texture upload, not to this file. |
| 71 | -/// VP9 profile 2 is still refused by `Demuxer`: a VP9 stream does not state its | 71 | +/// VP9 profile 2 reaches the P010 pool like the rest: a VP9 stream states its |
| 72 | -/// depth where that reads it (an `av1C` and an `hvcC` both do). | 72 | +/// depth in no container record the way an `av1C` or an `hvcC` does, so |
| 73 | +/// `Demuxer` reads it off the first keyframe's uncompressed header | ||
| 74 | +/// (`demux::vp9_bit_depth`) rather than assuming the 8 bits of profile 0. | ||
| 73 | enum Decoder { | 75 | enum Decoder { |
| 74 | H264(Dec<H264>), | 76 | H264(Dec<H264>), |
| 75 | Hevc(Dec<H265>), | 77 | Hevc(Dec<H265>), |
crates/engine/examples/probe_fps.rsmodified+34 -19
| @@ -2,11 +2,11 @@ | |||
| 2 | //! frame the master clock asks for ten minutes in -- the arithmetic behind A/V | 2 | //! frame the master clock asks for ten minutes in -- the arithmetic behind A/V |
| 3 | //! desync on NTSC-rate files, on a file too big to keep as a fixture. | 3 | //! desync on NTSC-rate files, on a file too big to keep as a fixture. |
| 4 | //! | 4 | //! |
| 5 | -//! `cargo run --release -p engine --example probe_fps -- <file.mp4> [secs] [play]` | 5 | +//! `cargo run --release -p engine --example probe_fps -- <file> [secs] [play] [play_secs]` |
| 6 | //! | 6 | //! |
| 7 | -//! With `play` it also seeks there, plays two seconds against the real audio | 7 | +//! With `play` it also seeks there, plays `play_secs` (two by default) against the |
| 8 | -//! device and reports the skew between the picture on screen and the master | 8 | +//! real audio device and reports the skew between the picture on screen and the |
| 9 | -//! clock -- the machine-checkable half of "lip sync holds". | 9 | +//! master clock -- the machine-checkable half of "lip sync holds". |
| 10 | 10 | ||
| 11 | use std::path::PathBuf; | 11 | use std::path::PathBuf; |
| 12 | use std::time::{Duration, Instant}; | 12 | use std::time::{Duration, Instant}; |
| @@ -36,7 +36,34 @@ fn main() { | |||
| 36 | secs * (meta.frame_rate - 23.0) | 36 | secs * (meta.frame_rate - 23.0) |
| 37 | ); | 37 | ); |
| 38 | // Straight from the container, to show what the demuxer's frame 0 skipped. | 38 | // Straight from the container, to show what the demuxer's frame 0 skipped. |
| 39 | - let file = std::fs::File::open(&path).expect("open"); | 39 | + // mp4 only: a Matroska file has no `moov` and reading one out of it is a |
| 40 | + // panic, which used to make this tool unusable on exactly the films in a | ||
| 41 | + // library that the demuxer most needs checking against. | ||
| 42 | + if !engine::demux::is_matroska(&path) { | ||
| 43 | + mp4_boxes(&path); | ||
| 44 | + } | ||
| 45 | + match engine::AudioSession::open(&path) { | ||
| 46 | + Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels), | ||
| 47 | + Ok(None) => println!( | ||
| 48 | + " audio: none usable ({:?})", | ||
| 49 | + engine::AudioSession::unsupported(&path) | ||
| 50 | + ), | ||
| 51 | + Err(e) => println!(" audio: refused ({e})"), | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + // `play [secs]`: how long to play for, two seconds by default. | ||
| 55 | + if args.next().is_some_and(|a| a == *"play") { | ||
| 56 | + let seconds = args | ||
| 57 | + .next() | ||
| 58 | + .and_then(|s| s.to_str().and_then(|s| s.parse().ok())) | ||
| 59 | + .unwrap_or(2.0); | ||
| 60 | + play(&path, secs, meta.frame_rate, seconds); | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// The edit list and sample counts of an mp4, per track. | ||
| 65 | +fn mp4_boxes(path: &std::path::Path) { | ||
| 66 | + let file = std::fs::File::open(path).expect("open"); | ||
| 40 | let size = file.metadata().expect("stat").len(); | 67 | let size = file.metadata().expect("stat").len(); |
| 41 | let reader = | 68 | let reader = |
| 42 | mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("read header"); | 69 | mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("read header"); |
| @@ -76,31 +103,19 @@ fn main() { | |||
| 76 | track.sample_count(), | 103 | track.sample_count(), |
| 77 | ); | 104 | ); |
| 78 | } | 105 | } |
| 79 | - match engine::AudioSession::open(&path) { | ||
| 80 | - Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels), | ||
| 81 | - Ok(None) => println!( | ||
| 82 | - " audio: none usable ({:?})", | ||
| 83 | - engine::AudioSession::unsupported(&path) | ||
| 84 | - ), | ||
| 85 | - Err(e) => println!(" audio: refused ({e})"), | ||
| 86 | - } | ||
| 87 | - | ||
| 88 | - if args.next().is_some_and(|a| a == *"play") { | ||
| 89 | - play(&path, secs, meta.frame_rate); | ||
| 90 | - } | ||
| 91 | } | 106 | } |
| 92 | 107 | ||
| 93 | /// Seeks in, plays two seconds against the real device, and reports where the | 108 | /// Seeks in, plays two seconds against the real device, and reports where the |
| 94 | /// picture stands against the master clock. The clock counts audio samples, so | 109 | /// picture stands against the master clock. The clock counts audio samples, so |
| 95 | /// `frame / fps - clock` *is* the A/V skew: a truncated frame rate shows up | 110 | /// `frame / fps - clock` *is* the A/V skew: a truncated frame rate shows up |
| 96 | /// here as tens of seconds of it, ten minutes in. | 111 | /// here as tens of seconds of it, ten minutes in. |
| 97 | -fn play(path: &std::path::Path, secs: f64, fps: f64) { | 112 | +fn play(path: &std::path::Path, secs: f64, fps: f64, seconds: f64) { |
| 98 | let mut session = engine::PlaybackSession::open(path).expect("open for playback"); | 113 | let mut session = engine::PlaybackSession::open(path).expect("open for playback"); |
| 99 | session.seek(secs); | 114 | session.seek(secs); |
| 100 | session.play(); | 115 | session.play(); |
| 101 | let mut last = None; | 116 | let mut last = None; |
| 102 | let mut held: Option<u32> = None; | 117 | let mut held: Option<u32> = None; |
| 103 | - let deadline = Instant::now() + Duration::from_secs(2); | 118 | + let deadline = Instant::now() + Duration::from_secs_f64(seconds); |
| 104 | while Instant::now() < deadline { | 119 | while Instant::now() < deadline { |
| 105 | session.tick(); | 120 | session.tick(); |
| 106 | // The app's own drop-when-behind rule (`Player::pump`): show every frame | 121 | // The app's own drop-when-behind rule (`Player::pump`): show every frame |
crates/engine/src/audio.rsmodified+31 -9
| @@ -61,6 +61,23 @@ const DEFAULT_PRIMING: u64 = 1024; | |||
| 61 | /// An edit list entry that only shifts the timeline, carrying no media. | 61 | /// An edit list entry that only shifts the timeline, carrying no media. |
| 62 | const EMPTY_EDIT: u64 = u32::MAX as u64; | 62 | const EMPTY_EDIT: u64 = u32::MAX as u64; |
| 63 | 63 | ||
| 64 | +/// What the sound of a *Matroska* file is read with, named for a refusal: | ||
| 65 | +/// symphonia's registry as this project enables it (see the feature list in | ||
| 66 | +/// `Cargo.toml`) plus the AC-3 family, which no symphonia version carries and | ||
| 67 | +/// `oxideav-ac3` does ([`MkvAc3Track`]). | ||
| 68 | +/// | ||
| 69 | +/// Written down per container because capability is not one set: an mp4 video's | ||
| 70 | +/// sound never reaches symphonia ([`Track::open`] answers before it), so it | ||
| 71 | +/// reads fewer codecs than a Matroska file does. Both strings were "AAC only" | ||
| 72 | +/// long after that stopped being true, which is how a user came to re-encode a | ||
| 73 | +/// film whose FLAC track already played; `capability_matrix` opens one file per | ||
| 74 | +/// codec named here. | ||
| 75 | +const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, PCM and Vorbis"; | ||
| 76 | + | ||
| 77 | +/// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video | ||
| 78 | +/// file's sound is read and where it stops. | ||
| 79 | +const MP4_DECODED: &str = "AAC-LC and AC-3/E-AC-3"; | ||
| 80 | + | ||
| 64 | /// Packets decoded and thrown away ahead of a seek target: one for the MDCT | 81 | /// Packets decoded and thrown away ahead of a seek target: one for the MDCT |
| 65 | /// overlap-add that reconstructs the target packet, one to warm the decoder. | 82 | /// overlap-add that reconstructs the target packet, one to warm the decoder. |
| 66 | const PRE_ROLL: u32 = 2; | 83 | const PRE_ROLL: u32 = 2; |
| @@ -653,8 +670,8 @@ impl AudioSession { | |||
| 653 | } | 670 | } |
| 654 | 671 | ||
| 655 | /// Why [`open`](Self::open) came back silent for a file that *has* sound: | 672 | /// Why [`open`](Self::open) came back silent for a file that *has* sound: |
| 656 | - /// `Some(reason)` when there is an audio track and it is not the AAC-LC | 673 | + /// `Some(reason)` when there is an audio track in a codec this does not |
| 657 | - /// this decodes (an AC-3 remux, say). `None` when the file is simply silent | 674 | + /// decode (an Opus web rip, say). `None` when the file is simply silent |
| 658 | /// -- nothing to tell the user there. Header only, and only worth calling | 675 | /// -- nothing to tell the user there. Header only, and only worth calling |
| 659 | /// once the open has already returned no audio. | 676 | /// once the open has already returned no audio. |
| 660 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { | 677 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { |
| @@ -674,7 +691,7 @@ impl AudioSession { | |||
| 674 | return Ok(Some(match MkvAc3Track::open(path.as_ref()) { | 691 | return Ok(Some(match MkvAc3Track::open(path.as_ref()) { |
| 675 | Ok(Some(_)) => return Ok(None), | 692 | Ok(Some(_)) => return Ok(None), |
| 676 | Ok(None) => format!( | 693 | Ok(None) => format!( |
| 677 | - "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" | 694 | + "the {codec} track of this Matroska file cannot be decoded — {MKV_DECODED} are" |
| 678 | ), | 695 | ), |
| 679 | Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), | 696 | Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), |
| 680 | })); | 697 | })); |
| @@ -682,14 +699,19 @@ impl AudioSession { | |||
| 682 | let file = File::open(path.as_ref())?; | 699 | let file = File::open(path.as_ref())?; |
| 683 | let size = file.metadata()?.len(); | 700 | let size = file.metadata()?.len(); |
| 684 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; | 701 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; |
| 685 | - Ok(reader | 702 | + // File order, out of `moov.traks`: naming a codec off a `HashMap` walk |
| 686 | - .tracks() | 703 | + // would tell the user about a different track from one run to the next |
| 687 | - .values() | 704 | + // on a film with two ([`audio_track_ids`], and the same trap the video |
| 688 | - .find(|t| matches!(t.track_type(), Ok(TrackType::Audio))) | 705 | + // pick had in `demux::Mp4Demuxer::open`). |
| 706 | + Ok(audio_track_ids(&reader) | ||
| 707 | + .first() | ||
| 708 | + .and_then(|id| reader.tracks().get(id)) | ||
| 689 | .map(|t| match t.media_type() { | 709 | .map(|t| match t.media_type() { |
| 690 | - Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"), | 710 | + Ok(media) => { |
| 711 | + format!("the {media} audio track cannot be decoded — {MP4_DECODED} are") | ||
| 712 | + } | ||
| 691 | Err(_) => { | 713 | Err(_) => { |
| 692 | - "the audio track is in a codec we cannot decode (AAC-LC only)".to_string() | 714 | + format!("the audio track is in a codec we cannot decode — {MP4_DECODED} are") |
| 693 | } | 715 | } |
| 694 | })) | 716 | })) |
| 695 | } | 717 | } |
crates/engine/src/demux.rsmodified+353 -54
| @@ -16,7 +16,7 @@ use std::fs::File; | |||
| 16 | use std::io::{BufReader, Read, Seek, SeekFrom}; | 16 | use std::io::{BufReader, Read, Seek, SeekFrom}; |
| 17 | use std::path::Path; | 17 | use std::path::Path; |
| 18 | 18 | ||
| 19 | -use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType}; | 19 | +use mp4::{Mp4Reader, Mp4Track, TrackType}; |
| 20 | 20 | ||
| 21 | use crate::audio::{edit_media_time, packet_at, stts_pairs}; | 21 | use crate::audio::{edit_media_time, packet_at, stts_pairs}; |
| 22 | use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags}; | 22 | use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags}; |
| @@ -67,6 +67,65 @@ impl Codec { | |||
| 67 | } | 67 | } |
| 68 | } | 68 | } |
| 69 | 69 | ||
| 70 | +/// The capability matrix: every [`Codec`] the decoder layer can be handed, with | ||
| 71 | +/// the id that names it in each container -- the Matroska `CodecID` and the mp4 | ||
| 72 | +/// `stsd` sample entry fourcc. Both dispatches read *this*, so a codec is | ||
| 73 | +/// reachable from both containers or from neither, never from one because | ||
| 74 | +/// somebody wrote an arm and forgot its twin (VP9 was exactly that: decoded out | ||
| 75 | +/// of an mp4, refused out of a `.webm`, with the VA-API decoder wired all along). | ||
| 76 | +/// | ||
| 77 | +/// A cell that is deliberately absent is a row in [`UNSUPPORTED`] with a reason, | ||
| 78 | +/// never a silent fall-through; `every_codec_is_reachable_from_both_containers` | ||
| 79 | +/// holds both halves. | ||
| 80 | +const CODEC_IDS: &[(Codec, &str, &[u8; 4])] = &[ | ||
| 81 | + (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"), | ||
| 82 | + (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"), | ||
| 83 | + (Codec::Vp9, "V_VP9", b"vp09"), | ||
| 84 | + (Codec::Av1, "V_AV1", b"av01"), | ||
| 85 | +]; | ||
| 86 | + | ||
| 87 | +/// The written-down gaps: container ids -- a Matroska `CodecID` or a four-byte | ||
| 88 | +/// mp4 fourcc -- this reads no picture out of, and why. Asserted to be genuinely | ||
| 89 | +/// unreachable by the same test that asserts [`CODEC_IDS`] is reachable, so a gap | ||
| 90 | +/// that gets closed has to be moved out of here rather than left lying as a false | ||
| 91 | +/// claim. | ||
| 92 | +const UNSUPPORTED: &[(&str, &str)] = &[ | ||
| 93 | + // The mp4 path re-injects the parameter sets out of the `avcC` ahead of | ||
| 94 | + // every sync sample and has nothing to inject for an `avc3` track, which | ||
| 95 | + // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all | ||
| 96 | + // either, so `sequence_parameter_set()` would come back empty-handed. | ||
| 97 | + ("avc3", "H.264 with parameter sets in-band only"), | ||
| 98 | + ("vp08", "no VP8 decoder: cros-codecs carries none"), | ||
| 99 | + ("V_VP8", "no VP8 decoder: cros-codecs carries none"), | ||
| 100 | + ("V_MPEG2", "no MPEG-2 decoder, hardware or software"), | ||
| 101 | + ( | ||
| 102 | + "V_MS/VFW/FOURCC", | ||
| 103 | + "a codec inside a BITMAPINFOHEADER; nothing here unwraps one", | ||
| 104 | + ), | ||
| 105 | +]; | ||
| 106 | + | ||
| 107 | +/// Which codec a Matroska `CodecID` names, or `None` for a track this reads no | ||
| 108 | +/// picture out of. The mkv half of [`CODEC_IDS`]. | ||
| 109 | +fn mkv_codec(id: &str) -> Option<Codec> { | ||
| 110 | + CODEC_IDS | ||
| 111 | + .iter() | ||
| 112 | + .find(|(_, mkv, _)| *mkv == id) | ||
| 113 | + .map(|&(codec, ..)| codec) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// Which codec an mp4 `stsd` sample entry fourcc names. The mp4 half of | ||
| 117 | +/// [`CODEC_IDS`], plus `hev1`: HEVC arrives under either fourcc and the record | ||
| 118 | +/// the parameter sets come out of is the same `hvcC` either way. | ||
| 119 | +fn mp4_codec(fourcc: &[u8; 4]) -> Option<Codec> { | ||
| 120 | + if fourcc == b"hev1" { | ||
| 121 | + return Some(Codec::Hevc); | ||
| 122 | + } | ||
| 123 | + CODEC_IDS | ||
| 124 | + .iter() | ||
| 125 | + .find(|(_, _, mp4)| *mp4 == fourcc) | ||
| 126 | + .map(|&(codec, ..)| codec) | ||
| 127 | +} | ||
| 128 | + | ||
| 70 | #[derive(Debug, Clone, Copy, PartialEq)] | 129 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 71 | pub struct VideoMeta { | 130 | pub struct VideoMeta { |
| 72 | pub width: u32, | 131 | pub width: u32, |
| @@ -98,6 +157,7 @@ impl Demuxer { | |||
| 98 | (meta, Self::Mp4(mp4)) | 157 | (meta, Self::Mp4(mp4)) |
| 99 | }; | 158 | }; |
| 100 | demuxer.fill_sei_light(); | 159 | demuxer.fill_sei_light(); |
| 160 | + demuxer.fill_vp9_depth()?; | ||
| 101 | Ok((meta, demuxer)) | 161 | Ok((meta, demuxer)) |
| 102 | } | 162 | } |
| 103 | 163 | ||
| @@ -146,6 +206,42 @@ impl Demuxer { | |||
| 146 | } | 206 | } |
| 147 | } | 207 | } |
| 148 | 208 | ||
| 209 | + /// The bitstream tier of [`Self::bit_depth`] for VP9, which is *all* of it: | ||
| 210 | + /// an HEVC track states its depth in an `hvcC` and an AV1 one in an `av1C`, | ||
| 211 | + /// and a VP9 track states it nowhere either demuxer reads -- a Matroska | ||
| 212 | + /// `TrackEntry` carries no configuration record at all, and the `vpcC` an mp4 | ||
| 213 | + /// writes is optional and describes the file rather than the frame. So it is | ||
| 214 | + /// read where it is always true: the uncompressed header of the first | ||
| 215 | + /// keyframe, which is what [`vp9_bit_depth`] parses. | ||
| 216 | + /// | ||
| 217 | + /// Assuming 8 instead is how a profile 2 stream would decode into an NV12 | ||
| 218 | + /// pool and come back as garbage -- the plugin picks its surface pool off | ||
| 219 | + /// this number ([`crate::hw`]). | ||
| 220 | + fn fill_vp9_depth(&mut self) -> crate::Result<()> { | ||
| 221 | + let codec = match self { | ||
| 222 | + Self::Mp4(d) => d.codec, | ||
| 223 | + Self::Mkv(d) => d.codec, | ||
| 224 | + }; | ||
| 225 | + if codec != Codec::Vp9 { | ||
| 226 | + return Ok(()); | ||
| 227 | + } | ||
| 228 | + let first = self.next_access_unit(); | ||
| 229 | + self.seek_to_sync_at_or_before(0); | ||
| 230 | + let Ok(Some(au)) = first else { | ||
| 231 | + return Ok(()); | ||
| 232 | + }; | ||
| 233 | + // A 12-bit stream is refused by name here, exactly as a 12-bit AV1 is in | ||
| 234 | + // `parse_av1c`: the plugin has an NV12 pool and a P010 one and no third. | ||
| 235 | + let Some(depth) = vp9_bit_depth(&au)? else { | ||
| 236 | + return Ok(()); | ||
| 237 | + }; | ||
| 238 | + match self { | ||
| 239 | + Self::Mp4(d) => d.bit_depth = depth, | ||
| 240 | + Self::Mkv(d) => d.bit_depth = depth, | ||
| 241 | + } | ||
| 242 | + Ok(()) | ||
| 243 | + } | ||
| 244 | + | ||
| 149 | /// Next access unit in decode order, `None` at end of track. | 245 | /// Next access unit in decode order, `None` at end of track. |
| 150 | pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { | 246 | pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { |
| 151 | match self { | 247 | match self { |
| @@ -221,35 +317,39 @@ impl Mp4Demuxer { | |||
| 221 | let size = file.metadata()?.len(); | 317 | let size = file.metadata()?.len(); |
| 222 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; | 318 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; |
| 223 | 319 | ||
| 224 | - let track = reader | 320 | + // In *file* order, out of `moov.traks` rather than `Mp4Reader::tracks`, |
| 225 | - .tracks() | 321 | + // which is a `HashMap`: iterating that would make "the video track" a |
| 226 | - .values() | 322 | + // different one from one run to the next on a file carrying two, and a |
| 227 | - .find_map(|t| match t.media_type() { | 323 | + // saved `.edith` would reopen on the other picture. The audio side reads |
| 228 | - Ok(MediaType::H264) => Some((t, Codec::H264)), | 324 | + // the same box for the same reason ([`crate::audio::audio_track_ids`]). |
| 229 | - Ok(MediaType::H265) => Some((t, Codec::Hevc)), | 325 | + // |
| 230 | - Ok(MediaType::VP9) => Some((t, Codec::Vp9)), | 326 | + // The fourcc of the sample entry is what names the codec, read out of the |
| 231 | - // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry | 327 | + // file by hand: `mp4 0.14`'s `stsd` parser knows only a `hev1` entry |
| 232 | - // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC | 328 | + // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC track -- |
| 233 | - // track -- what Apple and ffmpeg's mov muxer write in practice | 329 | + // what Apple and ffmpeg's mov muxer write in practice -- and every AV1 |
| 234 | - // -- and every AV1 track report no media type, and such a file | 330 | + // track report no media type through `media_type()`, and such a file used |
| 235 | - // used to read back as having no video. Its sample tables | 331 | + // to read back as having no video. Its sample tables |
| 236 | - // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the | 332 | + // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the entry the |
| 237 | - // entry the crate dropped, so only the fourcc has to be read | 333 | + // crate dropped, so the fourcc is all that is missing. hvc1 differs from |
| 238 | - // here by hand. hvc1 differs from hev1 in that the parameter | 334 | + // hev1 in that the parameter sets may not repeat in-band, which costs |
| 239 | - // sets may not repeat in-band, which costs nothing: they are | 335 | + // nothing: they are re-injected out of `hvcC` ahead of every sync sample |
| 240 | - // re-injected out of `hvcC` ahead of every sync sample either | 336 | + // either way, exactly as an AV1 sequence header is out of `av1C`. |
| 241 | - // way, exactly as an AV1 sequence header is out of `av1C`. | 337 | + let (track, codec) = reader |
| 242 | - _ => matches!(t.track_type(), Ok(TrackType::Video)) | 338 | + .moov |
| 339 | + .traks | ||
| 340 | + .iter() | ||
| 341 | + .filter_map(|trak| reader.tracks().get(&trak.tkhd.track_id)) | ||
| 342 | + .find_map(|t| { | ||
| 343 | + matches!(t.track_type(), Ok(TrackType::Video)) | ||
| 243 | .then(|| sample_entry(path, t.track_id()).ok()) | 344 | .then(|| sample_entry(path, t.track_id()).ok()) |
| 244 | .flatten() | 345 | .flatten() |
| 245 | - .and_then(|(kind, _)| match &kind { | 346 | + .and_then(|(kind, _)| mp4_codec(&kind)) |
| 246 | - b"hvc1" => Some((t, Codec::Hevc)), | 347 | + .map(|codec| (t, codec)) |
| 247 | - b"av01" => Some((t, Codec::Av1)), | ||
| 248 | - _ => None, | ||
| 249 | - }), | ||
| 250 | }) | 348 | }) |
| 251 | - .ok_or("no H.264, HEVC, VP9 or AV1 video track in file")?; | 349 | + // Named, for the same reason the Matroska door names it: "no video |
| 252 | - let (track, codec) = track; | 350 | + // track" is a lie about a file that has one in a codec this does not |
| 351 | + // read, and the fourcc is what tells a user which. | ||
| 352 | + .ok_or_else(|| mp4_no_video(path, &reader))?; | ||
| 253 | 353 | ||
| 254 | let track_id = track.track_id(); | 354 | let track_id = track.track_id(); |
| 255 | let meta = VideoMeta { | 355 | let meta = VideoMeta { |
| @@ -467,9 +567,16 @@ impl MkvDemuxer { | |||
| 467 | // in a codec this does not read. | 567 | // in a codec this does not read. |
| 468 | None => { | 568 | None => { |
| 469 | return Err(match other { | 569 | return Err(match other { |
| 470 | - Some(codec) => format!( | 570 | + // By the reason the table gives where there is one, so the |
| 471 | - "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are" | 571 | + // refusal says what is missing rather than only what is not. |
| 472 | - ), | 572 | + Some(codec) => match UNSUPPORTED.iter().find(|(id, _)| *id == codec) { |
| 573 | + Some((_, why)) => { | ||
| 574 | + format!("{codec} video in a Matroska file is not supported — {why}") | ||
| 575 | + } | ||
| 576 | + None => format!( | ||
| 577 | + "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are" | ||
| 578 | + ), | ||
| 579 | + }, | ||
| 473 | None => "this Matroska file has no video track".to_string(), | 580 | None => "this Matroska file has no video track".to_string(), |
| 474 | } | 581 | } |
| 475 | .into()); | 582 | .into()); |
| @@ -544,8 +651,9 @@ impl MkvDemuxer { | |||
| 544 | } | 651 | } |
| 545 | 652 | ||
| 546 | /// Next access unit in decode order: the block verbatim for AV1, which is | 653 | /// Next access unit in decode order: the block verbatim for AV1, which is |
| 547 | - /// one temporal unit already, and Annex-B for HEVC, whose block holds the | 654 | + /// one temporal unit already, and for VP9, whose block is one (super)frame; |
| 548 | - /// same length-prefixed NALs an mp4 sample does. | 655 | + /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed |
| 656 | + /// NALs an mp4 sample does. | ||
| 549 | fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { | 657 | fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { |
| 550 | let Some(&block) = self.blocks.get(self.next) else { | 658 | let Some(&block) = self.blocks.get(self.next) else { |
| 551 | return Ok(None); | 659 | return Ok(None); |
| @@ -564,7 +672,7 @@ impl MkvDemuxer { | |||
| 564 | // the bytes as a codec's: a stripped block is not a NAL and an inflated | 672 | // the bytes as a codec's: a stripped block is not a NAL and an inflated |
| 565 | // one is not where it was read from. | 673 | // one is not where it was read from. |
| 566 | unpack.frame(scratch)?; | 674 | unpack.frame(scratch)?; |
| 567 | - if self.codec == Codec::Av1 { | 675 | + if matches!(self.codec, Codec::Av1 | Codec::Vp9) { |
| 568 | let mut au = Vec::with_capacity(head + self.scratch.len()); | 676 | let mut au = Vec::with_capacity(head + self.scratch.len()); |
| 569 | au.extend_from_slice(&self.config[..head]); | 677 | au.extend_from_slice(&self.config[..head]); |
| 570 | au.extend_from_slice(&self.scratch); | 678 | au.extend_from_slice(&self.scratch); |
| @@ -1097,39 +1205,59 @@ fn mkv_track_entry( | |||
| 1097 | // A Matroska `CodecPrivate` is the codec's own configuration record -- | 1205 | // A Matroska `CodecPrivate` is the codec's own configuration record -- |
| 1098 | // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 | 1206 | // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 |
| 1099 | // sample entry carries, so it parses with the very same reader. | 1207 | // sample entry carries, so it parses with the very same reader. |
| 1100 | - let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) { | 1208 | + // |
| 1101 | - (1, "V_AV1") => { | 1209 | + // Which codec the id names is [`mkv_codec`]'s answer and not a match arm of |
| 1210 | + // its own, so this cannot know a codec the mp4 side does not; the match below | ||
| 1211 | + // is exhaustive over [`Codec`] for the other half of it -- a variant added to | ||
| 1212 | + // the enum fails to compile here rather than falling through to a refusal. | ||
| 1213 | + if kind == 2 { | ||
| 1214 | + return Ok(MkvEntry::Audio(MkvAudioTrack { | ||
| 1215 | + number, | ||
| 1216 | + codec, | ||
| 1217 | + // What a `TrackEntry` without a `Language` element means, by spec -- | ||
| 1218 | + // the same default the subtitle walk applies. | ||
| 1219 | + language: if language.is_empty() { | ||
| 1220 | + "und".into() | ||
| 1221 | + } else { | ||
| 1222 | + language | ||
| 1223 | + }, | ||
| 1224 | + name, | ||
| 1225 | + unpack, | ||
| 1226 | + })); | ||
| 1227 | + } | ||
| 1228 | + if kind != 1 { | ||
| 1229 | + return Ok(MkvEntry::Other); | ||
| 1230 | + } | ||
| 1231 | + // The inner match carries no wildcard on purpose: a codec added to [`Codec`] | ||
| 1232 | + // fails to compile here rather than falling through to a refusal, which is | ||
| 1233 | + // how a VP9 `.webm` came to be refused by a build whose VA-API VP9 decoder | ||
| 1234 | + // was wired. | ||
| 1235 | + let Some(known) = mkv_codec(&codec) else { | ||
| 1236 | + return Ok(MkvEntry::OtherVideo(codec)); | ||
| 1237 | + }; | ||
| 1238 | + let (codec, nal_length, config, bit_depth) = match known { | ||
| 1239 | + Codec::Av1 => { | ||
| 1102 | let (sets, bit_depth) = parse_av1c(&config)?; | 1240 | let (sets, bit_depth) = parse_av1c(&config)?; |
| 1103 | (Codec::Av1, 4, sets, bit_depth) | 1241 | (Codec::Av1, 4, sets, bit_depth) |
| 1104 | } | 1242 | } |
| 1105 | - (1, "V_MPEGH/ISO/HEVC") => { | 1243 | + Codec::Hevc => { |
| 1106 | let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; | 1244 | let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; |
| 1107 | (Codec::Hevc, nal_length, sets, bit_depth) | 1245 | (Codec::Hevc, nal_length, sets, bit_depth) |
| 1108 | } | 1246 | } |
| 1109 | // The `avcC` beside them, and the same story: length-prefixed blocks and | 1247 | // The `avcC` beside them, and the same story: length-prefixed blocks and |
| 1110 | // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole | 1248 | // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole |
| 1111 | // H.264 path here assumes of an mp4's `avc1` too. | 1249 | // H.264 path here assumes of an mp4's `avc1` too. |
| 1112 | - (1, "V_MPEG4/ISO/AVC") => { | 1250 | + Codec::H264 => { |
| 1113 | let (nal_length, sets) = parse_avcc(&config)?; | 1251 | let (nal_length, sets) = parse_avcc(&config)?; |
| 1114 | (Codec::H264, nal_length, sets, 8) | 1252 | (Codec::H264, nal_length, sets, 8) |
| 1115 | } | 1253 | } |
| 1116 | - (1, _) => return Ok(MkvEntry::OtherVideo(codec)), | 1254 | + // A VP9 block is one self-contained (super)frame: no length prefixes to |
| 1117 | - (2, _) => { | 1255 | + // strip and no configuration record to re-inject -- a `.webm` writes no |
| 1118 | - return Ok(MkvEntry::Audio(MkvAudioTrack { | 1256 | + // `CodecPrivate` at all, and the `vpcC` an mp4 writes is not bitstream |
| 1119 | - number, | 1257 | + // and would corrupt the frame if it were prepended. The depth is not in |
| 1120 | - codec, | 1258 | + // the container either, so it is read off the first keyframe by |
| 1121 | - // What a `TrackEntry` without a `Language` element means, by | 1259 | + // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from. |
| 1122 | - // spec -- the same default the subtitle walk applies. | 1260 | + Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8), |
| 1123 | - language: if language.is_empty() { | ||
| 1124 | - "und".into() | ||
| 1125 | - } else { | ||
| 1126 | - language | ||
| 1127 | - }, | ||
| 1128 | - name, | ||
| 1129 | - unpack, | ||
| 1130 | - })); | ||
| 1131 | - } | ||
| 1132 | - _ => return Ok(MkvEntry::Other), | ||
| 1133 | }; | 1261 | }; |
| 1134 | Ok(MkvEntry::Video(MkvVideo { | 1262 | Ok(MkvEntry::Video(MkvVideo { |
| 1135 | number, | 1263 | number, |
| @@ -1222,6 +1350,94 @@ fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> { | |||
| 1222 | Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) | 1350 | Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) |
| 1223 | } | 1351 | } |
| 1224 | 1352 | ||
| 1353 | +/// Why an mp4 came back with no picture, by the fourcc of the video track it | ||
| 1354 | +/// does carry: `avc3` and `mp4v` are files with video in them, and telling their | ||
| 1355 | +/// owner there is none sends them looking for a fault that is not in the file. | ||
| 1356 | +/// [`UNSUPPORTED`]'s reason where the table has one, the fourcc itself where it | ||
| 1357 | +/// does not. | ||
| 1358 | +fn mp4_no_video<R>(path: &Path, reader: &Mp4Reader<R>) -> crate::Error { | ||
| 1359 | + let found = reader | ||
| 1360 | + .moov | ||
| 1361 | + .traks | ||
| 1362 | + .iter() | ||
| 1363 | + .filter(|trak| { | ||
| 1364 | + matches!( | ||
| 1365 | + TrackType::try_from(&trak.mdia.hdlr.handler_type), | ||
| 1366 | + Ok(TrackType::Video) | ||
| 1367 | + ) | ||
| 1368 | + }) | ||
| 1369 | + .find_map(|trak| sample_entry(path, trak.tkhd.track_id).ok()) | ||
| 1370 | + .map(|(kind, _)| String::from_utf8_lossy(&kind).trim().to_string()); | ||
| 1371 | + match found { | ||
| 1372 | + Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) { | ||
| 1373 | + Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"), | ||
| 1374 | + None => { | ||
| 1375 | + format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are") | ||
| 1376 | + } | ||
| 1377 | + }, | ||
| 1378 | + None => "no H.264, HEVC, VP9 or AV1 video track in file".to_string(), | ||
| 1379 | + } | ||
| 1380 | + .into() | ||
| 1381 | +} | ||
| 1382 | + | ||
| 1383 | +/// Bits per luma sample out of a VP9 keyframe's uncompressed header (VP9 | ||
| 1384 | +/// bitstream spec §6.2 `uncompressed_header` and §6.4.1 `color_config`), which is | ||
| 1385 | +/// the one place a VP9 stream states its own depth -- see | ||
| 1386 | +/// [`Demuxer::fill_vp9_depth`] for why neither container is asked. | ||
| 1387 | +/// | ||
| 1388 | +/// `None` when this access unit cannot answer -- not a keyframe, a | ||
| 1389 | +/// `show_existing_frame`, a truncated block -- which leaves the caller's 8-bit | ||
| 1390 | +/// default standing rather than guessing; profile 0 and 1 *are* 8-bit by | ||
| 1391 | +/// definition, and they are all a `.webm` off the web ever is. | ||
| 1392 | +fn vp9_bit_depth(au: &[u8]) -> crate::Result<Option<u8>> { | ||
| 1393 | + /// `count` bits, MSB first, from bit offset `at`. Up to 24 at a time, which | ||
| 1394 | + /// is the frame sync code and the widest field read here. | ||
| 1395 | + fn bits(au: &[u8], at: &mut usize, count: usize) -> Option<u32> { | ||
| 1396 | + let mut value = 0; | ||
| 1397 | + for _ in 0..count { | ||
| 1398 | + let byte = *au.get(*at / 8)?; | ||
| 1399 | + value = value << 1 | u32::from(byte >> (7 - *at % 8) & 1); | ||
| 1400 | + *at += 1; | ||
| 1401 | + } | ||
| 1402 | + Some(value) | ||
| 1403 | + } | ||
| 1404 | + let at = &mut 0; | ||
| 1405 | + // frame_marker, then the profile as two bits written low one first; profile 3 | ||
| 1406 | + // spends a reserved bit before the rest. | ||
| 1407 | + if bits(au, at, 2) != Some(2) { | ||
| 1408 | + return Ok(None); | ||
| 1409 | + } | ||
| 1410 | + let (Some(low), Some(high)) = (bits(au, at, 1), bits(au, at, 1)) else { | ||
| 1411 | + return Ok(None); | ||
| 1412 | + }; | ||
| 1413 | + let profile = high << 1 | low; | ||
| 1414 | + if profile == 3 && bits(au, at, 1).is_none() { | ||
| 1415 | + return Ok(None); | ||
| 1416 | + } | ||
| 1417 | + // show_existing_frame: such a frame is a reference already decoded and its | ||
| 1418 | + // header stops right here. Then frame_type (0 is a keyframe), show_frame and | ||
| 1419 | + // error_resilient_mode, and only a keyframe carries the colour config. | ||
| 1420 | + if bits(au, at, 1) != Some(0) || bits(au, at, 1) != Some(0) { | ||
| 1421 | + return Ok(None); | ||
| 1422 | + } | ||
| 1423 | + if bits(au, at, 2).is_none() { | ||
| 1424 | + return Ok(None); | ||
| 1425 | + } | ||
| 1426 | + if bits(au, at, 24) != Some(0x49_8342) { | ||
| 1427 | + return Ok(None); | ||
| 1428 | + } | ||
| 1429 | + if profile < 2 { | ||
| 1430 | + return Ok(Some(8)); | ||
| 1431 | + } | ||
| 1432 | + match bits(au, at, 1) { | ||
| 1433 | + Some(0) => Ok(Some(10)), | ||
| 1434 | + Some(_) => { | ||
| 1435 | + Err("12-bit VP9 is not supported — 8- and 10-bit are what the decoder carries".into()) | ||
| 1436 | + } | ||
| 1437 | + None => Ok(None), | ||
| 1438 | + } | ||
| 1439 | +} | ||
| 1440 | + | ||
| 1225 | /// Every block of track `number`, in storage order, with the presentation span | 1441 | /// Every block of track `number`, in storage order, with the presentation span |
| 1226 | /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback | 1442 | /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback |
| 1227 | /// needs. | 1443 | /// needs. |
| @@ -2099,6 +2315,89 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { | |||
| 2099 | mod tests { | 2315 | mod tests { |
| 2100 | use super::*; | 2316 | use super::*; |
| 2101 | 2317 | ||
| 2318 | + /// The capability matrix, as an assert: every codec the decoder layer can be | ||
| 2319 | + /// handed is reachable from *both* container dispatches, and every gap is a | ||
| 2320 | + /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into | ||
| 2321 | + /// `engine-hw` and reachable from one container only is the defect this | ||
| 2322 | + /// exists for -- VP9 was decodable out of an mp4 and refused out of a | ||
| 2323 | + /// `.webm`, with the VA-API VP9 decoder compiled in the whole time. | ||
| 2324 | + /// | ||
| 2325 | + /// The `Codec::` list is written out rather than iterated because there is no | ||
| 2326 | + /// variant list to iterate: what makes it stay complete is that both | ||
| 2327 | + /// dispatches match on [`Codec`] with no wildcard, so a new variant fails to | ||
| 2328 | + /// compile until it has been routed. | ||
| 2329 | + #[test] | ||
| 2330 | + fn every_codec_is_reachable_from_both_containers() { | ||
| 2331 | + for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Av1] { | ||
| 2332 | + let row = CODEC_IDS | ||
| 2333 | + .iter() | ||
| 2334 | + .find(|(c, ..)| *c == codec) | ||
| 2335 | + .unwrap_or_else(|| panic!("{} has no row in CODEC_IDS", codec.name())); | ||
| 2336 | + assert_eq!( | ||
| 2337 | + mkv_codec(row.1), | ||
| 2338 | + Some(codec), | ||
| 2339 | + "{} is not reachable from a Matroska file", | ||
| 2340 | + codec.name() | ||
| 2341 | + ); | ||
| 2342 | + assert_eq!( | ||
| 2343 | + mp4_codec(row.2), | ||
| 2344 | + Some(codec), | ||
| 2345 | + "{} is not reachable from an mp4", | ||
| 2346 | + codec.name() | ||
| 2347 | + ); | ||
| 2348 | + } | ||
| 2349 | + // hev1 and hvc1 are one codec in two fourccs; both are HEVC. | ||
| 2350 | + assert_eq!(mp4_codec(b"hev1"), Some(Codec::Hevc)); | ||
| 2351 | + | ||
| 2352 | + for (id, why) in UNSUPPORTED { | ||
| 2353 | + assert_eq!(mkv_codec(id), None, "{id} is supported after all ({why})"); | ||
| 2354 | + if let Ok(fourcc) = <&[u8; 4]>::try_from(id.as_bytes()) { | ||
| 2355 | + assert_eq!( | ||
| 2356 | + mp4_codec(fourcc), | ||
| 2357 | + None, | ||
| 2358 | + "{id} is supported after all ({why})" | ||
| 2359 | + ); | ||
| 2360 | + } | ||
| 2361 | + } | ||
| 2362 | + // ...and a codec nothing here reads is refused rather than mistaken for | ||
| 2363 | + // its neighbour in the table. | ||
| 2364 | + assert_eq!(mkv_codec("V_MPEG4/ISO/ASP"), None); | ||
| 2365 | + assert_eq!(mp4_codec(b"jpeg"), None); | ||
| 2366 | + } | ||
| 2367 | + | ||
| 2368 | + /// The one place a VP9 stream states its own depth. Byte-aligned by | ||
| 2369 | + /// construction: the fields ahead of the frame sync code are exactly 8 bits | ||
| 2370 | + /// for profiles 0-2. | ||
| 2371 | + #[test] | ||
| 2372 | + fn a_vp9_keyframe_states_its_own_bit_depth() { | ||
| 2373 | + // frame_marker 10, profile bits, show_existing 0, frame_type 0 (key), | ||
| 2374 | + // show_frame 1, error_resilient 0, then the sync code 49 83 42. | ||
| 2375 | + let profile0 = [0b1000_0010, 0x49, 0x83, 0x42]; | ||
| 2376 | + assert_eq!(vp9_bit_depth(&profile0).unwrap(), Some(8)); | ||
| 2377 | + // profile 2 (low 0, high 1), then ten_or_twelve_bit = 0. | ||
| 2378 | + let profile2 = [0b1001_0010, 0x49, 0x83, 0x42, 0b0000_0000]; | ||
| 2379 | + assert_eq!(vp9_bit_depth(&profile2).unwrap(), Some(10)); | ||
| 2380 | + // ...and with it set: 12-bit, which has no surface pool here and is | ||
| 2381 | + // refused by name rather than decoded into garbage. | ||
| 2382 | + let twelve = [0b1001_0010, 0x49, 0x83, 0x42, 0b1000_0000]; | ||
| 2383 | + let refused = vp9_bit_depth(&twelve).unwrap_err().to_string(); | ||
| 2384 | + assert!(refused.contains("12-bit VP9"), "{refused}"); | ||
| 2385 | + // Nothing to answer with is not an answer: an inter frame, a | ||
| 2386 | + // show_existing_frame, a truncated block and a non-VP9 payload all leave | ||
| 2387 | + // the caller's default standing. | ||
| 2388 | + assert_eq!( | ||
| 2389 | + vp9_bit_depth(&[0b1000_0110, 0x49, 0x83, 0x42]).unwrap(), | ||
| 2390 | + None | ||
| 2391 | + ); | ||
| 2392 | + assert_eq!( | ||
| 2393 | + vp9_bit_depth(&[0b1000_1010, 0x49, 0x83, 0x42]).unwrap(), | ||
| 2394 | + None | ||
| 2395 | + ); | ||
| 2396 | + assert_eq!(vp9_bit_depth(&profile2[..3]).unwrap(), None); | ||
| 2397 | + assert_eq!(vp9_bit_depth(&[0, 0, 0, 1, 0x65]).unwrap(), None); | ||
| 2398 | + assert_eq!(vp9_bit_depth(&[]).unwrap(), None); | ||
| 2399 | + } | ||
| 2400 | + | ||
| 2102 | #[test] | 2401 | #[test] |
| 2103 | fn splits_two_nals() { | 2402 | fn splits_two_nals() { |
| 2104 | let mut out = Vec::new(); | 2403 | let mut out = Vec::new(); |
crates/engine/tests/capability_matrix.rsadded+168 -0
| @@ -0,0 +1,168 @@ | |||
| 1 | +//! The capability matrix against real files: what the unit test in | ||
| 2 | +//! `demux::tests` asserts about the dispatch tables, this asserts about the | ||
| 3 | +//! containers themselves — every codec the decoder layer can be handed opens | ||
| 4 | +//! from *both* an mp4 and a Matroska file, and says its own name. | ||
| 5 | +//! | ||
| 6 | +//! The defect class it exists for: VP9 shipped decodable out of an mp4 and | ||
| 7 | +//! refused out of a `.webm` with the VA-API VP9 decoder compiled in, because one | ||
| 8 | +//! dispatch arm was missing while the refusal string claimed the capability was | ||
| 9 | +//! absent. A gap must be a written-down row (`demux::UNSUPPORTED`), never a | ||
| 10 | +//! silent fall-through. | ||
| 11 | +//! | ||
| 12 | +//! Nothing installed is needed: these are container reads, not decodes. | ||
| 13 | + | ||
| 14 | +use std::path::PathBuf; | ||
| 15 | + | ||
| 16 | +use engine::AudioSession; | ||
| 17 | +use engine::demux::{Codec, Demuxer}; | ||
| 18 | + | ||
| 19 | +fn asset(name: &str) -> PathBuf { | ||
| 20 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 21 | + .join("../../assets") | ||
| 22 | + .join(name) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/// One row per cell of (codec × container). A cell with no fixture is a hole in | ||
| 26 | +/// the evidence, so every one of them is filled here. | ||
| 27 | +const MATRIX: &[(Codec, &str, &str)] = &[ | ||
| 28 | + (Codec::H264, "test_baseline.mp4", "test_h264.mkv"), | ||
| 29 | + (Codec::Hevc, "test_hevc.mp4", "test_hevc.mkv"), | ||
| 30 | + (Codec::Vp9, "test_vp9.mp4", "test_vp9.webm"), | ||
| 31 | + // `mp4 0.14` writes no `av01` sample entry, so there is no AV1 mp4 fixture | ||
| 32 | + // to open; the mp4 half of that row is `av01`'s presence in the dispatch | ||
| 33 | + // table, which `demux::tests` holds. | ||
| 34 | + (Codec::Av1, "", "test_av1.mkv"), | ||
| 35 | +]; | ||
| 36 | + | ||
| 37 | +#[test] | ||
| 38 | +fn every_codec_opens_from_every_container_it_arrives_in() { | ||
| 39 | + for (codec, mp4, mkv) in MATRIX { | ||
| 40 | + for file in [mp4, mkv].into_iter().filter(|f| !f.is_empty()) { | ||
| 41 | + let (meta, _) = Demuxer::open(&asset(file)) | ||
| 42 | + .unwrap_or_else(|e| panic!("{file} carries {} and was refused: {e}", codec.name())); | ||
| 43 | + assert_eq!(meta.codec, *codec, "{file}"); | ||
| 44 | + assert!(meta.frame_count > 0, "{file} came back with no frames"); | ||
| 45 | + assert_eq!((meta.width, meta.height), (1280, 720), "{file}"); | ||
| 46 | + } | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The depth cell of the matrix: 10-bit is a property of the stream, and VP9 | ||
| 51 | +/// states it in the one place neither container repeats — the keyframe's | ||
| 52 | +/// uncompressed header. Assumed 8-bit, a profile 2 stream decodes into an NV12 | ||
| 53 | +/// pool and comes back as garbage. | ||
| 54 | +#[test] | ||
| 55 | +fn a_ten_bit_vp9_webm_is_read_as_ten_bit() { | ||
| 56 | + let (meta, demuxer) = Demuxer::open(&asset("test_vp9_10.webm")).expect("open a profile 2 webm"); | ||
| 57 | + assert_eq!(meta.codec, Codec::Vp9); | ||
| 58 | + assert_eq!(demuxer.bit_depth(), 10, "profile 2 is 10-bit"); | ||
| 59 | + | ||
| 60 | + let (_, eight) = Demuxer::open(&asset("test_vp9.webm")).expect("open a profile 0 webm"); | ||
| 61 | + assert_eq!(eight.bit_depth(), 8, "profile 0 is 8-bit by definition"); | ||
| 62 | + | ||
| 63 | + // ...and the probe put the read cursor back where it opened: frame 0 is the | ||
| 64 | + // first picture out, not frame 1. | ||
| 65 | + let (meta, mut demuxer) = Demuxer::open(&asset("test_vp9.webm")).expect("open"); | ||
| 66 | + let mut count = 0; | ||
| 67 | + while demuxer.next_access_unit().expect("read").is_some() { | ||
| 68 | + count += 1; | ||
| 69 | + } | ||
| 70 | + assert_eq!( | ||
| 71 | + count, meta.frame_count, | ||
| 72 | + "the depth probe ate an access unit" | ||
| 73 | + ); | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// The audio half, and the claim a refusal makes: every codec the "cannot be | ||
| 77 | +/// decoded" notice names as readable really opens, per container. It read "AAC | ||
| 78 | +/// and AC-3 only" while FLAC, MP3, Vorbis, ALAC and PCM all decoded out of a | ||
| 79 | +/// Matroska file — a refusal that undersells sends a user re-encoding a film | ||
| 80 | +/// whose sound already plays. | ||
| 81 | +#[test] | ||
| 82 | +fn every_audio_codec_the_refusal_names_really_decodes() { | ||
| 83 | + // The five in one fixture, in the order `gen_fixtures.sh` muxes them, plus | ||
| 84 | + // the AAC and AC-3 the older fixtures carry. | ||
| 85 | + for (stream, codec) in [ | ||
| 86 | + (0, "flac"), | ||
| 87 | + (1, "mp3"), | ||
| 88 | + (2, "vorbis"), | ||
| 89 | + (3, "alac"), | ||
| 90 | + (4, "pcm"), | ||
| 91 | + ] { | ||
| 92 | + let probe = AudioSession::probe(asset("test_mkv_audio.mkv"), stream) | ||
| 93 | + .unwrap_or_else(|e| panic!("{codec} in a Matroska file: {e}")) | ||
| 94 | + .unwrap_or_else(|| panic!("{codec} in a Matroska file came back silent")); | ||
| 95 | + assert_eq!(probe.sample_rate, 44_100, "{codec}"); | ||
| 96 | + } | ||
| 97 | + for (file, codec) in [("test_av1.mkv", "aac"), ("test_ac3.mkv", "ac-3")] { | ||
| 98 | + assert!( | ||
| 99 | + AudioSession::probe(asset(file), 0).expect(codec).is_some(), | ||
| 100 | + "{codec} in a Matroska file came back silent" | ||
| 101 | + ); | ||
| 102 | + } | ||
| 103 | + for (file, codec) in [("test_av.mp4", "aac-lc"), ("test_ac3.mp4", "ac-3")] { | ||
| 104 | + assert!( | ||
| 105 | + AudioSession::probe(asset(file), 0).expect(codec).is_some(), | ||
| 106 | + "{codec} in an mp4 came back silent" | ||
| 107 | + ); | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + // ...and the gap the refusal is *for*: Opus has no decoder here at any | ||
| 111 | + // version, so the notice names the track and then names what would work. | ||
| 112 | + let refused = AudioSession::unsupported(asset("test_vp9.webm")) | ||
| 113 | + .expect("read the header") | ||
| 114 | + .expect("an Opus track is a reason, not silence"); | ||
| 115 | + assert!(refused.contains("A_OPUS"), "{refused}"); | ||
| 116 | + for named in ["FLAC", "MP3", "Vorbis"] { | ||
| 117 | + assert!( | ||
| 118 | + refused.contains(named), | ||
| 119 | + "the refusal hides a codec that decodes ({named}): {refused}" | ||
| 120 | + ); | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Which of two video tracks an mp4 opens on may not depend on hash order: it is | ||
| 125 | +/// the first in `moov.traks`, file order, the same box the audio side numbers its | ||
| 126 | +/// streams out of. A `HashMap` walk here made a saved `.edith` reopen on the | ||
| 127 | +/// other picture from one launch to the next. | ||
| 128 | +#[test] | ||
| 129 | +fn the_video_track_of_an_mp4_is_the_first_one_in_file_order() { | ||
| 130 | + let path = asset("test_two_video.mp4"); | ||
| 131 | + let file = std::fs::File::open(&path).expect("open the fixture"); | ||
| 132 | + let size = file.metadata().expect("stat").len(); | ||
| 133 | + let reader = mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("header"); | ||
| 134 | + | ||
| 135 | + // What file order says, read straight off the box rather than through the | ||
| 136 | + // map: the test may not share the code it is checking. | ||
| 137 | + let first = reader | ||
| 138 | + .moov | ||
| 139 | + .traks | ||
| 140 | + .iter() | ||
| 141 | + .find(|trak| { | ||
| 142 | + matches!( | ||
| 143 | + mp4::TrackType::try_from(&trak.mdia.hdlr.handler_type), | ||
| 144 | + Ok(mp4::TrackType::Video) | ||
| 145 | + ) | ||
| 146 | + }) | ||
| 147 | + .expect("the fixture has two video tracks"); | ||
| 148 | + let expected = ( | ||
| 149 | + u32::from(first.tkhd.width.value()), | ||
| 150 | + u32::from(first.tkhd.height.value()), | ||
| 151 | + ); | ||
| 152 | + assert_eq!( | ||
| 153 | + expected, | ||
| 154 | + (1280, 720), | ||
| 155 | + "the fixture is the one it says it is" | ||
| 156 | + ); | ||
| 157 | + | ||
| 158 | + // Repeated, because the failure this guards against is a *random* one: the | ||
| 159 | + // hash order that picked the 320x240 track is a different order each run. | ||
| 160 | + for _ in 0..8 { | ||
| 161 | + let (meta, _) = Demuxer::open(&path).expect("open the two-track fixture"); | ||
| 162 | + assert_eq!( | ||
| 163 | + (meta.width, meta.height), | ||
| 164 | + expected, | ||
| 165 | + "the demuxer opened the second video track" | ||
| 166 | + ); | ||
| 167 | + } | ||
| 168 | +} | ||
scripts/gen_fixtures.shmodified+35 -0
| @@ -81,6 +81,41 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 81 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 81 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 82 | -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \ | 82 | -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \ |
| 83 | -c:a aac -b:a 128k assets/test_vp9.mp4 | 83 | -c:a aac -b:a 128k assets/test_vp9.mp4 |
| 84 | +# The same VP9 stream in Matroska, which is where a yt-dlp download and every | ||
| 85 | +# other VP9 file in the wild actually arrives: `V_VP9` used to fall through the | ||
| 86 | +# mkv track dispatch and be refused by name while the mp4 twin above decoded. | ||
| 87 | +# Opus audio because that is what a .webm carries; the sound is a separate | ||
| 88 | +# refusal (no Opus decoder here) and the picture must not depend on it. | ||
| 89 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 90 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 91 | + -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \ | ||
| 92 | + -c:a libopus -b:a 96k assets/test_vp9.webm | ||
| 93 | +# ...and profile 2, 10-bit, which no container states: an mkv `TrackEntry` | ||
| 94 | +# carries no configuration record for VP9 at all and the `vpcC` in an mp4 is | ||
| 95 | +# optional, so the depth is read off the keyframe's uncompressed header | ||
| 96 | +# (`demux::vp9_bit_depth`) -- the difference between a P010 surface pool and a | ||
| 97 | +# picture of garbage. | ||
| 98 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 99 | + -c:v libvpx-vp9 -b:v 2M -g 30 -profile:v 2 -pix_fmt yuv420p10le \ | ||
| 100 | + -an assets/test_vp9_10.webm | ||
| 101 | +# One Matroska file per audio codec the refusal string in `audio.rs` claims is | ||
| 102 | +# decodable, as five tracks of one file: FLAC, MP3, Vorbis, ALAC and PCM. The | ||
| 103 | +# string said "AAC and AC-3 only" long after every one of these decoded, which is | ||
| 104 | +# the shape of refusal this suite exists to stop (`tests/capability_matrix.rs`). | ||
| 105 | +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ | ||
| 106 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 107 | + -map 0:v -map 1:a -map 1:a -map 1:a -map 1:a -map 1:a \ | ||
| 108 | + -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 109 | + -c:a:0 flac -c:a:1 libmp3lame -c:a:2 libvorbis -c:a:3 alac -c:a:4 pcm_s16le \ | ||
| 110 | + assets/test_mkv_audio.mkv | ||
| 111 | +# Two video tracks in one mp4, at different sizes so a test can tell which one | ||
| 112 | +# the demuxer picked. `Mp4Reader::tracks()` is a HashMap and iterating it made | ||
| 113 | +# "the video track" a different one from one run to the next; the pick comes out | ||
| 114 | +# of `moov.traks` (file order) and this is what holds it there. | ||
| 115 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 116 | + -f lavfi -i testsrc=size=320x240:rate=30:duration=2 \ | ||
| 117 | + -map 0:v -map 1:v -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 118 | + assets/test_two_video.mp4 | ||
| 84 | # HEVC fixture: the same A/V shape again, so the tests measure the codec and | 119 | # HEVC fixture: the same A/V shape again, so the tests measure the codec and |
| 85 | # nothing else. 8-bit Main profile, because the plugin's NV12 read-back cannot | 120 | # nothing else. 8-bit Main profile, because the plugin's NV12 read-back cannot |
| 86 | # carry Main 10. | 121 | # carry Main 10. |