From dff7d843f3d0fedec086d9c2e7e2b68304835ed5 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 07:50:59 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20every=20audio=20str?= =?UTF-8?q?eam=20is=20listed,=20and=20any=20one=20of=20them=20opens?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A remux carries one audio track per language; the engine took whichever AAC track a HashMap handed it first and there was no way to ask for another. - probe_streams() describes every audio track in file order, undecodable ones included (decodable: false) so a picker can grey them rather than hide them - open_multi_streams() takes (path, stream) per source; the old open_multi_segments is a wrapper pinning stream 0, so no caller moved - stream ids come from moov.traks, not the tracks HashMap: "stream 0" was a different track run to run on a multi-track file - a named stream that is missing or not AAC is an Err; stream 0 stays the silent source it always was, because a file we cannot decode the audio of still has a picture worth editing - assets/test_multiaudio.mp4: video + AAC stereo + AAC mono (fra) + AC-3, which covers the picking, the language and the greyed row --- crates/engine/src/audio.rs | 160 ++++++++++++++++++++--- crates/engine/src/lib.rs | 4 +- crates/engine/tests/audio_streams.rs | 181 +++++++++++++++++++++++++++ scripts/gen_fixtures.sh | 17 +++ 4 files changed, 346 insertions(+), 16 deletions(-) create mode 100644 crates/engine/tests/audio_streams.rs diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 9ede29f..ea3e093 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -8,7 +8,7 @@ use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; -use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track}; +use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; use symphonia_codec_aac::AacDecoder; use symphonia_core::codecs::audio::{ AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, @@ -73,6 +73,34 @@ pub struct AudioProbe { pub channels: u16, } +/// One audio stream of a file as its header describes it. Every audio track is +/// described, decodable or not: a picker shows the ones we refuse greyed out +/// rather than pretending a BluRay remux has fewer streams than it has. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StreamInfo { + /// Position among this file's audio tracks in file order — the `stream` + /// [`AudioSession::open_multi_streams`] takes. + pub index: usize, + /// Container codec. + /// + /// ponytail: mp4 0.14 parses `mp4a` sample entries and silently drops every + /// other kind (`stsd.rs` `_ => {}`), keeping no fourcc, so an AC-3/DTS/PCM + /// stream can only be `"unknown"` here — enough to grey a row out, not + /// enough to name the codec. Upgrade path is reading the sample entry's + /// fourcc out of the file ourselves. + pub codec: String, + /// `0` for a stream whose sample entry mp4 0.14 does not parse. + pub channels: u16, + /// `0` for a stream whose sample entry mp4 0.14 does not parse. + pub sample_rate: u32, + /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write. + pub lang: Option, + /// Whether opening this stream would decode: AAC-LC, mono or stereo. The + /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels` + /// make one file at a time. + pub decodable: bool, +} + pub struct AudioSession; impl AudioSession { @@ -132,10 +160,24 @@ impl AudioSession { sources: &[PathBuf], segs: &[(Option, f64, f64)], ) -> crate::Result)>> { - let Some(first) = sources.first() else { + let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect(); + Self::open_multi_streams(&sources, segs) + } + + /// [`open_multi_segments`](Self::open_multi_segments) with each source + /// naming *which* of its audio streams to decode — files carrying several + /// (a remux with one track per language) are otherwise stuck on their first. + /// The index counts audio tracks in file order, as + /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not + /// exist or does not decode is an `Err` here, never a panic. + pub fn open_multi_streams( + sources: &[(PathBuf, usize)], + segs: &[(Option, f64, f64)], + ) -> crate::Result)>> { + let Some((path, stream)) = sources.first() else { return Ok(None); }; - let Some(first) = Track::open(first)? else { + let Some(first) = Track::open(path, *stream)? else { return Ok(None); }; // The timeline's meta is the first source's: policy makes every other @@ -161,7 +203,8 @@ impl AudioSession { if slot.is_some() { continue; // already opened, and the checks below already ran } - let track = Track::open(&sources[source])? + let (path, stream) = &sources[source]; + let track = Track::open(path, *stream)? .ok_or_else(|| format!("source {source} has no audio track"))?; if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { return Err(format!( @@ -221,7 +264,7 @@ impl AudioSession { /// `Ok(None)` means no AAC track — an audio-less file, which import pairs /// only with other audio-less files. pub fn probe(path: impl AsRef) -> crate::Result> { - let Some(track) = Track::open(path.as_ref())? else { + let Some(track) = Track::open(path.as_ref(), 0)? else { return Ok(None); }; Ok(Some(AudioProbe { @@ -230,6 +273,42 @@ impl AudioSession { })) } + /// Every audio stream of `path`, in file order: an entry's `index` is the + /// stream number [`open_multi_streams`](Self::open_multi_streams) takes. + /// Header only, no decoder and no worker — and no filtering either, so a + /// stream this engine cannot decode is listed with `decodable: false` + /// instead of vanishing. + /// + /// An empty list means the file has no audio at all, which is a valid + /// silent source. + pub fn probe_streams(path: impl AsRef) -> crate::Result> { + let file = File::open(path.as_ref())?; + let size = file.metadata()?.len(); + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; + Ok(audio_track_ids(&reader) + .into_iter() + .enumerate() + .map(|(index, id)| { + let track = &reader.tracks()[&id]; + let aac = matches!(track.media_type(), Ok(MediaType::AAC)); + 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()), + lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()), + decodable: aac + && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity)) + && matches!( + track.channel_config(), + Ok(ChannelConfig::Mono | ChannelConfig::Stereo) + ), + } + }) + .collect()) + } + /// The raw AAC packets covering `segs` — the same half-open source-second /// windows [`open_segments`](Self::open_segments) decodes — copied out /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go @@ -284,7 +363,7 @@ impl AudioSession { let path = sources .get(first) .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; - let Some(track) = Track::open(path)? else { + let Some(track) = Track::open(path, 0)? else { return Ok(None); // silent source, silent export }; let params = track.track_params(); @@ -375,6 +454,11 @@ fn silent_packet(chan_conf: u8) -> crate::Result> { /// The source at `index`, opened on first use. Sources a segment list never /// names are never touched: a project's list only grows. +/// +/// ponytail: the copy path is still stream 0 of every source — an export of a +/// timeline playing stream 1 would carry stream 0's audio. Upgrade path is the +/// `(PathBuf, usize)` list [`AudioSession::open_multi_streams`] already takes, +/// which is S4b's job once a stream can be picked at all. fn source_at<'a>( tracks: &'a mut [Option], sources: &[PathBuf], @@ -385,7 +469,7 @@ fn source_at<'a>( .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; if slot.is_none() { *slot = Some( - Track::open(&sources[index])? + Track::open(&sources[index], 0)? .ok_or_else(|| format!("source {index} has no audio track"))?, ); } @@ -415,19 +499,37 @@ struct Track { } impl Track { - /// `Ok(None)` for a file with no AAC track, which is a valid silent source. - fn open(path: &Path) -> crate::Result> { + /// The `stream`-th audio track of `path`, counted in file order over *all* + /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out. + /// + /// Stream 0 is best effort: `Ok(None)` when there is no audio there at all + /// or the codec is one we do not decode, which is a valid silent source (a + /// file whose audio is AC-3 still has a picture worth editing). A stream the + /// caller *named* is a promise instead, so out of range or undecodable + /// there is an `Err` rather than silence the caller did not ask for. + fn open(path: &Path, stream: usize) -> crate::Result> { let file = File::open(path)?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; - let Some(track) = reader - .tracks() - .values() - .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) - else { - return Ok(None); + let ids = audio_track_ids(&reader); + let Some(track) = ids.get(stream).map(|id| &reader.tracks()[id]) else { + return match stream { + 0 => Ok(None), + n => Err(format!( + "{}: audio stream {n} of {} streams", + path.display(), + ids.len() + ) + .into()), + }; }; + if !matches!(track.media_type(), Ok(MediaType::AAC)) { + return match stream { + 0 => Ok(None), + n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()), + }; + } // Refuse early with a message instead of failing packet by packet — and // a copy carries no profile of its own: the writer rebuilds the // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a @@ -529,6 +631,34 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { n } +/// This file's audio tracks in file order — the order a stream index counts in. +/// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a +/// `HashMap`: iterating that would make "stream 0" a different track from one +/// run to the next on any file carrying more than one. +fn audio_track_ids(reader: &Mp4Reader) -> Vec { + reader + .moov + .traks + .iter() + .filter(|trak| { + matches!( + TrackType::try_from(&trak.mdia.hdlr.handler_type), + Ok(TrackType::Audio) + ) + }) + .map(|trak| trak.tkhd.track_id) + .collect() +} + +/// Channels in an AAC channel configuration. The config number *is* the channel +/// count up to 5.1; 7.1 is the one that is not. +fn channel_count(config: ChannelConfig) -> u16 { + match config { + ChannelConfig::SevenOne => 8, + other => other as u16, + } +} + /// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a /// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside /// the crate (same trap as `SttsEntry`, see [`packet_at`]). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aae94c3..2700e0c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -14,7 +14,9 @@ pub mod playback; pub mod project; pub mod waveform; -pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession}; +pub use audio::{ + AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo, +}; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; diff --git a/crates/engine/tests/audio_streams.rs b/crates/engine/tests/audio_streams.rs new file mode 100644 index 0000000..d9a4dd6 --- /dev/null +++ b/crates/engine/tests/audio_streams.rs @@ -0,0 +1,181 @@ +//! Files carry more than one audio track — a remux has one per language — so +//! the engine has to *list* them all and open the one it is asked for, instead +//! of taking whichever AAC track it stumbles on first. + +use std::path::PathBuf; + +use engine::audio::{AudioSession, StreamInfo}; + +/// Three audio streams: 0 is AAC 44.1k stereo (440/880 Hz, und), 1 is AAC +/// 22.05k mono (220 Hz, fra), 2 is AC-3, which we cannot decode. +/// See `scripts/gen_fixtures.sh`. +const MULTI: &str = "test_multiaudio.mp4"; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Everything the worker produced for one stream, flat. +fn decode(name: &str, stream: usize) -> (engine::AudioMeta, Vec) { + let sources = [(asset(name), stream)]; + let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) + .expect("opens") + .expect("has audio"); + let mut samples = Vec::new(); + for chunk in rx { + samples.extend_from_slice(&chunk.samples); + } + (meta, samples) +} + +/// Sign changes, exact zeros ignored: at one tone per channel this is 2f per +/// second per channel. +fn zero_crossings(samples: &[f32]) -> usize { + let (mut crossings, mut last) = (0, 0f32); + for &s in samples { + if s == 0.0 { + continue; + } + if last != 0.0 && (s > 0.0) != (last > 0.0) { + crossings += 1; + } + last = s; + } + crossings +} + +#[test] +fn probe_streams_lists_every_audio_track_in_file_order() { + let streams = AudioSession::probe_streams(asset(MULTI)).expect("probes"); + assert_eq!( + streams, + vec![ + StreamInfo { + index: 0, + codec: "aac".into(), + channels: 2, + sample_rate: 44100, + lang: None, // the `und` every muxer writes by default + decodable: true, + }, + StreamInfo { + index: 1, + codec: "aac".into(), + channels: 1, + sample_rate: 22050, + 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. + StreamInfo { + index: 2, + codec: "unknown".into(), + channels: 0, + sample_rate: 0, + lang: None, + decodable: false, + }, + ] + ); + // File order, run to run: `Mp4Reader::tracks` is a HashMap, so a careless + // enumeration would shuffle these two. + for _ in 0..8 { + let again = AudioSession::probe_streams(asset(MULTI)).expect("probes"); + assert_eq!(again, streams); + } +} + +#[test] +fn probe_streams_on_one_track_and_on_none() { + let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes"); + assert_eq!(one.len(), 1, "test_av.mp4 has a single audio track"); + assert_eq!( + (one[0].index, one[0].sample_rate, one[0].channels), + (0, 44100, 2) + ); + assert!(one[0].decodable); + // No audio at all is an empty list, not an error: a silent source is valid. + assert!( + AudioSession::probe_streams(asset("test_baseline.mp4")) + .expect("probes") + .is_empty() + ); +} + +#[test] +fn a_named_stream_decodes_that_stream_and_not_the_first() { + let (meta, samples) = decode(MULTI, 1); + assert_eq!((meta.sample_rate, meta.channels), (22050, 1)); + // 220 Hz mono is 2 crossings a period. Measured over the middle half only: + // the encoder's ramp-in and the container's tail padding are low-level + // noise that crosses zero far more often than the tone does. + let middle = &samples[samples.len() / 4..samples.len() * 3 / 4]; + let expected = 2.0 * 220.0 * middle.len() as f64 / 22050.0; + let crossings = zero_crossings(middle) as f64; + assert!( + (crossings - expected).abs() < 0.05 * expected, + "stream 1 is {crossings} crossings, 220 Hz mono would be {expected}" + ); + assert!(samples.len() > 22050, "less than a second of stream 1"); + + // Stream 0 of the same file is the other one entirely. + let (meta, _) = decode(MULTI, 0); + assert_eq!((meta.sample_rate, meta.channels), (44100, 2)); +} + +#[test] +fn stream_0_stays_exactly_what_the_wrapper_gave() { + // The default wrapper and stream 0 are the same track, sample for sample. + let (wrapped, rx) = AudioSession::open(asset(MULTI)) + .expect("opens") + .expect("audio"); + let mut plain = Vec::new(); + for chunk in rx { + plain.extend_from_slice(&chunk.samples); + } + let (meta, named) = decode(MULTI, 0); + assert_eq!(wrapped, meta); + assert_eq!(plain, named); +} + +#[test] +fn an_impossible_stream_is_refused_not_guessed() { + let out_of_range = [(asset(MULTI), 3)]; + let err = AudioSession::open_multi_streams(&out_of_range, &[(Some(0), 0.0, 1.0)]) + .expect_err("stream 3 of 3 does not exist"); + assert!( + 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. + 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}" + ); + // A source a *segment* names, opened lazily, refuses just the same. + let sources = [(asset(MULTI), 0), (asset(MULTI), 9)]; + assert!( + AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]) + .is_err(), + "a second source's bad stream index has to refuse too" + ); + + // Stream 0 of a file with no audio is still the silent source it always + // was; a *named* stream of one is a promise the file cannot keep. + let silent = asset("test_baseline.mp4"); + assert!( + AudioSession::open_multi_streams(&[(silent.clone(), 0)], &[(Some(0), 0.0, 1.0)]) + .expect("no audio is not an error") + .is_none() + ); + assert!(AudioSession::open_multi_streams(&[(silent, 1)], &[(Some(0), 0.0, 1.0)]).is_err()); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index c1255d3..0e2c38b 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -25,6 +25,23 @@ ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30:duration=4 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av2.mp4 +# Multi-audio fixture: one video and three audio streams, so stream selection +# has something to select. Stream 0 is AAC 44.1k stereo (440 Hz left, 880 Hz +# right), stream 1 is AAC 22.05k mono 220 Hz tagged French — different rate, +# layout and content, so a test can tell which stream it was handed — and +# stream 2 is AC-3, the codec we cannot decode and must still list. +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -f lavfi -i "sine=frequency=220:duration=2" \ + -f lavfi -i "sine=frequency=330:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a0]" \ + -map 0:v -map "[a0]" -map 3:a -map 4:a \ + -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a:0 aac -ar:a:0 44100 -ac:a:0 2 \ + -c:a:1 aac -ar:a:1 22050 -ac:a:1 1 \ + -c:a:2 ac3 -ar:a:2 44100 -ac:a:2 2 \ + -metadata:s:a:1 language=fra assets/test_multiaudio.mp4 # Mismatch fixture: different resolution and no audio track at all, so import # has something concrete to refuse. ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \