forge
Explore
Log in

Don't you dare go Hollow

Every audio track of an mkv is a row, and the second one plays

Browse files at this commit

264c10cb1283bef8c9fc4abec02360e65520f933Ahmet Kaan GümüşParent: 0a39fae
  • feat
    • every audio track of an mkv is a row, and the second one plays
Show full message
✨ feat(audio): every audio track of an mkv is a row, and the second one plays

A Matroska file was worth exactly one audio stream here -- whichever
track the readers stumbled on first -- so the second language of a
dual-audio remux was invisible and unopenable, and no mkv ever showed
what language its sound was in.

The header walk now collects every audio TrackEntry in file order with
its number, codec id, TrackLanguage and TrackName
(demux::matroska_audio_tracks), and that list is what a stream index
counts in. The index picks an entry, the entry's *track number* is what
each reader is then pointed at -- MkvAudio::open_track for the AC-3
blocks, SymTrack::open_track for symphonia, whose mkv reader keeps the
same number as its track id -- so the two readers cannot disagree about
which track a stream meant. Stream 0 is still the file's first audio
track, sample for sample.

Rows name their codec from the container rather than from symphonia's
registry: the tracks that most need naming are exactly the ones it has
no decoder for, and "opus is not supported" beats "an unsupported
format".

Fixture: test_multiaudio.mkv, two AAC tracks, eng 440/880 Hz and fra
220/330 Hz -- different tones because a mapping that drifts plays the
other language.
crates/engine/src/audio.rsmodified+120 -38
@@ -712,40 +712,55 @@ impl AudioSession {
712712 /// and an ALAC `.m4a` only half is.
713713 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
714714 let path = path.as_ref();
715- // A Matroska file has exactly one readable audio stream here -- the
716- // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one
717- // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a
718- // standalone audio file rather than like an mp4, and one with no
719- // readable track at all lists as the silent source it is.
715+ // A Matroska file lists one row per `TrackEntry` of audio, in the order
716+ // its `Tracks` element gives them -- a dual-audio remux has two, and the
717+ // second one used to be invisible. A file whose header will not walk at
718+ // all is an `Err` here, as it is in [`Track::open`]: a listing that
719+ // quietly came back empty for a broken file is how a lane ends up silent
720+ // with nothing to go on. No audio track at all is an empty list, which
721+ // is the silent source it says it is.
720722 if crate::demux::is_matroska(path) {
721- // The AC-3 row describes what the decoder *emits*, which is the
722- // stereo the §7.8 downmix hands the timeline, not the 5.1 the file
723- // carries -- exactly as the mp4 AC-3 rows do.
724- if let Ok(Some(track)) = MkvAc3Track::open(path) {
725- return Ok(vec![StreamInfo {
726- index: 0,
727- codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(),
728- channels: track.channels,
729- sample_rate: track.sample_rate,
730- lang: None,
731- decodable: matches!(track.channels, 1 | 2),
732- }]);
723+ let mut streams = Vec::new();
724+ for (index, entry) in crate::demux::matroska_audio_tracks(path)?
725+ .iter()
726+ .enumerate()
727+ {
728+ // The routing [`Track::open`] does, one row at a time, so a row
729+ // describes the track that would really open: AC-3 and E-AC-3
730+ // through the Dolby decoder's own reader, everything else
731+ // through symphonia. The AC-3 row describes what the decoder
732+ // *emits*, which is the stereo the §7.8 downmix hands the
733+ // timeline, not the 5.1 the file carries -- exactly as the mp4
734+ // AC-3 rows do.
735+ let ac3 = matches!(entry.codec.as_str(), "A_AC3" | "A_EAC3")
736+ .then(|| MkvAc3Track::open_track(path, entry.number).ok().flatten())
737+ .flatten();
738+ // A track symphonia cannot even describe is listed undecodable
739+ // by the name the container gives it, rather than taking the
740+ // whole listing down with it: the other language still plays.
741+ let sym = match &ac3 {
742+ Some(_) => None,
743+ None => SymTrack::open_track(path, entry.number).ok().flatten(),
744+ };
745+ let channels = ac3.as_ref().map_or_else(
746+ || sym.as_ref().map_or(0, |t| t.channels),
747+ |t| t.channels,
748+ );
749+ streams.push(StreamInfo {
750+ index,
751+ codec: mkv_codec_name(&entry.codec),
752+ channels,
753+ sample_rate: ac3.as_ref().map_or_else(
754+ || sym.as_ref().map_or(0, |t| t.sample_rate),
755+ |t| t.sample_rate,
756+ ),
757+ lang: (entry.language != "und" && !entry.language.is_empty())
758+ .then(|| entry.language.clone()),
759+ decodable: matches!(channels, 1 | 2)
760+ && (ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok())),
761+ });
733762 }
734- // No audio track lists as the silent source it is; a track that
735- // will not open at all is an `Err` here, as it is in
736- // [`Track::open`] -- a listing that quietly came back empty for a
737- // broken file is how a lane ends up silent with nothing to go on.
738- let Some(track) = SymTrack::open(path)? else {
739- return Ok(Vec::new());
740- };
741- return Ok(vec![StreamInfo {
742- index: 0,
743- codec: track.codec.into(),
744- channels: track.channels,
745- sample_rate: track.sample_rate,
746- lang: None,
747- decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(),
748- }]);
763+ return Ok(streams);
749764 }
750765 if crate::is_audio(path) {
751766 let track = SymTrack::open_required(path)?;
@@ -1123,10 +1138,26 @@ impl Track {
11231138 // failing the import of a file whose picture is fine. A track that will
11241139 // not open at all is *not* in that group: see below.
11251140 if crate::demux::is_matroska(path) {
1126- if stream > 0 {
1127- return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
1141+ // File order, the one `probe_streams` lists and a project saves:
1142+ // the stream index picks a `TrackEntry`, that entry's *track
1143+ // number* is what both readers are then pointed at. Positions are
1144+ // never handed to a reader -- symphonia's own order is its business
1145+ // -- because a mapping that drifts plays the wrong language and
1146+ // saves it into the project.
1147+ let tracks = crate::demux::matroska_audio_tracks(path)?;
1148+ if tracks.is_empty() {
1149+ return Ok(None);
11281150 }
1129- match MkvAc3Track::open(path) {
1151+ let Some(entry) = tracks.get(stream) else {
1152+ return Err(format!(
1153+ "{}: audio stream {stream} of {} stream{}",
1154+ path.display(),
1155+ tracks.len(),
1156+ if tracks.len() == 1 { "" } else { "s" }
1157+ )
1158+ .into());
1159+ };
1160+ match MkvAc3Track::open_track(path, entry.number) {
11301161 Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
11311162 Ok(None) => {}
11321163 // Named on the way past rather than returned: symphonia gets the
@@ -1142,7 +1173,7 @@ impl Track {
11421173 // same answer the mp4 arm gives: turned into silence it would play
11431174 // and export as a hole with only an eprintln to say why, which is a
11441175 // bug wearing a feature's clothes.
1145- let Some(track) = SymTrack::open(path)? else {
1176+ let Some(track) = SymTrack::open_track(path, entry.number)? else {
11461177 return Ok(None);
11471178 };
11481179 if let Err(e) = track.decoder() {
@@ -1311,6 +1342,22 @@ impl SymTrack {
13111342 /// difference matters because silence is played and exported without a word
13121343 /// while an `Err` is shown ([`Track::open`]).
13131344 fn open(path: &Path) -> crate::Result<Option<Self>> {
1345+ Self::open_inner(path, None)
1346+ }
1347+
1348+ /// [`open`](Self::open) pointed at one **named** track: a Matroska
1349+ /// `TrackNumber`, which symphonia keeps as the track's id
1350+ /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second
1351+ /// language of a dual-audio file reachable, and it is matched by number
1352+ /// rather than by position so this reader and
1353+ /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which
1354+ /// track a stream index meant. `Ok(None)` for a number the reader does not
1355+ /// carry.
1356+ fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
1357+ Self::open_inner(path, Some(number))
1358+ }
1359+
1360+ fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
13141361 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
13151362 // The extension is a hint, not a decision: the probe reads the magic and
13161363 // is free to disagree, which is what makes a mislabelled file work.
@@ -1324,7 +1371,14 @@ impl SymTrack {
13241371 FormatOptions::default(),
13251372 MetadataOptions::default(),
13261373 )?;
1327- let Some(track) = reader.default_track(SymKind::Audio) else {
1374+ let track = match number {
1375+ Some(number) => reader
1376+ .tracks()
1377+ .iter()
1378+ .find(|t| u64::from(t.id) == number),
1379+ None => reader.default_track(SymKind::Audio),
1380+ };
1381+ let Some(track) = track else {
13281382 return Ok(None);
13291383 };
13301384 // `track.delay` is deliberately not read: see the `priming` field.
@@ -1611,7 +1665,19 @@ impl MkvAc3Track {
16111665 /// that is one and could not be read, which
16121666 /// [`AudioSession::unsupported`] quotes back to the user.
16131667 fn open(path: &Path) -> crate::Result<Option<Self>> {
1614- let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else {
1668+ Self::from_blocks(crate::demux::MkvAudio::open(path)?)
1669+ }
1670+
1671+ /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]),
1672+ /// which is how the AC-3 half of a dual-audio file is reached.
1673+ ///
1674+ /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number
1675+ fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
1676+ Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?)
1677+ }
1678+
1679+ fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> {
1680+ let Some(mut mkv) = mkv else {
16151681 return Ok(None);
16161682 };
16171683 let first = mkv
@@ -1889,6 +1955,22 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
18891955 n
18901956 }
18911957
1958+/// 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`.
1960+///
1961+/// The codec id rather than symphonia's short name, because the rows that most
1962+/// need naming are exactly the ones it has no decoder for: an Opus or DTS track
1963+/// is greyed out with the codec in the reason (`unusable` in the app reads this
1964+/// very string), where symphonia would call it "an unsupported format".
1965+fn mkv_codec_name(id: &str) -> String {
1966+ match id {
1967+ "A_AC3" => "ac-3".into(),
1968+ "A_EAC3" => "e-ac-3".into(),
1969+ "A_MPEG/L3" => "mp3".into(),
1970+ _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(),
1971+ }
1972+}
1973+
18921974 /// This file's audio tracks in file order — the order a stream index counts in.
18931975 /// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a
18941976 /// `HashMap`: iterating that would make "stream 0" a different track from one
crates/engine/src/demux.rsmodified+86 -25
@@ -512,10 +512,35 @@ impl MkvDemuxer {
512512 /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and
513513 /// this exists to say which codec neither of them took.
514514 pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
515+ Ok(matroska_audio_tracks(path)?.into_iter().next().map(|t| t.codec))
516+}
517+
518+/// One audio `TrackEntry` of a Matroska file, as the header describes it.
519+pub struct MkvAudioTrack {
520+ /// `TrackNumber`: what this track's blocks are stamped with ([`MkvAudio`]),
521+ /// and the id symphonia keeps for the same track. *Not* a position -- a
522+ /// file's first audio track is number 2 as often as not.
523+ pub number: u64,
524+ /// The Matroska codec id: `A_AAC`, `A_EAC3`, `A_DTS`, ...
525+ pub codec: String,
526+ /// `TrackLanguage`, `"und"` for an entry that declares none (the spec's own
527+ /// default), which is what a muxer writes when nobody said.
528+ pub language: String,
529+ /// `TrackName` -- "Japanese 5.1", "Commentary" -- empty when there is none.
530+ pub name: String,
531+ /// What this track's blocks have to be put back through.
532+ unpack: Unpack,
533+}
534+
535+/// Every audio track of a Matroska file, in file order: the numbering
536+/// [`crate::AudioSession::probe_streams`] hands out, and the one a dual-audio
537+/// remux is picked from. Header only, like [`matroska_audio_codec`], and an
538+/// empty list is a file with no sound at all rather than an error.
539+pub fn matroska_audio_tracks(path: &Path) -> crate::Result<Vec<MkvAudioTrack>> {
515540 let mut file = File::open(path)?;
516541 let end = file.metadata()?.len();
517542 let segment = mkv_segment(&mut file, end)?;
518- Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec, _)| codec))
543+ Ok(mkv_tracks(&mut file, segment)?.1)
519544 }
520545
521546 /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio
@@ -543,12 +568,36 @@ impl MkvAudio {
543568 /// is in a codec nothing here decodes -- that file is the silent source it
544569 /// has always been, and [`crate::audio::AudioSession::unsupported`] names
545570 /// the codec. An `Err` is a track that *is* AC-3 and could not be read.
571+ ///
572+ /// The file's *first* audio track, which is the one this has always read.
546573 pub fn open(path: &Path) -> crate::Result<Option<Self>> {
574+ Self::open_inner(path, None)
575+ }
576+
577+ /// The audio track stamped `number` ([`MkvAudioTrack::number`], not a
578+ /// position), for a file carrying more than one -- a dual-audio remux, where
579+ /// which track is heard is the user's pick and not the muxer's order.
580+ /// `Ok(None)` for a number this file does not have, or one whose codec is
581+ /// not AC-3, exactly as [`open`](Self::open) answers for the first track.
582+ pub fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
583+ Self::open_inner(path, Some(number))
584+ }
585+
586+ fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
547587 let mut file = File::open(path)?;
548588 let end = file.metadata()?.len();
549589 let segment = mkv_segment(&mut file, end)?;
550590 let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?;
551- let Some((number, codec, unpack)) = audio else {
591+ let Some(MkvAudioTrack {
592+ number,
593+ codec,
594+ unpack,
595+ ..
596+ }) = (match number {
597+ Some(number) => audio.into_iter().find(|t| t.number == number),
598+ None => audio.into_iter().next(),
599+ })
600+ else {
552601 return Ok(None);
553602 };
554603 let codec = match codec.as_str() {
@@ -752,6 +801,8 @@ const DEFAULT_DURATION: u32 = 0x23E383;
752801 const VIDEO: u32 = 0xE0;
753802 const PIXEL_WIDTH: u32 = 0xB0;
754803 const PIXEL_HEIGHT: u32 = 0xBA;
804+const TRACK_LANGUAGE: u32 = 0x22B59C;
805+const TRACK_NAME: u32 = 0x536E;
755806 const CONTENT_ENCODINGS: u32 = 0x6D80;
756807 const CONTENT_ENCODING: u32 = 0x6240;
757808 const CONTENT_ENCODING_SCOPE: u32 = 0x5032;
@@ -778,25 +829,21 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
778829 Err("no Segment element: not a Matroska file".into())
779830 }
780831
781-/// The video track of `segment`, the number and codec id of its first audio
782-/// track, the codec id of a video track this cannot read, and the segment's
783-/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a
784-/// sound track from; it and the other codec id are what tell a user why a file
785-/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to
786-/// open at all.
832+/// The video track of `segment`, **every** audio track in file order, the codec
833+/// id of a video track this cannot read, and the segment's `TimestampScale` in
834+/// nanoseconds. The audio list is what [`MkvAudio`] reads a sound track from and
835+/// what [`matroska_audio_tracks`] hands a stream picker; it and the other codec
836+/// id are what tell a user why a file plays silent
837+/// ([`crate::audio::AudioSession::unsupported`]) or refuses to open at all.
787838 ///
788839 /// Header only: the walk stops at the first `Cluster`, so this costs a handful
789840 /// of seeks whatever the file weighs.
790841 fn mkv_tracks(
791842 file: &mut File,
792843 segment: (u64, u64),
793-) -> crate::Result<(
794- Option<MkvVideo>,
795- Option<(u64, String, Unpack)>,
796- Option<String>,
797- u64,
798-)> {
799- let (mut video, mut audio, mut other) = (None, None, None);
844+) -> crate::Result<(Option<MkvVideo>, Vec<MkvAudioTrack>, Option<String>, u64)> {
845+ let (mut video, mut other) = (None, None);
846+ let mut audio = Vec::new();
800847 let mut timestamp_scale = 1_000_000;
801848 let mut at = segment.0;
802849 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
@@ -818,9 +865,11 @@ fn mkv_tracks(
818865 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
819866 MkvEntry::Video(track) if video.is_none() => video = Some(track),
820867 MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),
821- MkvEntry::Audio(number, codec, unpack) if audio.is_none() => {
822- audio = Some((number, codec, unpack))
823- }
868+ // Every one of them, in the order the `Tracks`
869+ // element lists them: that order *is* the stream
870+ // numbering everything above hands out, so a
871+ // careless filter here plays the wrong language.
872+ MkvEntry::Audio(track) => audio.push(track),
824873 _ => {}
825874 }
826875 }
@@ -839,10 +888,7 @@ enum MkvEntry {
839888 Video(MkvVideo),
840889 /// A video track in a codec this does not read, by the name it gives itself.
841890 OtherVideo(String),
842- /// An audio track: its track number, which is what [`MkvAudio`] indexes the
843- /// blocks of, its codec id (`A_AAC`, `A_EAC3`, ...), and what its blocks
844- /// have to be put back through.
845- Audio(u64, String, Unpack),
891+ Audio(MkvAudioTrack),
846892 /// Subtitles, buttons: nobody's here.
847893 Other,
848894 }
@@ -856,6 +902,7 @@ fn mkv_track_entry(
856902 ) -> crate::Result<MkvEntry> {
857903 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
858904 let (mut width, mut height, mut config) = (0, 0, Vec::new());
905+ let (mut language, mut name) = (String::new(), String::new());
859906 let mut unpack = Unpack::None;
860907 let mut at = body;
861908 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
@@ -863,6 +910,8 @@ fn mkv_track_entry(
863910 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
864911 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
865912 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
913+ TRACK_LANGUAGE => language = string_of(file, body, stop)?,
914+ TRACK_NAME => name = string_of(file, body, stop)?,
866915 DEFAULT_DURATION => {
867916 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
868917 }
@@ -906,7 +955,21 @@ fn mkv_track_entry(
906955 (Codec::H264, nal_length, sets, 8)
907956 }
908957 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
909- (2, _) => return Ok(MkvEntry::Audio(number, codec, unpack)),
958+ (2, _) => {
959+ return Ok(MkvEntry::Audio(MkvAudioTrack {
960+ number,
961+ codec,
962+ // What a `TrackEntry` without a `Language` element means, by
963+ // spec -- the same default the subtitle walk applies.
964+ language: if language.is_empty() {
965+ "und".into()
966+ } else {
967+ language
968+ },
969+ name,
970+ unpack,
971+ }));
972+ }
910973 _ => return Ok(MkvEntry::Other),
911974 };
912975 Ok(MkvEntry::Video(MkvVideo {
@@ -1667,8 +1730,6 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
16671730
16681731 /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.
16691732 fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {
1670- const TRACK_LANGUAGE: u32 = 0x22B59C;
1671- const TRACK_NAME: u32 = 0x536E;
16721733 const SUBTITLE: u64 = 0x11;
16731734 let (mut number, mut kind, mut codec) = (0, 0, String::new());
16741735 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
crates/engine/tests/audio_streams.rsmodified+126 -0
@@ -11,6 +11,11 @@ use engine::audio::{AudioSession, StreamInfo};
1111 /// See `scripts/gen_fixtures.sh`.
1212 const MULTI: &str = "test_multiaudio.mp4";
1313
14+/// Two audio streams in **Matroska**, the shape a dual-audio remux has: 0 is
15+/// AAC 44.1k stereo 440/880 Hz English, 1 is the same shape at 220/330 Hz
16+/// French. See `scripts/gen_fixtures.sh`.
17+const MULTI_MKV: &str = "test_multiaudio.mkv";
18+
1419 fn asset(name: &str) -> PathBuf {
1520 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1621 .join("../../assets")
@@ -90,6 +95,127 @@ fn probe_streams_lists_every_audio_track_in_file_order() {
9095 }
9196 }
9297
98+/// The same listing for the container a film actually arrives in. A Matroska
99+/// file used to be worth exactly one row here -- whichever track the readers
100+/// stumbled on first -- so the second language of a dual-audio remux was
101+/// invisible, and the language it is in was never shown at all.
102+#[test]
103+fn probe_streams_lists_every_matroska_audio_track_with_its_language() {
104+ let streams = AudioSession::probe_streams(asset(MULTI_MKV)).expect("probes");
105+ assert_eq!(
106+ streams,
107+ vec![
108+ StreamInfo {
109+ index: 0,
110+ codec: "aac".into(),
111+ channels: 2,
112+ sample_rate: 44100,
113+ lang: Some("eng".into()),
114+ decodable: true,
115+ },
116+ StreamInfo {
117+ index: 1,
118+ codec: "aac".into(),
119+ channels: 2,
120+ sample_rate: 44100,
121+ lang: Some("fra".into()),
122+ decodable: true,
123+ },
124+ ]
125+ );
126+}
127+
128+/// The stream index is a position in the file's `Tracks` element and the reader
129+/// is pointed at that entry's *track number*; a mapping that drifts plays the
130+/// other language and saves it into the project, so it is measured by the tones
131+/// each track carries.
132+#[test]
133+fn a_named_matroska_stream_decodes_that_stream_and_not_the_first() {
134+ // The left channel of each stream: 440 Hz on stream 0, 220 Hz on stream 1.
135+ for (stream, hz) in [(0usize, 440.0f64), (1, 220.0)] {
136+ let (meta, samples) = decode(MULTI_MKV, stream);
137+ assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
138+ let left: Vec<f32> = samples.chunks(2).map(|c| c[0]).collect();
139+ let middle = &left[left.len() / 4..left.len() * 3 / 4];
140+ let expected = 2.0 * hz * middle.len() as f64 / 44100.0;
141+ let crossings = zero_crossings(middle) as f64;
142+ assert!(
143+ (crossings - expected).abs() < 0.05 * expected,
144+ "stream {stream} is {crossings} crossings, {hz} Hz would be {expected}"
145+ );
146+ let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
147+ / samples.len() as f64)
148+ .sqrt();
149+ assert!(rms > 0.01, "stream {stream} decoded silent: RMS {rms:.6}");
150+ }
151+
152+ // Stream 0 is what the file has always played: the wrapper that names no
153+ // stream and stream 0 are the same track, sample for sample.
154+ let (wrapped, rx) = AudioSession::open(asset(MULTI_MKV))
155+ .expect("opens")
156+ .expect("audio");
157+ let plain: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
158+ let (meta, named) = decode(MULTI_MKV, 0);
159+ assert_eq!(wrapped, meta);
160+ assert_eq!(plain, named);
161+
162+ // ...and a stream the file does not have is refused, not quietly served the
163+ // first track.
164+ let err = AudioSession::open_multi_streams(&[(asset(MULTI_MKV), 2)], &[(Some(0), 0.0, 1.0)])
165+ .expect_err("stream 2 of 2 does not exist");
166+ assert!(
167+ err.to_string().contains("audio stream 2 of 2 streams"),
168+ "unhelpful refusal: {err}"
169+ );
170+}
171+
172+/// 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.
174+#[test]
175+fn a_real_dual_audio_remux_lists_both_tracks_and_plays_the_second() {
176+ let path = PathBuf::from(
177+ "/path/to/\
178+a-real-h264-dual-audio-film.mkv",
179+ );
180+ if !path.exists() {
181+ eprintln!("skipped: {} is not on this machine", path.display());
182+ return;
183+ }
184+ let streams = AudioSession::probe_streams(&path).expect("probes");
185+ assert_eq!(streams.len(), 2, "two audio tracks: {streams:?}");
186+ for (index, info) in streams.iter().enumerate() {
187+ assert_eq!(info.index, index);
188+ assert_eq!(info.codec, "aac", "{info:?}");
189+ assert!(info.decodable, "{info:?}");
190+ }
191+ // A second of each track, ten seconds in (past the silence a title card
192+ // opens on): both have to carry sound and they have to be *different*
193+ // sound. The failure this guards against is a stream index that resolves to
194+ // nothing, or to the first track again.
195+ let mut takes = Vec::new();
196+ for stream in [0, 1] {
197+ let (meta, rx) =
198+ AudioSession::open_multi_streams(&[(path.clone(), stream)], &[(Some(0), 10.0, 11.0)])
199+ .expect("the stream opens")
200+ .expect("the stream is there");
201+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
202+ assert!(
203+ samples.len() > meta.sample_rate as usize / 2,
204+ "half a second of stream {stream} at least, got {}",
205+ samples.len()
206+ );
207+ let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
208+ / samples.len() as f64)
209+ .sqrt();
210+ assert!(rms > 1e-4, "stream {stream} came out silent: RMS {rms:.8}");
211+ takes.push(samples);
212+ }
213+ assert_ne!(
214+ takes[0], takes[1],
215+ "the two languages decoded to the same samples: the stream index picked one track twice"
216+ );
217+}
218+
93219 #[test]
94220 fn probe_streams_on_one_track_and_on_none() {
95221 let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes");
scripts/gen_fixtures.shmodified+18 -0
@@ -195,6 +195,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
195195 -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
196196 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \
197197 -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv
198+# Dual audio in Matroska: the shape an anime remux has -- one picture and two
199+# AAC tracks that differ in language and content and *agree* on rate and layout
200+# (44.1k stereo), so either one can go on the same timeline. Stream 0 is
201+# 440/880 Hz English, stream 1 is 220/330 Hz French; the tones are what a test
202+# tells the two apart by, and getting the mapping wrong plays the other
203+# language. test_multilang.mp4 is this file's mp4 twin.
204+ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
205+ -f lavfi -i "sine=frequency=440:duration=2" \
206+ -f lavfi -i "sine=frequency=880:duration=2" \
207+ -f lavfi -i "sine=frequency=220:duration=2" \
208+ -f lavfi -i "sine=frequency=330:duration=2" \
209+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a0];\
210+[3:a][4:a]join=inputs=2:channel_layout=stereo[a1]" \
211+ -map 0:v -map "[a0]" -map "[a1]" \
212+ -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \
213+ -c:a aac -ar 44100 -ac 2 \
214+ -metadata:s:a:0 language=eng -metadata:s:a:1 language=fra \
215+ assets/test_multiaudio.mkv
198216 # Sync fixture: one flash and one beep, at the same instant. Black picture with
199217 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
200218 # stretch — so a test can find each of them and say how far apart they came out.