diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 6f36428..e14ef0c 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -712,17 +712,20 @@ impl AudioSession { /// and an ALAC `.m4a` only half is. pub fn probe_streams(path: impl AsRef) -> crate::Result> { let path = path.as_ref(); - // A Matroska file lists one row per `TrackEntry` of audio, in the order - // its `Tracks` element gives them -- a dual-audio remux has two, and the - // second one used to be invisible. A file whose header will not walk at - // all is an `Err` here, as it is in [`Track::open`]: a listing that - // quietly came back empty for a broken file is how a lane ends up silent - // with nothing to go on. No audio track at all is an empty list, which - // is the silent source it says it is. + // A Matroska file lists one row per `TrackEntry` of audio -- a + // dual-audio remux has two, and the second one used to be invisible -- + // numbered by [`mkv_stream_order`]: the track that already plays first, + // then the rest in file order. A file whose header will not walk at all + // is an `Err` here, as it is in [`Track::open`]: a listing that quietly + // came back empty for a broken file is how a lane ends up silent with + // nothing to go on. No audio track at all is an empty list, which is + // the silent source it says it is. if crate::demux::is_matroska(path) { + let tracks = crate::demux::matroska_audio_tracks(path)?; let mut streams = Vec::new(); - for (index, entry) in crate::demux::matroska_audio_tracks(path)? - .iter() + for (index, entry) in mkv_stream_order(path, &tracks) + .into_iter() + .map(|at| &tracks[at]) .enumerate() { // The routing [`Track::open`] does, one row at a time, so a row @@ -1138,17 +1141,19 @@ impl Track { // failing the import of a file whose picture is fine. A track that will // not open at all is *not* in that group: see below. if crate::demux::is_matroska(path) { - // File order, the one `probe_streams` lists and a project saves: - // the stream index picks a `TrackEntry`, that entry's *track - // number* is what both readers are then pointed at. Positions are - // never handed to a reader -- symphonia's own order is its business - // -- because a mapping that drifts plays the wrong language and - // saves it into the project. + // The numbering `probe_streams` lists and a project saves, from the + // one function that decides it ([`mkv_stream_order`]): the stream + // index picks a `TrackEntry`, that entry's *track number* is what + // both readers are then pointed at. Positions are never handed to a + // reader -- symphonia's own order is its business -- because a + // mapping that drifts plays the wrong language and saves it into + // the project. let tracks = crate::demux::matroska_audio_tracks(path)?; if tracks.is_empty() { return Ok(None); } - let Some(entry) = tracks.get(stream) else { + let order = mkv_stream_order(path, &tracks); + let Some(entry) = order.get(stream).map(|at| &tracks[*at]) else { return Err(format!( "{}: audio stream {stream} of {} stream{}", path.display(), @@ -1955,6 +1960,54 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { n } +/// The order a Matroska file's audio streams are numbered in, as positions into +/// `tracks` (which is file order): **stream 0 is the track this project has +/// always opened**, and the rest follow in file order behind it. +/// +/// Not file order outright, and the difference is a saved project's sound. A +/// remux flags the language it wants heard with `FlagDefault` on whichever +/// track it likes -- mkvmerge writes it on the second one all the time -- and +/// that flag is what every reader here used to pick with. Numbering by file +/// position would have made stream 0 a *different* track on those files, so an +/// `.edith` project saved before this would quietly start playing the other +/// language. Nothing that already plays may change what it plays. +/// +/// The old pick is not re-derived here, it is *run*: the AC-3 arm asks +/// [`MkvAc3Track`] the same question [`Track::open`] asked it (and only of the +/// file's first audio track, which is as far as [`crate::demux::MkvAudio`] +/// ever looked), and everything else asks symphonia for its default track, +/// which is `FlagDefault` where a muxer set one and the first readable track +/// where nobody did. +fn mkv_stream_order(path: &Path, tracks: &[crate::demux::MkvAudioTrack]) -> Vec { + // One track is its own order, and it is the common case: no second probe + // for the file that cannot have a second answer. + if tracks.len() < 2 { + return (0..tracks.len()).collect(); + } + let head = match tracks.first() { + Some(first) + if matches!(first.codec.as_str(), "A_AC3" | "A_EAC3") + && matches!(MkvAc3Track::open_track(path, first.number), Ok(Some(_))) => + { + 0 + } + // A file symphonia will not open at all keeps file order: the open + // itself is where that failure is reported, not the numbering. + _ => SymTrack::open(path) + .ok() + .flatten() + .and_then(|track| { + tracks + .iter() + .position(|entry| entry.number == u64::from(track.track_id)) + }) + .unwrap_or(0), + }; + std::iter::once(head) + .chain((0..tracks.len()).filter(|i| *i != head)) + .collect() +} + /// The name a Matroska audio row wears: the container's own codec id, cut down /// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`. /// diff --git a/crates/engine/tests/audio_streams.rs b/crates/engine/tests/audio_streams.rs index e7a29c3..c117b21 100644 --- a/crates/engine/tests/audio_streams.rs +++ b/crates/engine/tests/audio_streams.rs @@ -169,6 +169,72 @@ fn a_named_matroska_stream_decodes_that_stream_and_not_the_first() { ); } +/// Stream 0 is the track the file already played, not the first one in the +/// file: a remux flags the language it wants heard with `FlagDefault` on +/// whichever track it likes, every reader here picked with that flag, and an +/// `.edith` project saved before this listing existed must keep playing what it +/// was saved with. Numbering by file position outright would switch its audio +/// silently. +/// +/// The flag is byte-patched in rather than muxed: ffmpeg writes `FlagDefault` +/// only to say *0*, so the fixture's second track carries `88 81 00` and the +/// one byte is flipped here -- same length, same offsets, a file mkvmerge could +/// have written. +#[test] +fn flag_default_on_a_later_track_is_still_stream_0() { + let mut bytes = std::fs::read(asset(MULTI_MKV)).expect("read the fixture"); + // `TrackLanguage` "fra" is the second audio `TrackEntry`; its `FlagDefault` + // sits right behind it. + let language = b"\x22\xb5\x9c\x83fra"; + let at = bytes + .windows(language.len()) + .position(|w| w == language) + .expect("the fixture's French track") + + language.len(); + assert_eq!( + &bytes[at..at + 3], + b"\x88\x81\x00", + "the fixture stopped carrying an explicit FlagDefault=0" + ); + bytes[at + 2] = 1; + let patched = std::env::temp_dir().join(format!("ve_flagdefault_{}.mkv", std::process::id())); + std::fs::write(&patched, &bytes).expect("write the patched file"); + + // The flagged track leads: it is what `AudioSession::open` played before + // any of this, so it is stream 0 -- and the other one is still listed, + // behind it. + let streams = AudioSession::probe_streams(&patched).expect("probes"); + assert_eq!( + streams.iter().map(|s| s.lang.clone()).collect::>(), + vec![Some("fra".into()), Some("eng".into())], + "the default track has to lead: {streams:?}" + ); + assert_eq!((streams[0].index, streams[1].index), (0, 1)); + + // ...and it decodes to what it always decoded to: 220 Hz, the French + // track's tone, sample for sample what the wrapper hands out. + let (wrapped, rx) = AudioSession::open(&patched).expect("opens").expect("audio"); + let played: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let sources = [(patched.clone(), 0)]; + let (meta, stream_0) = { + let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) + .expect("opens") + .expect("audio"); + (meta, rx.into_iter().flat_map(|c| c.samples).collect::>()) + }; + assert_eq!(wrapped, meta); + assert_eq!(played, stream_0, "stream 0 is not what the file plays"); + let left: Vec = stream_0.chunks(2).map(|c| c[0]).collect(); + let middle = &left[left.len() / 4..left.len() * 3 / 4]; + let expected = 2.0 * 220.0 * middle.len() as f64 / 44100.0; + let crossings = zero_crossings(middle) as f64; + assert!( + (crossings - expected).abs() < 0.05 * expected, + "stream 0 is {crossings} crossings, the French track's 220 Hz would be {expected}" + ); + std::fs::remove_file(&patched).unwrap(); +} + /// The file the ask came from: a dual-audio Blu-ray rip, two AAC tracks, and /// the second one has to play. Existence-gated -- it is not in the repo. #[test]