From 8c7bf808ae19e1655737ac07a94de22b5002565f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 13:31:57 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(audio):=20AC3=20tracks=20decod?= =?UTF-8?q?e=20with=20a=20built-in=20stereo=20downmix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 22 ++ crates/app/src/main.rs | 6 +- crates/engine/Cargo.toml | 2 + crates/engine/src/audio.rs | 311 +++++++++++++++++++++++++-- crates/engine/src/demux.rs | 5 +- crates/engine/src/waveform.rs | 6 +- crates/engine/tests/audio_decode.rs | 69 ++++-- crates/engine/tests/audio_export.rs | 54 +++++ crates/engine/tests/audio_streams.rs | 31 ++- scripts/gen_fixtures.sh | 7 + 10 files changed, 459 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 28ddcf2..b0c5af7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1634,6 +1634,8 @@ dependencies = [ "hound", "libloading", "mp4", + "oxideav-ac3", + "oxideav-core", "rusty_h264", "symphonia", "symphonia-codec-aac", @@ -3924,6 +3926,26 @@ 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-core" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a68d9a74d6d0a7373589eca0c0bb8ab380c46fd1d7fc807e696d716cdad078c" +dependencies = [ + "bytemuck", + "serde_json", + "thiserror 2.0.20", +] + [[package]] name = "parking" version = "2.2.1" diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index df73209..0032e36 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -3826,9 +3826,9 @@ fn layout(channels: u16) -> Option { /// picker that hides them is a picker that lies. fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option { if !info.decodable { - // ponytail: mp4 0.14 keeps no fourcc for a sample entry it does not - // parse (`StreamInfo::codec`), so an AC-3 track can only be named as - // unsupported, not as AC-3. Upgrade path is reading the stsd ourselves. + // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the + // stsd fourcc by hand); anything else mp4 0.14 does not parse has no + // name to give, and a row with no name still says why it is greyed. return Some(match info.codec.as_str() { "unknown" => "unsupported codec".to_string(), codec => format!("{codec} is not supported"), diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 05c63e7..8baefda 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -35,3 +35,5 @@ symphonia = { version = "0.6", default-features = false, features = [ "vorbis", "wav", ] } +oxideav-ac3 = "=0.0.10" +oxideav-core = "0.1.34" diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 4260214..1644894 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -2,11 +2,14 @@ //! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own //! reader so the video demuxer stays single-owner. //! -//! Two readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as +//! Three readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as //! it always has -- that path also yields the raw access units the export //! copies, which is the only reason it is kept separate -- and a standalone //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through -//! symphonia's own format probe. Everything downstream of [`Track`] sees the +//! symphonia's own format probe. An mp4's **AC-3** track is the third: the same +//! sample tables, decoded by `oxideav-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, //! because there is nothing to copy out of an mp3 that an mp4 can hold. //! @@ -27,6 +30,7 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; 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, well_known::CODEC_ID_AAC, @@ -59,6 +63,14 @@ const PRE_ROLL: u32 = 2; /// Frames per channel one AAC-LC packet carries. Fixed by the codec. const SAMPLES_PER_PACKET: u32 = 1024; +/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks +/// of 256), the way 1024 is fixed for AAC-LC. +const AC3_SAMPLES_PER_FRAME: u32 = 1536; + +/// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the +/// 256-sample overlap-add the target frame is reconstructed with. +const AC3_PRE_ROLL: u32 = 1; + /// Frames per channel a seek into a standalone audio file lands ahead of the /// window, decoded and thrown away: enough to refill an mp3's bit reservoir /// (a frame is 1152 samples and the reservoir reaches back two of them) at any @@ -493,14 +505,35 @@ impl AudioSession { .map(|(index, id)| { let track = &reader.tracks()[&id]; let aac = matches!(track.media_type(), Ok(MediaType::AAC)); + // An AC-3 track describes itself through its own reader: mp4 + // 0.14 parses no sample entry for it, so `channel_config` and + // `sample_freq_index` have nothing to say. What is listed is + // the *decoded* shape -- stereo, because that is what the §7.8 + // downmix hands the timeline (see [`Ac3Track`]). + let ac3 = (!aac) + .then(|| Ac3Track::open(path, index).ok().flatten()) + .flatten(); let lang = track.language(); StreamInfo { index, - codec: if aac { "aac" } else { "unknown" }.into(), - channels: track.channel_config().map_or(0, channel_count), - sample_rate: track.sample_freq_index().map_or(0, |f| f.freq()), + codec: match (aac, &ac3) { + (true, _) => "aac", + (_, Some(_)) => "ac-3", + _ => "unknown", + } + .into(), + channels: ac3 + .as_ref() + .map_or_else(|| track.channel_config().map_or(0, channel_count), |t| { + t.channels + }), + sample_rate: ac3.as_ref().map_or_else( + || track.sample_freq_index().map_or(0, |f| f.freq()), + |t| t.sample_rate, + ), lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()), - decodable: aac + decodable: ac3.as_ref().is_some_and(|t| matches!(t.channels, 1 | 2)) + || aac && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity)) && matches!( track.channel_config(), @@ -732,22 +765,32 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result> { match Track::open(path, stream)? { None => Ok(None), Some(Track::Aac(track)) => Ok(Some(track)), - Some(Track::Sym(track)) => Err(format!( - "export needs AAC audio today; {} is {}", - path.file_name() - .unwrap_or(path.as_os_str()) - .to_string_lossy(), - track.codec - ) - .into()), + Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)), + // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` + // sample table can hold, and there is no AAC encoder here to turn it + // into one. A WAV/FLAC export of the same timeline decodes fine. + Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), } } +/// The one wording for "this source's audio cannot be copied into an mp4", +/// shared by every format that cannot be: a front-end shows it verbatim. +fn uncopyable(path: &Path, codec: &str) -> crate::Error { + format!( + "export needs AAC audio today; {} is {codec}", + path.file_name() + .unwrap_or(path.as_os_str()) + .to_string_lossy(), + ) + .into() +} + /// One source's audio, however it is stored: the mp4 AAC track the export can /// copy, or a standalone file read through symphonia's probe. The opener and /// the worker speak to this, never to either reader directly. enum Track { Aac(AacTrack), + Ac3(Ac3Track), Sym(SymTrack), } @@ -773,6 +816,15 @@ impl Track { return Ok(None); } let audio_file = crate::is_audio(path); + // Ahead of the AAC reader, because that one answers "not AAC" for a + // *named* stream with an `Err` and an AC-3 track is not an error any + // more. `Ok(None)` here means "not an AC-3 track", so every other file + // falls through to exactly the reader it always used. + if !audio_file + && let Some(track) = Ac3Track::open(path, stream)? + { + return Ok(Some(Self::Ac3(track))); + } match AacTrack::open(path, stream) { Ok(Some(track)) => return Ok(Some(Self::Aac(track))), Ok(None) if !audio_file => return Ok(None), @@ -788,6 +840,7 @@ impl Track { fn sample_rate(&self) -> u32 { match self { Self::Aac(t) => t.sample_rate, + Self::Ac3(t) => t.sample_rate, Self::Sym(t) => t.sample_rate, } } @@ -797,6 +850,12 @@ impl Track { fn channels(&self) -> crate::Result { match self { Self::Aac(t) => t.channels(), + // Already downmixed: `channels` is what comes *out* of the decoder, + // which is 2 for everything from mono to 5.1 (see [`Ac3Track`]). + Self::Ac3(t) => match t.channels { + 1 | 2 => Ok(t.channels), + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), + }, Self::Sym(t) => match t.channels { 1 | 2 => Ok(t.channels), n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), @@ -808,6 +867,7 @@ impl Track { fn total_samples(&self) -> Option { match self { Self::Aac(t) => t.total_samples, + Self::Ac3(t) => t.total_samples, Self::Sym(t) => t.total_samples, } } @@ -816,6 +876,7 @@ impl Track { fn priming(&self) -> u64 { match self { Self::Aac(t) => t.priming, + Self::Ac3(t) => t.priming, Self::Sym(t) => t.priming, } } @@ -825,6 +886,7 @@ impl Track { fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { match self { Self::Aac(t) => t.segment(source, start_secs, end_secs), + Self::Ac3(t) => t.segment(source, start_secs, end_secs), Self::Sym(t) => { let media_target = t.media(start_secs); Segment { @@ -845,6 +907,9 @@ impl Track { Self::Aac(t) => { AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; } + Self::Ac3(t) => { + ac3_decoder(t.requested)?; + } Self::Sym(t) => { t.decoder()?; } @@ -945,6 +1010,159 @@ impl SymTrack { } } +/// 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. +/// +/// `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. +struct Ac3Track { + reader: Mp4Reader>, + track_id: u32, + sample_count: u32, + sample_rate: u32, + channels: u16, + timescale: u32, + priming: u64, + 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`]. + requested: Option, +} + +impl Ac3Track { + /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it + /// is anything else (including out of range) — the caller then goes on to + /// the AAC reader, which owns those verdicts and their wording. + /// + /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without + /// keeping the fourcc, so what the track *is* comes out of the `stsd` by + /// hand ([`crate::demux::sample_entry`]); the rate and the channel count + /// come out of the first syncframe, which is where AC-3 states them. + fn open(path: &Path, stream: usize) -> crate::Result> { + let file = File::open(path)?; + let size = file.metadata()?.len(); + let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?; + let ids = audio_track_ids(&reader); + let Some(&track_id) = ids.get(stream) else { + return Ok(None); + }; + if !matches!(crate::demux::sample_entry(path, track_id), Ok((kind, _)) if &kind == b"ac-3") + { + return Ok(None); + } + let track = &reader.tracks()[&track_id]; + let timescale = track.timescale(); + let duration = track.trak.mdia.mdhd.duration; + let edit = edit_media_time(track); + let stts: Vec<(u32, u32)> = stts_pairs(track).collect(); + let sample_count = reader.sample_count(track_id)?; + + 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) + .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()) + .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(requested)?; + let channels = decode_ac3(&mut decoder, &first.bytes)? + .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16) + .filter(|&c| c > 0) + .ok_or("the first AC-3 syncframe decoded to nothing")?; + + // No encoder delay in AC-3; a remux that writes an edit list is still + // honoured, exactly as the AAC track honours it. + let priming = edit + .and_then(|t| scale(t, sample_rate, timescale)) + .unwrap_or(0); + Ok(Some(Self { + track_id, + sample_count, + sample_rate, + channels, + timescale, + priming, + total_samples: scale(duration, sample_rate, timescale) + .map(|d| d.saturating_sub(priming)), + stts, + requested, + reader, + })) + } + + /// `secs` on this source's audible timeline into media samples. + fn media(&self, secs: f64) -> u64 { + ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) + } + + /// One `[start, end)` window, resolved to syncframes and media samples — + /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll. + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { + let media_target = self.media(start_secs); + let target_ts = unscale(media_target, self.sample_rate, self.timescale); + let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL); + Segment { + source: Some(source), + start_id, + start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), + media_target, + media_end: self.media(end_secs).max(media_target), + } + } +} + +/// 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. +/// +/// ponytail: `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. +fn ac3_decoder(channels: Option) -> crate::Result> { + let mut registry = CodecRegistry::new(); + oxideav_ac3::register_codecs(&mut registry); + let mut params = CodecParameters::audio(CodecId::new("ac3")); + params.channels = channels; + registry + .first_decoder(¶ms) + .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) +} + +/// One syncframe in, one buffer of interleaved f32 out. `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. +fn decode_ac3(decoder: &mut Box, bytes: &[u8]) -> crate::Result>> { + 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) + .collect(), + )), + 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()), + } +} + /// One source's AAC track, resolved once: the reader plus everything the header /// has to say about it. `stts` is copied out because every other field would /// otherwise keep a borrow alive on the reader the worker needs mutably — a real @@ -1416,6 +1634,12 @@ fn run(mut w: Worker) { } continue; } + Track::Ac3(track) => { + if !run_ac3(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) { + return; // consumer went away + } + continue; + } Track::Aac(track) => track, }; let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) @@ -1523,6 +1747,65 @@ fn emit( tx.send(chunk).is_ok() } +/// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids +/// come out of the same mp4 tables, the window rules are [`emit`]'s as always, +/// and what reaches the mixer is already the stereo downmix. `false` means the +/// consumer went away. +fn run_ac3( + track: &mut Ac3Track, + seg: &Segment, + mut eq: Option<&mut EqState>, + channels: usize, + timeline: &mut u64, + tx: &SyncSender, +) -> bool { + let mut decoder = match ac3_decoder(track.requested) { + Ok(decoder) => decoder, + Err(e) => { + eprintln!("audio decoder init failed: {e}"); + return true; + } + }; + let mut pos = seg.start_pos; + for id in seg.start_id..=track.sample_count { + let mut interleaved; + if pos >= seg.media_end { + return true; // segment done, on to the next one + } + let sample = match track.reader.read_sample(track.track_id, id) { + Ok(Some(sample)) => sample, + Ok(None) => return true, + Err(e) => { + eprintln!("audio demux error at sample {id}: {e}"); + return true; + } + }; + match decode_ac3(&mut decoder, &sample.bytes) { + Ok(Some(pcm)) => interleaved = pcm, + Ok(None) => continue, // the decoder wants another frame first + Err(e) => { + eprintln!("audio decode error at sample {id}: {e}"); + return true; + } + } + let next = pos + (interleaved.len() / channels) as u64; + if !emit( + &mut interleaved, + channels, + seg, + eq.as_deref_mut(), + pos, + next, + timeline, + tx, + ) { + return false; + } + pos = next; + } + true +} + /// One segment of a standalone audio file: seek the reader to just before the /// window, then decode forward until the window is filled. /// diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 977b36a..00584e7 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -876,8 +876,9 @@ fn hvcc_record(path: &Path, track_id: u32) -> crate::Result> { /// entry's payload. Read by hand for the same reason the record above is: the /// crate keeps no fourcc for a sample entry it does not recognise, so this is /// the only thing that can tell an `hvc1` track from a track in a codec nothing -/// here reads. -fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec)> { +/// here reads. Shared with `audio`, which asks it the same question of a `soun` +/// track: `mp4a` or the `ac-3` the crate drops on the floor. +pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec)> { let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?; let trak = boxes(&moov) .filter(|(kind, _)| *kind == b"trak") diff --git a/crates/engine/src/waveform.rs b/crates/engine/src/waveform.rs index 10b0129..5c23923 100644 --- a/crates/engine/src/waveform.rs +++ b/crates/engine/src/waveform.rs @@ -165,7 +165,9 @@ mod tests { // that is what this refuses. assert_ne!(zero, one, "both streams drew the same envelope"); assert_ne!(zero[0], one[0], "...and they differ from the first bucket"); - // A stream that does not decode is refused, not drawn as silence. - assert!(peaks(&multi, 2, BPS).is_err(), "AC-3 has no envelope"); + // Stream 2 is AC-3, and it decodes now: it draws its own envelope like + // any other stream rather than being refused. + let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2"); + assert!(!two.is_empty(), "the AC-3 stream drew nothing"); } } diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index 8810491..4348dc4 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -117,24 +117,59 @@ fn video_only_file_has_no_audio() { ); } -/// Sound we cannot decode must not be silence we say nothing about: the AC-3 -/// fixture opens as picture-only and the session carries the reason a -/// front-end shows (`Player::open_media`). +/// Both ends of the AC-3 path decode: the 44.1 kHz **mono** fixture stays the +/// mono source it is, and the 48 kHz **5.1** one — the shape a BluRay remux has +/// — arrives as stereo, downmixed by the decoder itself (A/52 §7.8). Both play +/// their two seconds, at a level that is neither silence nor clipping, and +/// neither owes the session an excuse. #[test] -fn an_undecodable_audio_track_is_named() { - let path = asset("test_ac3.mp4"); +fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { + for (name, rate, channels) in [("test_ac3.mp4", 44100, 1), ("test_ac3_51.mp4", 48000, 2)] { + let path = asset(name); + let (meta, rx) = AudioSession::open(&path) + .expect("open") + .expect("AC-3 decodes now"); + assert_eq!((meta.sample_rate, meta.channels), (rate, channels), "{name}"); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let secs = (samples.len() / channels as usize) as f64 / f64::from(rate); + assert!( + (1.9..2.1).contains(&secs), + "{name} is two seconds, decoded {secs:.3}s" + ); + // The 440 Hz sine survives at a sane level. The vetting caveat was an + // LFE passthrough running hot, which the built-in downmix is what + // avoids; this is that level check, and it is also what catches a + // downmix that comes out silent. + 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" + ); + 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" + ); + } +} + +/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC +/// encoder here -- and that refusal is named, never a silent silent export. +#[test] +fn an_ac3_source_refuses_an_mp4_audio_copy() { + let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else { + panic!("AC-3 cannot become an mp4a track"); + }; + let err = err.to_string(); assert!( - AudioSession::open(&path).expect("open").is_none(), - "AC-3 is not decodable here" - ); - let reason = AudioSession::unsupported(&path) - .expect("probe") - .expect("the file has an audio track, so it owes a reason"); - assert!(reason.contains("decode"), "unhelpful reason: {reason}"); - let session = engine::PlaybackSession::open(&path).expect("open for playback"); - assert_eq!( - session.audio_disabled_reason(), - Some(reason.as_str()), - "the session must carry it to the front-end" + err.contains("needs AAC audio") && err.contains("AC-3"), + "unhelpful refusal: {err}" ); } diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index f77cf26..b93983f 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -305,3 +305,57 @@ fn a_silent_timeline_refuses_an_audio_export() { "nothing written" ); } + +/// An AC-3 source leaves through this door and no other: the mp4 export cannot +/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the +/// same timeline decodes, downmixes and reopens through the engine's own reader. +#[test] +fn a_51_ac3_source_round_trips_through_a_wav() { + let source = asset("test_ac3_51.mp4"); + let project = Project::from_parts( + vec![Source::new(source.clone(), 0)], + vec![( + LaneKind::Audio, + vec![Clip { + start: 0, + in_frame: 0, + out_frame: 30, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + }], + )], + Vec::new(), + Vec::new(), + ) + .expect("a one-source AC-3 project"); + let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0; + + let out = out_path("ac3", "wav"); + let handle = engine::export::start( + project, + video, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source"); + + let (meta, samples) = decode(&out); + assert_eq!( + (meta.sample_rate, meta.channels), + (48_000, 2), + "the §7.8 downmix is what reaches the file" + ); + let secs = (samples.len() / 2) as f64 / 48_000.; + assert!((0.9..1.1).contains(&secs), "one second of clip, got {secs:.3}s"); + let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() + / samples.len() as f64) + .sqrt(); + assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}"); + std::fs::remove_file(&out).unwrap(); +} diff --git a/crates/engine/tests/audio_streams.rs b/crates/engine/tests/audio_streams.rs index f83bbc0..e216f47 100644 --- a/crates/engine/tests/audio_streams.rs +++ b/crates/engine/tests/audio_streams.rs @@ -68,17 +68,17 @@ fn probe_streams_lists_every_audio_track_in_file_order() { lang: Some("fra".into()), decodable: true, }, - // The one we cannot play is listed all the same, so a picker can - // grey it rather than pretend the file has two streams. mp4 0.14 - // keeps no fourcc for a sample entry it does not parse, hence the - // blanks — the row exists, which is the point. + // mp4 0.14 parses no sample entry for AC-3 and keeps no fourcc, so + // this row is described by the AC-3 reader itself: the codec by the + // stsd fourcc read by hand, the rate and the layout by the first + // syncframe. Stereo, because that is what the downmix hands out. StreamInfo { index: 2, - codec: "unknown".into(), - channels: 0, - sample_rate: 0, + codec: "ac-3".into(), + channels: 2, + sample_rate: 44100, lang: None, - decodable: false, + decodable: true, }, ] ); @@ -152,15 +152,14 @@ fn an_impossible_stream_is_refused_not_guessed() { err.to_string().contains("audio stream 3 of 3"), "unhelpful refusal: {err}" ); - // Stream 2 exists but is AC-3: refused with its own message, not decoded - // into noise and not silently swapped for a stream that does decode. + // Stream 2 is AC-3, and a *named* stream is opened by its own reader: it + // decodes to the same 44.1 kHz stereo the AAC stream 0 does, which is what + // lets it share this timeline at all. let ac3 = [(asset(MULTI), 2)]; - let err = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)]) - .expect_err("AC-3 does not decode here"); - assert!( - err.to_string().contains("audio stream 2 is not AAC"), - "unhelpful refusal: {err}" - ); + let (meta, _rx) = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)]) + .expect("AC-3 decodes now") + .expect("the stream is there"); + assert_eq!((meta.sample_rate, meta.channels), (44100, 2)); // A source a *segment* names, opened lazily, refuses just the same. let sources = [(asset(MULTI), 0), (asset(MULTI), 9)]; assert!( diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 51fab68..1393b08 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -48,6 +48,13 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2" \ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ -c:a ac3 -b:a 192k assets/test_ac3.mp4 +# The shape a BluRay remux has: 48 kHz 5.1 AC-3, which the decoder downmixes to +# stereo for the timeline. The mono fixture above is the other end of the same +# path — no downmix at all — and both have to work. +ffmpeg -y -f lavfi -i testsrc2=size=320x180: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 \ + -ac 6 -c:a ac3 -b:a 448k assets/test_ac3_51.mp4 # Multi-language fixture: the shape real media has — one video and two AAC # streams that *agree* on rate and layout (44.1k stereo) and differ only in # language and content, 440/880 Hz undefined and 220/330 Hz French. One