From 699950af73d94cd691df3f0f5a875a38bed7577c 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 06:55:59 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=8A=20feat(audio):=20an=20Opus=20film?= =?UTF-8?q?=20is=20heard,=20not=20refused?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The refusal was the bug again. `is_audio` said "no opus, ac3 or dts, for which no pure-Rust decoder exists" while symphonia's own mkv and ogg readers have always mapped `A_OPUS` and `OpusHead` to `CODEC_ID_OPUS`: the containers read the format, only the decoder was missing. Symphonia genuinely has none at any version -- its feature list stops at vorbis and there is no `symphonia-codec-opus` crate -- so the decoder is `ruopus`, pure Rust, MIT, no dependencies of its own, and the film plays. Which crate is not a coin toss. A 5.1 track is four elementary Opus streams in one packet, all but the last self-delimited (RFC 6716 App. B). `rusty-opus 0.9.1` -- the sibling of `rusty_aac`/`rusty_mp3` already here -- hands each self-delimited slice to a decoder that parses it as an ordinary packet, so every stream but the last reads the length prefix as payload: it was measured on a 5.1 Opus remux as full-scale noise at -13 dBFS over a passage where the film is silent, which is exactly the failure that "the decoder returns samples" would have shipped. `ruopus` matches ffmpeg's decode of the same file to a correlation of 1.00000 on all six channels. Two things that are Opus's alone: it is stored in Vorbis channel order (FL, FC, FR, BL, BR, LFE) and the 5.1 fold reads the film order every other decoder here hands back, so the frame is permuted before it folds; and its encoder delay lives in the stream (`OpusHead`'s pre-skip, 312 samples) where neither reader drops it, so that is this track's priming -- sample-exact against ffmpeg afterwards, 6.5 ms late before. `.opus` and `.mka` join `is_audio`, `unsupported` asks the other reader before naming a codec (a refusal that fires on a track which decodes is the same defect wearing the other face), and `capability_matrix` covers Opus per container with DTS left as the one live refusal row. --- Cargo.lock | 7 ++ crates/engine/Cargo.toml | 24 +++- crates/engine/src/audio.rs | 149 +++++++++++++++++++++-- crates/engine/src/lib.rs | 28 +++-- crates/engine/tests/audio_decode.rs | 84 +++++++++++++ crates/engine/tests/capability_matrix.rs | 38 +++++- scripts/gen_fixtures.sh | 34 +++++- 7 files changed, 335 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66a74ca..9a22700 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1650,6 +1650,7 @@ dependencies = [ "oxideav-sub-image", "oxideav-subtitle", "rav1e", + "ruopus", "rusty_aac", "rusty_h264", "rusty_mp3", @@ -4856,6 +4857,12 @@ version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" +[[package]] +name = "ruopus" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd" + [[package]] name = "rust-embed" version = "8.12.0" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 038873a..4990a87 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -56,6 +56,25 @@ rusty_mp3 = "0.6" # packet. This one does the whole pipeline. Its quirks are measured and worked # around in [`crate::export::write_ogg`] -- read that before touching this line. rusty_vorbis = "0.1.1" +# The Opus decoder: pure Rust, MIT, no C and no FFI, and no dependencies at all +# without its default features (`spectrograms` is for its own analysis tools). +# Symphonia has no Opus at any version -- its feature list stops at vorbis and +# there is no `symphonia-codec-opus` crate -- while both of its containers *read* +# the format already: `A_OPUS` and `OpusHead` have always mapped to +# `CODEC_ID_OPUS`. The decoder was the one missing half, and the reason a 5.1 +# Opus film played silent while its picture was fine. +# +# Multistream is what decides which crate: a 5.1 track is four elementary Opus +# streams in one packet, all but the last **self-delimited** (RFC 6716 App. B), +# and this one strips that framing per stream (`multistream.rs:71`). The obvious +# sibling pick, `rusty-opus 0.9.1` -- same family as `rusty_aac`/`rusty_mp3` +# above -- hands each self-delimited slice to a decoder that parses it as an +# ordinary packet, so every stream but the last decodes the length prefix as +# payload: measured on a real 5.1 Opus remux as full-scale noise at -13 dBFS where the +# film is silent. This one matches ffmpeg's own decode of the same file to a +# correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3` +# below, because a decoder is a bit-exactness dependency. +ruopus = { version = "=0.1.2", default-features = false, features = ["std"] } # The Ogg container, and the only new *name* here that is not a new crate tree: # its one dependency is `oxideav-core`, which the AC-3 decoder above already # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the @@ -71,8 +90,9 @@ symphonia-codec-aac = "0.6" # ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of # a Matroska video file is read, the picture having its own demuxer here. -# There is no opus/ac3/dts feature at any symphonia version, which is why those -# are refused rather than promised. +# There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from +# `oxideav-ac3` and Opus from `ruopus` above, both plugged into this crate's +# own readers, and DTS is the one that really is refused. symphonia = { version = "0.6", default-features = false, features = [ "aac", "alac", diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 80db4b7..0d62b93 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -37,7 +37,8 @@ use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackT use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet}; use symphonia_codec_aac::AacDecoder; use symphonia_core::codecs::audio::{ - AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, + AudioCodecParameters, AudioDecoder, AudioDecoderOptions, + well_known::{CODEC_ID_AAC, CODEC_ID_OPUS}, }; use symphonia_core::formats::probe::Hint; // `TrackType` is the name both readers give their track kinds; the mp4 one is @@ -63,8 +64,9 @@ 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`]). +/// `Cargo.toml`) plus the two families no symphonia version carries and this +/// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`]) +/// and Opus through `ruopus` ([`SymDecoder::Opus`]). /// /// 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 @@ -72,7 +74,7 @@ const EMPTY_EDIT: u64 = u32::MAX as u64; /// 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"; +const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, Opus, PCM and Vorbis"; /// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video /// file's sound is read and where it stops. @@ -677,10 +679,10 @@ impl AudioSession { pub fn unsupported(path: impl AsRef) -> crate::Result> { // Matroska: what symphonia reads out of one ([`Track::open`]) plus the // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder - // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here - // has at any version -- is named rather than left playing silent with no - // reason given. A Matroska file with no audio track at all returns - // `None` here like any other silent file. + // ([`MkvAc3Track`]) and the Opus its own decoder takes; everything else + // -- DTS, and whatever else no decoder here has -- is named rather than + // left playing silent with no reason given. A Matroska file with no + // audio track at all returns `None` here like any other silent file. if crate::demux::is_matroska(path.as_ref()) { let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { return Ok(None); @@ -690,6 +692,18 @@ impl AudioSession { // reader's own words are the ones worth showing. return Ok(Some(match MkvAc3Track::open(path.as_ref()) { Ok(Some(_)) => return Ok(None), + // ...and the same question asked of the other reader, because a + // refusal is a claim: a track symphonia's side really opens and + // builds a decoder for is not one to tell the user about. This + // is what stopped naming `A_OPUS` the moment Opus decoded. + Ok(None) | Err(_) + if SymTrack::open(path.as_ref()) + .ok() + .flatten() + .is_some_and(|t| t.decoder().is_ok()) => + { + return Ok(None); + } Ok(None) => format!( "the {codec} track of this Matroska file cannot be decoded — {MKV_DECODED} are" ), @@ -1441,6 +1455,18 @@ impl SymTrack { let codec = symphonia::default::get_codecs() .get_audio_decoder(params.codec) .map_or("an unsupported format", |d| d.codec.info.short_name); + // The one codec here that *does* owe a priming number: Opus states its + // encoder delay in the stream itself (`OpusHead`'s pre-skip, 312 samples + // on a film remux) and neither reader drops it, because symphonia trims + // for its own decoders and the Opus one is this crate's. Measured against + // ffmpeg's decode of the same file: 312 samples late in *both* an mkv and + // an ogg until this is subtracted, sample-exact after (correlation + // 1.00000). It is priming exactly as an AAC track's is, and it is read + // off the stream rather than the container for that reason. + let priming = match params.codec { + CODEC_ID_OPUS => opus_pre_skip(params.extra_data.as_deref().unwrap_or_default()), + _ => 0, + }; Ok(Some(Self { reader, track_id, @@ -1450,8 +1476,8 @@ impl SymTrack { // [`Track::channels`], where it always was. channels: if channels == 6 { 2 } else { channels }, source_channels: channels, - total_samples: num_frames, - priming: 0, + total_samples: num_frames.map(|n| n.saturating_sub(priming)), + priming, time_base, params, codec, @@ -1471,9 +1497,19 @@ impl SymTrack { /// Which decoder is not the caller's business, and it is not always /// symphonia's: its AAC decoder refuses anything wider than stereo outright /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track - /// of a film in an mkv, so that one goes to `rusty_aac` instead. + /// of a film in an mkv, so that one goes to `rusty_aac` instead, and it has + /// no Opus decoder at all, so that one goes to `ruopus`. fn decoder(&self) -> crate::Result { let fold = self.source_channels != self.channels; + if self.params.codec == CODEC_ID_OPUS { + let channels = usize::from(self.source_channels); + let (streams, coupled, mapping) = + opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), channels)?; + // 48 kHz whatever the container says: that is the only rate Opus + // decodes at, and the rate both readers declare for it. + let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping); + return Ok(SymDecoder::Opus(Box::new(decoder), fold)); + } if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 { let asc = self .params @@ -1512,6 +1548,10 @@ enum SymDecoder { /// Boxed because the decoder carries its own IMDCT tables and this enum is /// moved into the worker. Aac(Box, bool), + /// Every Opus track, mono to 5.1: one multistream decoder -- the streams of + /// a packet, the channel mapping table and the routing between them are all + /// its business -- and the same fold flag. + Opus(Box, bool), } impl SymDecoder { @@ -1528,11 +1568,98 @@ impl SymDecoder { *out = pcm.samples; fold_5_1(out, *fold); } + Self::Opus(decoder, fold) => { + *out = decoder + .decode_packet(&packet.data) + .map_err(|e| format!("Opus decode failed: {e}"))?; + // The encoder delay is not dropped here: it is this track's + // priming ([`SymTrack::open_inner`]), which the window rules + // subtract once for the whole segment rather than per packet. + vorbis_to_film_order(out, *fold); + fold_5_1(out, *fold); + } } Ok(()) } } +/// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of +/// `OpusHead`, little-endian. Zero for a track whose header is missing or too +/// short to hold one -- there is nothing to subtract that we can trust. +fn opus_pre_skip(head: &[u8]) -> u64 { + match head { + [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', _, _, lo, hi, ..] => { + u64::from(u16::from_le_bytes([*lo, *hi])) + } + _ => 0, + } +} + +/// The stream layout of an Opus track, off the file's own `OpusHead`: how many +/// elementary streams one packet carries, how many of those are coupled +/// (stereo), and which decoded channel each output channel comes from. Both +/// readers hand the header over as `extra_data` verbatim -- an mkv's +/// `CodecPrivate`, an ogg's identification packet. +/// +/// Mapping family 0 carries no table at all and is mono or stereo by definition; +/// every other family writes one (RFC 7845 §5.1), and family 1 -- the Vorbis +/// surround layout a 5.1 film track is written with -- is four streams of which +/// two are coupled. +/// +/// Everything here is checked rather than trusted: `MultistreamDecoder::with_rate` +/// *panics* on a layout that breaks the RFC's limits, and this header comes +/// straight out of a file, so a truncated or hostile one has to come back as an +/// `Err` and be refused like any other undecodable track. +fn opus_layout(head: &[u8], channels: usize) -> crate::Result<(usize, usize, Vec)> { + if !(1..=255).contains(&channels) { + return Err(format!("an Opus track of {channels} channels").into()); + } + let table = match head { + [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', rest @ ..] if rest.len() > 10 => { + // Byte 18 of the header is the mapping family; the table, when there + // is one, is the two counts and one byte per output channel after it. + match rest[10] { + 0 => None, + _ => Some(rest.get(11..13 + channels).ok_or("a truncated OpusHead")?), + } + } + // No header at all: the container declared the channel count and nothing + // else, which only family 0 can honestly be. + _ => None, + }; + let Some(table) = table else { + if channels > 2 { + return Err(format!("an Opus track of {channels} channels with no mapping").into()); + } + return Ok((1, channels - 1, (0..channels as u8).collect())); + }; + let (streams, coupled) = (usize::from(table[0]), usize::from(table[1])); + let mapping = table[2..].to_vec(); + let decoded = streams + coupled; + if streams < 1 || coupled > streams || decoded > 255 { + return Err(format!("an Opus track of {streams} streams, {coupled} coupled").into()); + } + if !mapping.iter().all(|&m| m == 255 || usize::from(m) < decoded) { + return Err(format!("an Opus channel mapping outside its {decoded} streams").into()); + } + Ok((streams, coupled, mapping)) +} + +/// Opus 5.1 is stored in Vorbis channel order (FL, FC, FR, BL, BR, LFE) and +/// [`fold_5_1`] reads the film order every other decoder here hands back (FL, FR, +/// FC, LFE, BL, BR). This is that permutation, in place, and only for the 5.1 +/// track the fold is *for*: mono and stereo need none, and every other width is +/// refused by [`Track::channels`] before a packet is ever decoded. +fn vorbis_to_film_order(samples: &mut [f32], fold: bool) { + if !fold { + return; + } + for frame in samples.chunks_exact_mut(6) { + let [fl, fc, fr, bl, br, lfe] = <[f32; 6]>::try_from(&frame[..]).expect("a 5.1 frame"); + frame.copy_from_slice(&[fl, fr, fc, lfe, bl, br]); + } +} + /// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of /// each side join that side at -3 dB, and the LFE is dropped -- it carries no /// programme a stereo pair could put anywhere. Both outputs are divided by the diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b530440..38afa24 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -41,14 +41,17 @@ pub use project::{Clip, Project, Rate, Speed}; /// dropped file may land on *before* anything is opened, and so does /// [`PlaybackSession::import`](playback::PlaybackSession::import). /// -/// Exactly the containers the engine's audio path reads (`audio::AudioSession`): -/// no opus, ac3 or dts, for which no pure-Rust decoder exists -- those are -/// refused by the same door that refuses a `.txt`, which is the honest answer. +/// Exactly the containers the engine's audio path reads (`audio::AudioSession`), +/// Opus included: `.opus` is an Ogg file symphonia's probe already reads and +/// `ruopus` now decodes, and `.mka` is the Matroska whose sound is all it +/// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a +/// `.txt` -- there is no reader here that opens an elementary stream -- which is +/// the honest answer. pub fn is_audio(path: &std::path::Path) -> bool { path.extension().and_then(|e| e.to_str()).is_some_and(|e| { matches!( e.to_ascii_lowercase().as_str(), - "mp3" | "wav" | "flac" | "ogg" | "oga" | "m4a" | "aac" + "mp3" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac" ) }) } @@ -96,18 +99,27 @@ mod tests { #[test] fn is_audio_admits_the_containers_the_decoder_reads() { for name in [ - "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", + "song.mp3", + "a.WAV", + "b.flac", + "c.ogg", + "d.oga", + "e.m4a", + "f.aac", + "g.opus", + "h.OPUS", + "i.mka", ] { assert!(super::is_audio(Path::new(name)), "{name}"); } - // Video, projects, the formats with no pure-Rust decoder, and a file - // with no extension at all: all of them go elsewhere. + // Video, projects, the elementary streams no reader here opens, and a + // file with no extension at all: all of them go elsewhere. for name in [ "clip.mp4", "take.MP4", "cut.edith", - "x.opus", "y.ac3", + "z.dts", "notes", "mp3", ] { diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index d26e77e..4102aac 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -161,6 +161,90 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { } } +/// Opus, which used to be the codec the refusal string was *for*: a standalone +/// `.opus`, the `.webm` sound off the web, and the 5.1 in an `.mka` that a film +/// soundtrack is -- four Opus streams with a channel mapping table, decoded by +/// `ruopus` and folded to stereo by the same fold the AC-3 and AAC paths use. +/// +/// The 5.1 fixture is the channel-order check as well: its tone is in FL and BR +/// and silent in between, so both output channels carry sound only if the +/// decoder's Vorbis order (FL, FC, FR, BL, BR, LFE) was put into the film order +/// the fold reads (FL, FR, FC, LFE, BL, BR). Skipping that permutation folds BR +/// as if it were BL and the right channel comes out silent. +#[test] +fn opus_decodes_from_every_container_and_51_comes_down_in_order() { + for (name, secs, channels) in [("test_tone.opus", 3.0, 2), ("test_vp9.webm", 2.0, 1)] { + let path = asset(name); + let (meta, rx) = AudioSession::open(&path) + .expect("open") + .expect("Opus decodes now"); + assert_eq!((meta.sample_rate, meta.channels), (48000, channels), "{name}"); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let decoded = (samples.len() / channels as usize) as f64 / 48000.0; + assert!( + (secs - decoded).abs() < 0.1, + "{name} is {secs}s, decoded {decoded:.3}s" + ); + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() + / samples.len() as f64) + .sqrt(); + assert!( + (0.005..0.75).contains(&rms), + "{name}: RMS {rms:.6} is not a sine at a sane level" + ); + assert!( + samples.iter().all(|s| s.abs() <= 1.0), + "{name}: the decode must not leave the device's range" + ); + // ...and the same file as a session, where the picture allows it: the + // webm's is VP9, which is the VA-API plugin's and not this test's. + if !name.ends_with(".webm") { + let session = engine::PlaybackSession::open(&path).expect("open for playback"); + assert_eq!( + session.audio_disabled_reason(), + None, + "{name}: a track that decodes owes no excuse" + ); + } + } + + let path = asset("test_opus_51.mka"); + let (meta, rx) = AudioSession::open(&path) + .expect("open") + .expect("5.1 Opus decodes now"); + assert_eq!((meta.sample_rate, meta.channels), (48000, 2)); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let rms = |channel: usize| { + let side: Vec = samples[channel..] + .iter() + .step_by(2) + .map(|s| f64::from(*s) * f64::from(*s)) + .collect(); + (side.iter().sum::() / side.len() as f64).sqrt() + }; + let (left, right) = (rms(0), rms(1)); + assert!(left > 0.02, "the 5.1 fold came out silent on the left: {left}"); + assert!( + right > 0.3 * left, + "BR was folded as if it were BL: left {left:.4}, right {right:.4}" + ); + // ...and it is the *tone* on each side, not noise at the right level. This is + // the assert that bites: a multistream decoder that mis-slices the packet + // (all but the last stream of an Opus 5.1 packet are self-delimited) hands + // back full-scale hash whose RMS passes every level check above -- measured + // -13 dBFS of it on a film, where the film is silent. + let secs = (samples.len() / 2) as f64 / 48000.0; + for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] { + let side: Vec = samples[channel..].iter().step_by(2).copied().collect(); + let want = 2.0 * hz * secs; + let got = zero_crossings(&side) as f64; + assert!( + (got - want).abs() <= 0.05 * want, + "{name}: {got} zero crossings, want {want} +/-5% -- a decode this far off is noise" + ); + } +} + /// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and /// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" /// refusal used to fire on -- both come out of the blocks, both arrive as the diff --git a/crates/engine/tests/capability_matrix.rs b/crates/engine/tests/capability_matrix.rs index e5786ab..d1fa772 100644 --- a/crates/engine/tests/capability_matrix.rs +++ b/crates/engine/tests/capability_matrix.rs @@ -94,6 +94,23 @@ fn every_audio_codec_the_refusal_names_really_decodes() { .unwrap_or_else(|| panic!("{codec} in a Matroska file came back silent")); assert_eq!(probe.sample_rate, 44_100, "{codec}"); } + // Opus, every container it arrives in: a `.webm` off the web, the `.mka` a + // 5.1 film soundtrack is remuxed into, and the standalone `.opus`. It was + // the last codec the notice named as absent while both readers here already + // *parsed* it -- `A_OPUS` and `OpusHead` have always mapped to symphonia's + // `CODEC_ID_OPUS`; only the decoder was missing, and it is `ruopus` now. + for (file, what, channels) in [ + ("test_vp9.webm", "opus in a webm", 1), + // 5.1 arrives as the stereo fold, exactly as a 5.1 AC-3 track does. + ("test_opus_51.mka", "5.1 opus in an mka", 2), + ("test_tone.opus", "a standalone opus", 2), + ] { + let probe = AudioSession::probe(asset(file), 0) + .unwrap_or_else(|e| panic!("{what}: {e}")) + .unwrap_or_else(|| panic!("{what} came back silent")); + assert_eq!(probe.sample_rate, 48_000, "{what}"); + assert_eq!(probe.channels, channels, "{what}"); + } for (file, codec) in [("test_av1.mkv", "aac"), ("test_ac3.mkv", "ac-3")] { assert!( AudioSession::probe(asset(file), 0).expect(codec).is_some(), @@ -107,18 +124,27 @@ fn every_audio_codec_the_refusal_names_really_decodes() { ); } - // ...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")) + // ...and the gap the refusal is really *for*, which is DTS and no longer + // Opus: no decoder in this tree has it, so the notice names the track and + // then names what would have worked -- Opus among them, or the refusal is + // back to underselling the engine. + let refused = AudioSession::unsupported(asset("test_dts.mkv")) .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"] { + .expect("a DTS track is a reason, not silence"); + assert!(refused.contains("A_DTS"), "{refused}"); + for named in ["FLAC", "MP3", "Opus", "Vorbis"] { assert!( refused.contains(named), "the refusal hides a codec that decodes ({named}): {refused}" ); } + // The other half of that claim, and the one a stale refusal string cannot + // fake: a file whose track really does decode has nothing to excuse. + assert_eq!( + AudioSession::unsupported(asset("test_vp9.webm")).expect("read the header"), + None, + "an Opus track that decodes is not a refusal" + ); } /// Which of two video tracks an mp4 opens on may not depend on hash order: it is diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index fc1fcfc..5505f37 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -84,8 +84,8 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ # 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. +# Opus audio because that is what a .webm carries -- the sound decodes here now +# (`ruopus`), and this is the webm cell of the Opus row in `capability_matrix`. 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 \ @@ -108,6 +108,14 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ -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 +# ...and the codec that really is refused, so the other half of the refusal is +# testable too: DTS, which no decoder in this tree has (symphonia has none at any +# version and there is no pure-Rust one to reach for, unlike AC-3 and Opus). The +# notice must name *this* track and go on naming what would have worked. +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a dca -strict -2 -ac 2 assets/test_dts.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 @@ -418,6 +426,28 @@ for fmt in mp3 wav flac ogg m4a aac; do -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ "assets/test_tone.$fmt" done +# The two Opus fixtures, which cannot join the loop above: Opus decodes at 48 kHz +# and nothing else, so these are the 48k twins of the tone rather than 44.1k ones. +# First the standalone `.opus`, an Ogg file `crate::is_audio` now admits. +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \ + -f lavfi -i "sine=frequency=880:duration=3:sample_rate=48000" \ + -filter_complex "$tone" -map "[a]" -c:a libopus -b:a 96k \ + assets/test_tone.opus +# ...and 5.1 Opus in an `.mka`, which is the shape a film soundtrack has: four +# Opus streams with the Vorbis channel mapping, folded to stereo on the way to +# the timeline. The tone sits in **FL and BR only**, both silent in between, so +# the fold's channel order is checkable without an FFT: done right, 440 Hz comes +# out left and 880 Hz right; read in the decoder's own Vorbis order (FL, FC, FR, +# BL, BR, LFE) instead of the film order the fold wants (FL, FR, FC, LFE, BL, BR), +# BR lands on the left with FL and the right channel comes out silent. +# `join` needs every output channel mapped and assigns them by *name*, not by +# input order: without the explicit `map=` the two tones land in FC and BR +# instead, and the fixture stops testing what its comment says. +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \ + -f lavfi -i "sine=frequency=880:duration=3:sample_rate=48000" \ + -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \ + -filter_complex "[0:a][1:a][2:a]join=inputs=3:channel_layout=5.1:map=0.0-FL|2.0-FR|2.1-FC|2.2-LFE|2.3-BL|1.0-BR[a]" \ + -map "[a]" -c:a libopus -b:a 256k assets/test_opus_51.mka # Still-image fixture: the source with a picture and no timeline in it. Two # bands rather than one colour, so a test can tell top from bottom (a flipped # decode) and red from blue (a swapped channel order); 640x360, which is 16:9