forge
Explore
Log in

Don't you dare go Hollow

An mkv's stream 0 is the track it already played, not its first

Browse files at this commit

a7dd4c5cd319b11d45001ad524b7d030d7b02eabAhmet Kaan GümüşParent: cd8f9fa
  • fix
    • an mkv's stream 0 is the track it already played, not its first
Show full message
🩹 fix(audio): an mkv's stream 0 is the track it already played, not its first

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 every reader here picked with that flag. Numbering the streams by
file position outright made stream 0 a different track on those files,
so an .edith project saved before the listing existed would quietly
start playing the other language.

mkv_stream_order puts the track the file already plays first and the
rest behind it in file order, and it does not re-derive the old pick, it
runs it: the AC-3 arm asks MkvAc3Track the same question Track::open
asked it, everything else asks symphonia for its default track.
probe_streams, Track::open and therefore the library's rows all count in
that one order.

Tested on a byte-patched fixture -- ffmpeg writes FlagDefault only to
say 0, so the one byte behind the French track's language is flipped to
1 -- and it fails on file-order numbering: eng leads instead of fra.
crates/engine/src/audio.rsmodified+69 -16
@@ -712,17 +712,20 @@ impl AudioSession {
712 /// and an ALAC `.m4a` only half is.712 /// and an ALAC `.m4a` only half is.
713 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {713 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
714 let path = path.as_ref();714 let path = path.as_ref();
715- // A Matroska file lists one row per `TrackEntry` of audio, in the order715+ // A Matroska file lists one row per `TrackEntry` of audio -- a
716- // its `Tracks` element gives them -- a dual-audio remux has two, and the716+ // dual-audio remux has two, and the second one used to be invisible --
717- // second one used to be invisible. A file whose header will not walk at717+ // numbered by [`mkv_stream_order`]: the track that already plays first,
718- // all is an `Err` here, as it is in [`Track::open`]: a listing that718+ // then the rest in file order. A file whose header will not walk at all
719- // quietly came back empty for a broken file is how a lane ends up silent719+ // is an `Err` here, as it is in [`Track::open`]: a listing that quietly
720- // with nothing to go on. No audio track at all is an empty list, which720+ // came back empty for a broken file is how a lane ends up silent with
721- // is the silent source it says it is.721+ // nothing to go on. No audio track at all is an empty list, which is
722+ // the silent source it says it is.
722 if crate::demux::is_matroska(path) {723 if crate::demux::is_matroska(path) {
724+ let tracks = crate::demux::matroska_audio_tracks(path)?;
723 let mut streams = Vec::new();725 let mut streams = Vec::new();
724- for (index, entry) in crate::demux::matroska_audio_tracks(path)?726+ for (index, entry) in mkv_stream_order(path, &tracks)
725- .iter()727+ .into_iter()
728+ .map(|at| &tracks[at])
726 .enumerate()729 .enumerate()
727 {730 {
728 // The routing [`Track::open`] does, one row at a time, so a row731 // The routing [`Track::open`] does, one row at a time, so a row
@@ -1138,17 +1141,19 @@ impl Track {
1138 // failing the import of a file whose picture is fine. A track that will1141 // failing the import of a file whose picture is fine. A track that will
1139 // not open at all is *not* in that group: see below.1142 // not open at all is *not* in that group: see below.
1140 if crate::demux::is_matroska(path) {1143 if crate::demux::is_matroska(path) {
1141- // File order, the one `probe_streams` lists and a project saves:1144+ // The numbering `probe_streams` lists and a project saves, from the
1142- // the stream index picks a `TrackEntry`, that entry's *track1145+ // one function that decides it ([`mkv_stream_order`]): the stream
1143- // number* is what both readers are then pointed at. Positions are1146+ // index picks a `TrackEntry`, that entry's *track number* is what
1144- // never handed to a reader -- symphonia's own order is its business1147+ // both readers are then pointed at. Positions are never handed to a
1145- // -- because a mapping that drifts plays the wrong language and1148+ // reader -- symphonia's own order is its business -- because a
1146- // saves it into the project.1149+ // mapping that drifts plays the wrong language and saves it into
1150+ // the project.
1147 let tracks = crate::demux::matroska_audio_tracks(path)?;1151 let tracks = crate::demux::matroska_audio_tracks(path)?;
1148 if tracks.is_empty() {1152 if tracks.is_empty() {
1149 return Ok(None);1153 return Ok(None);
1150 }1154 }
1151- let Some(entry) = tracks.get(stream) else {1155+ let order = mkv_stream_order(path, &tracks);
1156+ let Some(entry) = order.get(stream).map(|at| &tracks[*at]) else {
1152 return Err(format!(1157 return Err(format!(
1153 "{}: audio stream {stream} of {} stream{}",1158 "{}: audio stream {stream} of {} stream{}",
1154 path.display(),1159 path.display(),
@@ -1955,6 +1960,54 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
1955 n1960 n
1956 }1961 }
1957 1962
1963+/// The order a Matroska file's audio streams are numbered in, as positions into
1964+/// `tracks` (which is file order): **stream 0 is the track this project has
1965+/// always opened**, and the rest follow in file order behind it.
1966+///
1967+/// Not file order outright, and the difference is a saved project's sound. A
1968+/// remux flags the language it wants heard with `FlagDefault` on whichever
1969+/// track it likes -- mkvmerge writes it on the second one all the time -- and
1970+/// that flag is what every reader here used to pick with. Numbering by file
1971+/// position would have made stream 0 a *different* track on those files, so an
1972+/// `.edith` project saved before this would quietly start playing the other
1973+/// language. Nothing that already plays may change what it plays.
1974+///
1975+/// The old pick is not re-derived here, it is *run*: the AC-3 arm asks
1976+/// [`MkvAc3Track`] the same question [`Track::open`] asked it (and only of the
1977+/// file's first audio track, which is as far as [`crate::demux::MkvAudio`]
1978+/// ever looked), and everything else asks symphonia for its default track,
1979+/// which is `FlagDefault` where a muxer set one and the first readable track
1980+/// where nobody did.
1981+fn mkv_stream_order(path: &Path, tracks: &[crate::demux::MkvAudioTrack]) -> Vec<usize> {
1982+ // One track is its own order, and it is the common case: no second probe
1983+ // for the file that cannot have a second answer.
1984+ if tracks.len() < 2 {
1985+ return (0..tracks.len()).collect();
1986+ }
1987+ let head = match tracks.first() {
1988+ Some(first)
1989+ if matches!(first.codec.as_str(), "A_AC3" | "A_EAC3")
1990+ && matches!(MkvAc3Track::open_track(path, first.number), Ok(Some(_))) =>
1991+ {
1992+ 0
1993+ }
1994+ // A file symphonia will not open at all keeps file order: the open
1995+ // itself is where that failure is reported, not the numbering.
1996+ _ => SymTrack::open(path)
1997+ .ok()
1998+ .flatten()
1999+ .and_then(|track| {
2000+ tracks
2001+ .iter()
2002+ .position(|entry| entry.number == u64::from(track.track_id))
2003+ })
2004+ .unwrap_or(0),
2005+ };
2006+ std::iter::once(head)
2007+ .chain((0..tracks.len()).filter(|i| *i != head))
2008+ .collect()
2009+}
2010+
1958 /// The name a Matroska audio row wears: the container's own codec id, cut down2011 /// The name a Matroska audio row wears: the container's own codec id, cut down
1959 /// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`.2012 /// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`.
1960 ///2013 ///
crates/engine/tests/audio_streams.rsmodified+66 -0
@@ -169,6 +169,72 @@ fn a_named_matroska_stream_decodes_that_stream_and_not_the_first() {
169 );169 );
170 }170 }
171 171
172+/// Stream 0 is the track the file already played, not the first one in the
173+/// file: a remux flags the language it wants heard with `FlagDefault` on
174+/// whichever track it likes, every reader here picked with that flag, and an
175+/// `.edith` project saved before this listing existed must keep playing what it
176+/// was saved with. Numbering by file position outright would switch its audio
177+/// silently.
178+///
179+/// The flag is byte-patched in rather than muxed: ffmpeg writes `FlagDefault`
180+/// only to say *0*, so the fixture's second track carries `88 81 00` and the
181+/// one byte is flipped here -- same length, same offsets, a file mkvmerge could
182+/// have written.
183+#[test]
184+fn flag_default_on_a_later_track_is_still_stream_0() {
185+ let mut bytes = std::fs::read(asset(MULTI_MKV)).expect("read the fixture");
186+ // `TrackLanguage` "fra" is the second audio `TrackEntry`; its `FlagDefault`
187+ // sits right behind it.
188+ let language = b"\x22\xb5\x9c\x83fra";
189+ let at = bytes
190+ .windows(language.len())
191+ .position(|w| w == language)
192+ .expect("the fixture's French track")
193+ + language.len();
194+ assert_eq!(
195+ &bytes[at..at + 3],
196+ b"\x88\x81\x00",
197+ "the fixture stopped carrying an explicit FlagDefault=0"
198+ );
199+ bytes[at + 2] = 1;
200+ let patched = std::env::temp_dir().join(format!("ve_flagdefault_{}.mkv", std::process::id()));
201+ std::fs::write(&patched, &bytes).expect("write the patched file");
202+
203+ // The flagged track leads: it is what `AudioSession::open` played before
204+ // any of this, so it is stream 0 -- and the other one is still listed,
205+ // behind it.
206+ let streams = AudioSession::probe_streams(&patched).expect("probes");
207+ assert_eq!(
208+ streams.iter().map(|s| s.lang.clone()).collect::<Vec<_>>(),
209+ vec![Some("fra".into()), Some("eng".into())],
210+ "the default track has to lead: {streams:?}"
211+ );
212+ assert_eq!((streams[0].index, streams[1].index), (0, 1));
213+
214+ // ...and it decodes to what it always decoded to: 220 Hz, the French
215+ // track's tone, sample for sample what the wrapper hands out.
216+ let (wrapped, rx) = AudioSession::open(&patched).expect("opens").expect("audio");
217+ let played: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
218+ let sources = [(patched.clone(), 0)];
219+ let (meta, stream_0) = {
220+ let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
221+ .expect("opens")
222+ .expect("audio");
223+ (meta, rx.into_iter().flat_map(|c| c.samples).collect::<Vec<f32>>())
224+ };
225+ assert_eq!(wrapped, meta);
226+ assert_eq!(played, stream_0, "stream 0 is not what the file plays");
227+ let left: Vec<f32> = stream_0.chunks(2).map(|c| c[0]).collect();
228+ let middle = &left[left.len() / 4..left.len() * 3 / 4];
229+ let expected = 2.0 * 220.0 * middle.len() as f64 / 44100.0;
230+ let crossings = zero_crossings(middle) as f64;
231+ assert!(
232+ (crossings - expected).abs() < 0.05 * expected,
233+ "stream 0 is {crossings} crossings, the French track's 220 Hz would be {expected}"
234+ );
235+ std::fs::remove_file(&patched).unwrap();
236+}
237+
172 /// The file the ask came from: a dual-audio Blu-ray rip, two AAC tracks, and238 /// The file the ask came from: a dual-audio Blu-ray rip, two AAC tracks, and
173 /// the second one has to play. Existence-gated -- it is not in the repo.239 /// the second one has to play. Existence-gated -- it is not in the repo.
174 #[test]240 #[test]