From 9fab7c99c10a52c2649c828ff67a932c864ee8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 13 Sep 2026 01:35:03 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=81=20feat(audio):=20the=20AC-3/E-AC-3?= =?UTF-8?q?=20decode=20seat=20is=20the=20native=20ec-ac3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit oxideav-ac3 leaves the tree. One decoder reads both syntaxes, dispatching per packet on bsid, and hands back interleaved f32 -- the seat asks for its own A/52 §7.8.2 stereo fold on anything wider than mono, per-position coefficients from each frame's own acmod and mix levels, so no width is refused any more (the 2.1-at-3ch passthrough refusal dies with the library) and the mono digital-silence corner-cut is gone with it. Witnesses on real content, identical packets, old seat vs new: - AC-3 5.1 film: per-channel correlations 0.99965-0.99999, rms ratios 1.001; the residual is the format's unspecified dither noise -- against ffmpeg's own decode both decoders sit equally close, and the two spots where they did not agree are OLD-seat deviations (the 2.0 rematrixing decode: 0.92/0.76 vs ffmpeg, the new seat 0.99997; the LFE: 0.976 vs ffmpeg, the new seat 1.000000). - E-AC-3 5.1 film: correlations >= 0.99998 on all six channels, rms 1.000. - Decode speed 1.64-1.68x the old seat (min-of-7, ~320x realtime 5.1). - Named coverage edge, refused by name at open, not silently: Annex E dependent substreams and enhanced coupling (7.1 DD+ assembled as 5.1-plus-dependents) -- oxideav walked those, ec-ac3 refuses them. Every single-substream AC-3 and E-AC-3 track decodes. New film witness file tests/audio_ac3_film.rs (seek-landing + ffmpeg correlation on a real AC-3 5.1 film and a real E-AC-3 5.1 film, mirroring the Opus/AAC film witnesses), real_library.toml.example documents the ac3_51_film key. caps row and the codec-table comment follow the seat. --- Cargo.lock | 19 ++- crates/engine/Cargo.toml | 18 ++- crates/engine/src/audio.rs | 147 ++++++++--------- crates/engine/src/caps.rs | 4 +- crates/engine/src/demux.rs | 2 +- crates/engine/tests/audio_ac3_film.rs | 225 ++++++++++++++++++++++++++ real_library.toml.example | 5 + 7 files changed, 325 insertions(+), 95 deletions(-) create mode 100644 crates/engine/tests/audio_ac3_film.rs diff --git a/Cargo.lock b/Cargo.lock index 181c0b6..f4d1ad8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1596,6 +1596,14 @@ dependencies = [ "ec-dsp", ] +[[package]] +name = "ec-ac3" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", +] + [[package]] name = "ec-av1" version = "0.1.0" @@ -1705,6 +1713,7 @@ name = "engine" version = "0.1.0" dependencies = [ "ec-aac", + "ec-ac3", "ec-av1", "ec-core", "ec-h264", @@ -1716,7 +1725,6 @@ dependencies = [ "libloading", "miniz_oxide", "mp4", - "oxideav-ac3", "oxideav-ass", "oxideav-core", "oxideav-h265", @@ -4015,15 +4023,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "oxideav-ac3" -version = "0.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c60744c9688507efb6849b1bff197fb17e742b56f8a7f914129464bc86197ad" -dependencies = [ - "oxideav-core", -] - [[package]] name = "oxideav-ass" version = "0.0.9" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b0be18d..852d67b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -126,9 +126,20 @@ rusty_vorbis = "0.1.1" # `tests/opus_export.rs` exports and re-reads the files through this project's # own decoder door. ec-opus = { path = "../../../edith_codecs/crates/ec-opus" } +# The AC-3 / E-AC-3 decode seat, the family's own decoder taking the seat the +# registry crate `oxideav-ac3` held. One decoder reads both syntaxes, dispatching +# per packet on `bsid`, and hands back interleaved f32 in the coded layout or -- +# what the seat asks for on anything wider than mono -- its own A/52 §7.8.2 +# stereo fold, per-position coefficients from the frame's own `acmod` and mix +# levels: the same shape and the same loudness the old seat served. One named +# coverage edge, witnessed, not silent: Annex E dependent substreams and +# enhanced coupling (7.1 DD+ assembled as 5.1-plus-dependents) are refused by +# name where `oxideav-ac3` walked them; every single-substream AC-3 and E-AC-3 +# track decodes. +ec-ac3 = { path = "../../../edith_codecs/crates/ec-ac3" } # 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 +# its one dependency is `oxideav-core`, a direct line below. MIT. Vorbis-aware +# where it counts -- `xiph_lace` builds the # three-header blob and the muxer pages those ahead of the audio, which is the # encapsulation order a Vorbis decoder needs and the part that is easy to get # wrong by hand. @@ -142,7 +153,7 @@ symphonia-codec-aac = "0.6" # `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: AC-3 comes from -# `oxideav-ac3` and Opus from `ec-opus` above, both plugged into this crate's +# `ec-ac3` and Opus from `ec-opus` 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", @@ -158,7 +169,6 @@ symphonia = { version = "0.6", default-features = false, features = [ "vorbis", "wav", ] } -oxideav-ac3 = "=0.0.10" oxideav-core = "0.1.34" # The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- # `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 53966ef..b952326 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -9,7 +9,7 @@ //! symphonia's own format probe, as does the AAC track of a **Matroska** file: //! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to //! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same -//! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the +//! sample tables, decoded by `ec-ac3` and downmixed to stereo by the //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo //! timeline. Everything downstream of [`Track`] sees the //! same samples either way; only the packet copy asks which reader it came from, @@ -34,7 +34,6 @@ use std::sync::{Arc, Mutex}; use std::thread; use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; -use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet}; use symphonia_codec_aac::AacDecoder; use symphonia_core::codecs::audio::{ AudioCodecParameters, AudioDecoder, AudioDecoderOptions, @@ -66,7 +65,7 @@ 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 two families no symphonia version carries and this -/// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`]) +/// project decodes anyway -- AC-3/E-AC-3 through `ec-ac3` ([`MkvAc3Track`]) /// and Opus through `ec-opus` ([`SymDecoder::Opus`]). /// /// Written down per container because capability is not one set: an mp4 video's @@ -1489,12 +1488,12 @@ impl Track { fn channels(&self) -> u16 { match self { Self::Aac(t) => t.channels(), - // Already downmixed by the AC-3 decoder itself; `channels` is what - // comes *out* of it, and the 2.1 passthrough it leaves at 3 (see - // [`Ac3Track`]) is folded by [`decode_ac3`] like any other width. - Self::Ac3(t) => t.channels.min(2), - // Downmixed by the very same decoder, out of a Matroska file. - Self::Mkv(t) => t.channels.min(2), + // Downmixed to a pair by the AC-3 decoder itself (§7.8.2); a mono + // track passes through as the one channel it is (see [`ac3_decoder`]), + // so what `channels` measures is already the timeline width. + Self::Ac3(t) => t.channels, + // The same decoder, out of a Matroska file. + Self::Mkv(t) => t.channels, Self::Sym(t) => t.channels, } } @@ -1549,10 +1548,10 @@ impl Track { aac_decoder(&t.params, t.source_channels())?; } Self::Ac3(t) => { - ac3_decoder("ac3", t.requested)?; + ac3_decoder(t.requested)?; } Self::Mkv(t) => { - ac3_decoder(t.mkv.codec, t.requested)?; + ac3_decoder(t.requested)?; } Self::Sym(t) => { t.decoder()?; @@ -2068,15 +2067,18 @@ fn widen(samples: &mut Vec, from: usize, to: usize) { } /// One source's AC-3 track: the same mp4 sample tables the AAC track is read -/// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder -/// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and -/// one timeline layout is all there is. A 5.1 BluRay track therefore arrives -/// here as an ordinary stereo source, and its rows in the picker say so. +/// from, decoded through `ec-ac3` and **downmixed to stereo by the decoder +/// itself** (ATSC A/52 §7.8.2, [`ec_ac3::Downmix::Stereo`]), because one output +/// device and one timeline layout is all there is. A 5.1 BluRay track therefore +/// arrives here as an ordinary stereo source, and its rows in the picker say so. /// /// `channels` is what the decoder actually emitted for the first frame rather -/// than an assumed 2: everything from mono to 5.1 downmixes to stereo, but a 2.1 -/// stream is a passthrough the library leaves at 3, and that is refused by name -/// in [`Track::channels`] instead of being mislabelled. +/// than an assumed 2: everything from stereo to 5.1 downmixes to stereo and a +/// mono track passes through as the one channel it is (`acmod` carries the +/// programme in the centre; duplicating it is the timeline's business, see +/// [`widen`]). The §7.8.2 fold is position-aware — every `acmod` from 1/0 to +/// 3/2 puts its centre and surrounds where the matrix says — so no width is +/// refused or mislabelled. struct Ac3Track { reader: Mp4Reader>, track_id: u32, @@ -2088,8 +2090,9 @@ struct Ac3Track { total_samples: Option, stts: Vec<(u32, u32)>, /// What the decoder is asked to hand out, from this track's own layout: - /// `Some(2)` for anything with more than one front channel, `None` — the - /// library's passthrough — for a mono track. See [`ac3_decoder`]. + /// [`ec_ac3::Downmix::Stereo`] for anything with more than one front + /// channel, [`ec_ac3::Downmix::Native`] — the coded channels untouched — + /// for a mono track. See [`ac3_decoder`]. requested: Option, } @@ -2124,14 +2127,14 @@ impl Ac3Track { let first = reader .read_sample(track_id, 1)? .ok_or("the AC-3 track has no samples")?; - let sample_rate = oxideav_ac3::syncinfo::parse(&first.bytes) + let sample_rate = ec_ac3::syncinfo::parse(&first.bytes) .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))? .sample_rate; - let nfchans = oxideav_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default()) + let nfchans = ec_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default()) .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? .nfchans; let requested = (nfchans > 1).then_some(2); - let mut decoder = ac3_decoder("ac3", requested)?; + let mut decoder = ac3_decoder(requested)?; let channels = decode_ac3(&mut decoder, &first.bytes)? .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) .filter(|&c| c > 0) @@ -2179,10 +2182,10 @@ impl Ac3Track { } /// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same -/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of +/// decoder and the very same §7.8.2 stereo downmix [`Ac3Track`] runs, fed out of /// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux /// therefore arrives on the timeline as an ordinary stereo source, exactly as -/// the mp4 path's does, and the mono passthrough quirk is the same one. +/// the mp4 path's does, and mono passes through exactly the same way. /// /// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side /// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): @@ -2198,7 +2201,7 @@ struct MkvAc3Track { total_samples: Option, /// What the decoder is asked to hand out, from this track's own layout: /// `Some(2)` for anything with more than one front channel, `None` for a - /// mono track. The reason is [`ac3_decoder`]'s `corner-cut`, not this file's. + /// mono track. See [`ac3_decoder`]. requested: Option, } @@ -2233,20 +2236,20 @@ impl MkvAc3Track { // downmix decision wants. let (sample_rate, nfchans) = if mkv.codec == "eac3" { // Annex E's BSI starts right after the 16-bit syncword. - let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) + let bsi = ec_ac3::eac3::parse(first.get(2..).unwrap_or_default()) .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; (bsi.sample_rate, bsi.nfchans) } else { - let sync = oxideav_ac3::syncinfo::parse(&first) + let sync = ec_ac3::syncinfo::parse(&first) .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; - let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) + let bsi = ec_ac3::bsi::parse(first.get(5..).unwrap_or_default()) .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; (sync.sample_rate, bsi.nfchans) }; let requested = (nfchans > 1).then_some(2); - let mut decoder = ac3_decoder(mkv.codec, requested)?; - let (pcm, samples) = - decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; + let mut decoder = ac3_decoder(requested)?; + let (pcm, samples) = decode_ac3(&mut decoder, &first)? + .ok_or("the first AC-3 syncframe decoded to nothing")?; let channels = (pcm.len() as u64 / samples.max(1)) as u16; if channels == 0 { return Err("the first AC-3 syncframe decoded to nothing".into()); @@ -2285,60 +2288,50 @@ impl MkvAc3Track { } } -/// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own -/// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a -/// 5.1 track at all. Fresh per segment for the same reason every other decoder -/// here is: a seek leaves overlap-add state belonging to the frames we skipped. -/// -/// corner-cut: `Some(2)` on a **mono** (`acmod` 1/0) source decodes to digital -/// silence in oxideav-ac3 0.0.10 — measured, 5.1 and stereo are correct — so a -/// mono track asks for no downmix at all and stays the mono source it is. The -/// upgrade path is `Some(2)` unconditionally once the library duplicates the -/// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. +/// A fresh AC-3 / E-AC-3 decoder. `requested` is the downmix ask: `Some(2)` +/// hands back the library's own A/52 §7.8.2 stereo fold — per-position +/// coefficients from the frame's own `acmod` and mix levels, LFE dropped, +/// normalised so a full-scale mix cannot clip — which is the whole reason the +/// timeline can carry a 5.1 track at all; `None` passes the coded channels +/// through, which is what a mono track asks for (`acmod` 1/0 carries the +/// programme in the centre, and duplicating it is the timeline's business, see +/// [`widen`]). Fresh per segment for the same reason every other decoder here +/// is: a seek leaves overlap-add state belonging to the frames we skipped. /// -/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers -/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct -/// behind both dispatches per packet on `bsid` in any case, so what this picks -/// is the capability set, not the syntax. -fn ac3_decoder(codec: &str, channels: Option) -> crate::Result> { - let mut registry = CodecRegistry::new(); - oxideav_ac3::register_codecs(&mut registry); - let mut params = CodecParameters::audio(CodecId::new(codec)); - params.channels = channels; - registry - .first_decoder(¶ms) - .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) +/// The syntax is not an argument: one decoder reads AC-3 and E-AC-3 alike, +/// dispatching per packet on `bsid`. +fn ac3_decoder(requested: Option) -> crate::Result { + Ok(ec_ac3::Ac3Decoder::with_options(ec_ac3::Options { + downmix: requested + .map(|_| ec_ac3::Downmix::Stereo) + .unwrap_or(ec_ac3::Downmix::Native), + ..ec_ac3::Options::default() + })) } /// One syncframe in, one buffer of interleaved f32 out and the frames per /// channel it holds. `Ok(None)` when the decoder wants more input before it can -/// hand a frame back, which is not an error. The library speaks S16 -/// little-endian; `/32768` is the whole conversion, and it lands in the -/// `[-1, 1)` every other reader here emits. +/// hand a frame back, which is not an error. The library speaks interleaved +/// little-endian f32 — the same `[-1, 1)` every other reader here emits. /// /// The frame count comes back beside the samples because an E-AC-3 frame is not /// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 /// or 3 blocks instead of 6 -- and dividing by an assumed length would put the /// channel count and every media position after it out. fn decode_ac3( - decoder: &mut Box, + decoder: &mut ec_ac3::Ac3Decoder, bytes: &[u8], ) -> crate::Result, u64)>> { - let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); - decoder - .send_packet(&packet) - .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; - match decoder.receive_frame() { - Ok(Frame::Audio(audio)) => Ok(Some(( - audio.data[0] - .chunks_exact(2) - .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) + match decoder.decode_frame(bytes) { + Ok(frame) => Ok(Some(( + frame.data[0] + .chunks_exact(4) + .map(|s| f32::from_le_bytes([s[0], s[1], s[2], s[3]])) .collect(), - u64::from(audio.samples), + frame.samples as u64, ))), - Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), - Err(oxideav_core::Error::NeedMore) => Ok(None), - Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), + Err(ec_ac3::Error::NeedMore) => Ok(None), + Err(e) => Err(format!("AC-3 decode failed: {e}").into()), } } @@ -3312,7 +3305,7 @@ fn run_ac3( timeline: &mut u64, tx: &SyncSender, ) -> bool { - let mut decoder = match ac3_decoder("ac3", track.requested) { + let mut decoder = match ac3_decoder(track.requested) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); @@ -3340,9 +3333,8 @@ fn run_ac3( return true; } }; - // The library's §7.8 downmix already handles everything but its own 2.1 - // passthrough, which comes out at 3 and is folded here like any width. - downmix(&mut interleaved, usize::from(track.channels)); + // §7.8.2 has already folded anything wider than a pair; only a mono + // track arrives here in its own width, and [`widen`]'s is the last word. widen(&mut interleaved, usize::from(track.channels), channels); let next = pos + samples; if !emit( @@ -3378,7 +3370,7 @@ fn run_mkv_ac3( timeline: &mut u64, tx: &SyncSender, ) -> bool { - let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { + let mut decoder = match ac3_decoder(track.requested) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); @@ -3406,8 +3398,7 @@ fn run_mkv_ac3( return true; } }; - // ...and the 2.1 passthrough folded here, as on the mp4 side. - downmix(&mut interleaved, usize::from(track.channels)); + // ...and widened here, as on the mp4 side. widen(&mut interleaved, usize::from(track.channels), channels); let next = pos + samples; if !emit( diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs index 34e9c94..4105215 100644 --- a/crates/engine/src/caps.rs +++ b/crates/engine/src/caps.rs @@ -42,7 +42,7 @@ const SW_CODECS: [(&str, &str, bool, bool); 10] = [ ("MP3", "symphonia / rusty_mp3", true, true), ("FLAC", "symphonia / flacenc", true, true), ("PCM", "symphonia / hound", true, true), - ("AC-3", "oxideav-ac3", true, false), + ("AC-3", "ec-ac3", true, false), ("Vorbis", "symphonia / rusty_vorbis", true, true), ("ALAC", "symphonia", true, false), ]; @@ -164,7 +164,7 @@ mod tests { } // Decode-only crates must not read as encoders, and the seat words are // the only thing saying which is which. - assert!(line.contains("AC-3 dec (oxideav-ac3)")); + assert!(line.contains("AC-3 dec (ec-ac3)")); assert!(line.contains("H.264 dec+enc (ec-h264)")); assert!(line.contains("HEVC enc (oxideav-h265 intra)")); } diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index def89ae..96957a3 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -1750,7 +1750,7 @@ pub fn matroska_audio_tracks(path: &Path) -> crate::Result> { pub struct MkvAudio { file: File, blocks: Vec, - /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`. + /// The Matroska codec id these blocks are packets of: `ac3` or `eac3`. pub codec: &'static str, /// Seconds one `TimestampScale` tick is worth, resolved once at open. secs_per_tick: f64, diff --git a/crates/engine/tests/audio_ac3_film.rs b/crates/engine/tests/audio_ac3_film.rs new file mode 100644 index 0000000..103b48f --- /dev/null +++ b/crates/engine/tests/audio_ac3_film.rs @@ -0,0 +1,225 @@ +//! The AC-3 films: the decode seat exercised on the kind of tracks it exists +//! for -- a BluRay remux's 48 kHz AC-3 5.1 and a web remux's 5.1 E-AC-3 +//! (Dolby Digital Plus) -- decoded, folded to the pair the timeline carries, +//! seeked across each film, and correlated against ffmpeg's own decode of the +//! same windows. A wrong channel order, a wrong rate, or a fold that lost a +//! side all move the correlation; a seat that refuses the track fails the +//! open. +//! +//! Mirrors `audio_seek`'s film witnesses, which make the same claim of the +//! Opus and multichannel AAC seats. Skipped, not failed, where the film or +//! ffmpeg is not -- these are named by the local `real_library.toml`, not +//! fixtures in this repository. + +use engine::audio::AudioSession; + +/// The AC-3 5.1 film: seeked to three seconds spread across the film and +/// correlated against ffmpeg's decode of the same window. The seat's §7.8.2 +/// fold and ffmpeg's `-ac 2` disagree by roughly 7.7 dB of level, which is +/// why the comparison is level-normalised (`best_lag`). +#[test] +fn a_seek_into_real_ac3_film_lands_on_the_second_it_asked_for() { + let Some(film) = engine::real_library::film("ac3_51_film") else { + return; + }; + if no_ffmpeg() { + return; + } + const SEARCH: f64 = 5.0; + for want in [300.0, 600.0, 900.0] { + let (meta, rx) = AudioSession::open_at(&film, want) + .expect("open") + .expect("the film has audio"); + assert_eq!(meta.sample_rate, 48_000); + assert_eq!(meta.channels, 2, "5.1 reaches the timeline as a pair"); + let probe = one_second(&meta, rx); + let from = want - SEARCH; + let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate); + let (lag, score) = best_lag(&probe, &reference); + let at = from + lag as f64 / f64::from(meta.sample_rate); + eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})"); + assert!( + score > 0.5, + "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \ + the measurement, not the seek, is what failed" + ); + assert!( + (at - want).abs() <= 0.05, + "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture", + at - want + ); + } +} + +/// The E-AC-3 film: the Dolby Digital Plus class a web remux carries, whose +/// blocks are fixed-laced in Matroska and whose frames are not the fixed +/// 1536-sample AC-3 shape. Same claim, same measurement. +#[test] +fn a_seek_into_real_eac3_film_lands_on_the_second_it_asked_for() { + let Some(film) = engine::real_library::film("hevc_4k_hdr") else { + return; + }; + if no_ffmpeg() { + return; + } + const SEARCH: f64 = 5.0; + for want in [600.0, 1800.0, 3600.0] { + let (meta, rx) = AudioSession::open_at(&film, want) + .expect("open") + .expect("the film has audio"); + assert_eq!(meta.sample_rate, 48_000); + assert_eq!(meta.channels, 2, "5.1 reaches the timeline as a pair"); + let probe = one_second(&meta, rx); + let from = want - SEARCH; + let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate); + let (lag, score) = best_lag(&probe, &reference); + let at = from + lag as f64 / f64::from(meta.sample_rate); + eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})"); + assert!( + score > 0.5, + "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \ + the measurement, not the seek, is what failed" + ); + assert!( + (at - want).abs() <= 0.05, + "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture", + at - want + ); + } +} + +/// True, with the skip said, when ffmpeg is not there to decode a reference. +fn no_ffmpeg() -> bool { + let missing = std::process::Command::new("ffmpeg") + .arg("-version") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .map(|s| !s.success()) + .unwrap_or(true); + if missing { + eprintln!("skipped: no ffmpeg to decode the reference window with"); + } + missing +} + +/// One second of the opened session, summed to mono: the probe `best_lag` +/// locates inside ffmpeg's window. +fn one_second( + meta: &engine::audio::AudioMeta, + rx: std::sync::mpsc::Receiver, +) -> Vec { + let channels = usize::from(meta.channels); + let mut probe: Vec = Vec::with_capacity(meta.sample_rate as usize); + for chunk in rx { + probe.extend( + chunk + .samples + .chunks_exact(channels) + .map(|f| f.iter().map(|s| f64::from(*s)).sum::() / channels as f64), + ); + if probe.len() >= meta.sample_rate as usize { + break; + } + } + probe.truncate(meta.sample_rate as usize); + assert_eq!(probe.len(), meta.sample_rate as usize, "a second to locate"); + probe +} + +/// `dur` seconds of `path`'s first audio track from `start`, decoded by ffmpeg, +/// summed to mono at `rate`. The reference this engine's own landing is measured +/// against, because a decoder cannot be its own witness about where it landed. +fn ffmpeg_mono(path: &std::path::Path, start: f64, dur: f64, rate: u32) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-ss"]) + .arg(format!("{start}")) + .arg("-t") + .arg(format!("{dur}")) + .arg("-i") + .arg(path) + .args(["-map", "0:a:0", "-ac", "1", "-ar"]) + .arg(rate.to_string()) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg runs"); + assert!( + out.status.success(), + "ffmpeg: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + .chunks_exact(4) + .map(|b| f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]]))) + .collect() +} + +/// Where in `reference` the `probe` sits, and how well: the offset in samples of +/// the best normalised cross-correlation, which is 1.0 for the same content and +/// falls away fast for anything else. +/// +/// Coarse then fine, because the naive product over a ten-second window at +/// 48 kHz is 3e10 multiplies: both signals are averaged down by [`DECIMATE`] +/// first -- a crude low-pass, and the peak of a correlation is broad -- then the +/// winner is refined at full rate over the one block around it. The normalisation +/// is what makes the two comparable at all, since this fold is 7.7 dB quieter +/// than ffmpeg's. +fn best_lag(probe: &[f64], reference: &[f64]) -> (usize, f64) { + const DECIMATE: usize = 32; + let down = |xs: &[f64]| -> Vec { + xs.chunks_exact(DECIMATE) + .map(|c| c.iter().sum::() / DECIMATE as f64) + .collect() + }; + let (coarse, at) = scan(&down(probe), &down(reference), 1); + let from = (at * DECIMATE).saturating_sub(DECIMATE); + let span = 3 * DECIMATE + probe.len(); + // The score reported is the coarse one, over the whole search window: the + // fine pass only sharpens the offset inside a block it has already chosen, + // and a score over a window that short says nothing about the match. + let (_, offset) = scan( + probe, + &reference[from.min(reference.len())..(from + span).min(reference.len())], + 1, + ); + (from + offset, coarse) +} + +/// The best normalised cross-correlation of `probe` over `reference`, at `step` +/// samples: `(score, offset)`. Both are mean-removed; the denominator is each +/// window's own energy, so a level difference between the two decoders cannot +/// move the peak. +fn scan(probe: &[f64], reference: &[f64], step: usize) -> (f64, usize) { + if reference.len() <= probe.len() || probe.is_empty() { + return (0.0, 0); + } + let mean = |xs: &[f64]| xs.iter().sum::() / xs.len() as f64; + let p: Vec = { + let m = mean(probe); + probe.iter().map(|s| s - m).collect() + }; + let pe = p.iter().map(|s| s * s).sum::().sqrt(); + if pe <= 0.0 { + return (0.0, 0); + } + let (mut best, mut at) = (0.0, 0); + for offset in (0..reference.len() - p.len()).step_by(step) { + let window = &reference[offset..offset + p.len()]; + let m = mean(window); + let (mut dot, mut energy) = (0.0, 0.0); + for (a, b) in p.iter().zip(window) { + let b = b - m; + dot += a * b; + energy += b * b; + } + let score = match energy > 0.0 { + true => dot / (pe * energy.sqrt()), + false => 0.0, + }; + if score > best { + best = score; + at = offset; + } + } + (best, at) +} diff --git a/real_library.toml.example b/real_library.toml.example index eb6cd33..218500c 100644 --- a/real_library.toml.example +++ b/real_library.toml.example @@ -26,3 +26,8 @@ av1_opus_71 = "/path/to/a-2160p-av1-opus-7.1-remux.mkv" # A feature-length 1080p AV1 remux with a 5.1 Opus track and a cue table: long # enough to seek an hour into, which is where a Matroska landing goes wrong. av1_opus_51 = "/path/to/a-1080p-av1-opus-5.1-remux.mkv" + +# A feature-length film with a plain AC-3 5.1 track (a BluRay encode or remux): +# the multichannel AC-3 seat's own film witness, seeked and correlated against +# ffmpeg like the Opus and AAC films are. +ac3_51_film = "/path/to/an-ac3-5.1-film.mkv"