From 264c10cb1283bef8c9fc4abec02360e65520f933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 11 Aug 2026 16:44:33 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(audio):=20every=20audio=20trac?= =?UTF-8?q?k=20of=20an=20mkv=20is=20a=20row,=20and=20the=20second=20one=20?= =?UTF-8?q?plays?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 158 ++++++++++++++++++++------- crates/engine/src/demux.rs | 111 ++++++++++++++----- crates/engine/tests/audio_streams.rs | 126 +++++++++++++++++++++ scripts/gen_fixtures.sh | 18 +++ 4 files changed, 350 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index d424d9b..6f36428 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -712,40 +712,55 @@ 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 has exactly one readable audio stream here -- the - // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one - // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a - // standalone audio file rather than like an mp4, and one with no - // readable track at all lists as the silent source it is. + // 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. if crate::demux::is_matroska(path) { - // The AC-3 row describes what the decoder *emits*, which is the - // stereo the §7.8 downmix hands the timeline, not the 5.1 the file - // carries -- exactly as the mp4 AC-3 rows do. - if let Ok(Some(track)) = MkvAc3Track::open(path) { - return Ok(vec![StreamInfo { - index: 0, - codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), - channels: track.channels, - sample_rate: track.sample_rate, - lang: None, - decodable: matches!(track.channels, 1 | 2), - }]); + let mut streams = Vec::new(); + for (index, entry) in crate::demux::matroska_audio_tracks(path)? + .iter() + .enumerate() + { + // The routing [`Track::open`] does, one row at a time, so a row + // describes the track that would really open: AC-3 and E-AC-3 + // through the Dolby decoder's own reader, everything else + // through symphonia. The AC-3 row describes what the decoder + // *emits*, which is the stereo the §7.8 downmix hands the + // timeline, not the 5.1 the file carries -- exactly as the mp4 + // AC-3 rows do. + let ac3 = matches!(entry.codec.as_str(), "A_AC3" | "A_EAC3") + .then(|| MkvAc3Track::open_track(path, entry.number).ok().flatten()) + .flatten(); + // A track symphonia cannot even describe is listed undecodable + // by the name the container gives it, rather than taking the + // whole listing down with it: the other language still plays. + let sym = match &ac3 { + Some(_) => None, + None => SymTrack::open_track(path, entry.number).ok().flatten(), + }; + let channels = ac3.as_ref().map_or_else( + || sym.as_ref().map_or(0, |t| t.channels), + |t| t.channels, + ); + streams.push(StreamInfo { + index, + codec: mkv_codec_name(&entry.codec), + channels, + sample_rate: ac3.as_ref().map_or_else( + || sym.as_ref().map_or(0, |t| t.sample_rate), + |t| t.sample_rate, + ), + lang: (entry.language != "und" && !entry.language.is_empty()) + .then(|| entry.language.clone()), + decodable: matches!(channels, 1 | 2) + && (ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok())), + }); } - // No audio track lists as the silent source it is; a track that - // will not open 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. - let Some(track) = SymTrack::open(path)? else { - return Ok(Vec::new()); - }; - return Ok(vec![StreamInfo { - index: 0, - codec: track.codec.into(), - channels: track.channels, - sample_rate: track.sample_rate, - lang: None, - decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(), - }]); + return Ok(streams); } if crate::is_audio(path) { let track = SymTrack::open_required(path)?; @@ -1123,10 +1138,26 @@ 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) { - if stream > 0 { - return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); + // 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. + let tracks = crate::demux::matroska_audio_tracks(path)?; + if tracks.is_empty() { + return Ok(None); } - match MkvAc3Track::open(path) { + let Some(entry) = tracks.get(stream) else { + return Err(format!( + "{}: audio stream {stream} of {} stream{}", + path.display(), + tracks.len(), + if tracks.len() == 1 { "" } else { "s" } + ) + .into()); + }; + match MkvAc3Track::open_track(path, entry.number) { Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), Ok(None) => {} // Named on the way past rather than returned: symphonia gets the @@ -1142,7 +1173,7 @@ impl Track { // same answer the mp4 arm gives: turned into silence it would play // and export as a hole with only an eprintln to say why, which is a // bug wearing a feature's clothes. - let Some(track) = SymTrack::open(path)? else { + let Some(track) = SymTrack::open_track(path, entry.number)? else { return Ok(None); }; if let Err(e) = track.decoder() { @@ -1311,6 +1342,22 @@ impl SymTrack { /// difference matters because silence is played and exported without a word /// while an `Err` is shown ([`Track::open`]). fn open(path: &Path) -> crate::Result> { + Self::open_inner(path, None) + } + + /// [`open`](Self::open) pointed at one **named** track: a Matroska + /// `TrackNumber`, which symphonia keeps as the track's id + /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second + /// language of a dual-audio file reachable, and it is matched by number + /// rather than by position so this reader and + /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which + /// track a stream index meant. `Ok(None)` for a number the reader does not + /// carry. + fn open_track(path: &Path, number: u64) -> crate::Result> { + Self::open_inner(path, Some(number)) + } + + fn open_inner(path: &Path, number: Option) -> crate::Result> { let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); // The extension is a hint, not a decision: the probe reads the magic and // is free to disagree, which is what makes a mislabelled file work. @@ -1324,7 +1371,14 @@ impl SymTrack { FormatOptions::default(), MetadataOptions::default(), )?; - let Some(track) = reader.default_track(SymKind::Audio) else { + let track = match number { + Some(number) => reader + .tracks() + .iter() + .find(|t| u64::from(t.id) == number), + None => reader.default_track(SymKind::Audio), + }; + let Some(track) = track else { return Ok(None); }; // `track.delay` is deliberately not read: see the `priming` field. @@ -1611,7 +1665,19 @@ impl MkvAc3Track { /// that is one and could not be read, which /// [`AudioSession::unsupported`] quotes back to the user. fn open(path: &Path) -> crate::Result> { - let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else { + Self::from_blocks(crate::demux::MkvAudio::open(path)?) + } + + /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]), + /// which is how the AC-3 half of a dual-audio file is reached. + /// + /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number + fn open_track(path: &Path, number: u64) -> crate::Result> { + Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?) + } + + fn from_blocks(mkv: Option) -> crate::Result> { + let Some(mut mkv) = mkv else { return Ok(None); }; let first = mkv @@ -1889,6 +1955,22 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { n } +/// 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`. +/// +/// The codec id rather than symphonia's short name, because the rows that most +/// need naming are exactly the ones it has no decoder for: an Opus or DTS track +/// is greyed out with the codec in the reason (`unusable` in the app reads this +/// very string), where symphonia would call it "an unsupported format". +fn mkv_codec_name(id: &str) -> String { + match id { + "A_AC3" => "ac-3".into(), + "A_EAC3" => "e-ac-3".into(), + "A_MPEG/L3" => "mp3".into(), + _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(), + } +} + /// 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 diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index f215c56..c63cb39 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -512,10 +512,35 @@ impl MkvDemuxer { /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and /// this exists to say which codec neither of them took. pub fn matroska_audio_codec(path: &Path) -> crate::Result> { + Ok(matroska_audio_tracks(path)?.into_iter().next().map(|t| t.codec)) +} + +/// One audio `TrackEntry` of a Matroska file, as the header describes it. +pub struct MkvAudioTrack { + /// `TrackNumber`: what this track's blocks are stamped with ([`MkvAudio`]), + /// and the id symphonia keeps for the same track. *Not* a position -- a + /// file's first audio track is number 2 as often as not. + pub number: u64, + /// The Matroska codec id: `A_AAC`, `A_EAC3`, `A_DTS`, ... + pub codec: String, + /// `TrackLanguage`, `"und"` for an entry that declares none (the spec's own + /// default), which is what a muxer writes when nobody said. + pub language: String, + /// `TrackName` -- "Japanese 5.1", "Commentary" -- empty when there is none. + pub name: String, + /// What this track's blocks have to be put back through. + unpack: Unpack, +} + +/// Every audio track of a Matroska file, in file order: the numbering +/// [`crate::AudioSession::probe_streams`] hands out, and the one a dual-audio +/// remux is picked from. Header only, like [`matroska_audio_codec`], and an +/// empty list is a file with no sound at all rather than an error. +pub fn matroska_audio_tracks(path: &Path) -> crate::Result> { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec, _)| codec)) + Ok(mkv_tracks(&mut file, segment)?.1) } /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio @@ -543,12 +568,36 @@ impl MkvAudio { /// is in a codec nothing here decodes -- that file is the silent source it /// has always been, and [`crate::audio::AudioSession::unsupported`] names /// the codec. An `Err` is a track that *is* AC-3 and could not be read. + /// + /// The file's *first* audio track, which is the one this has always read. pub fn open(path: &Path) -> crate::Result> { + Self::open_inner(path, None) + } + + /// The audio track stamped `number` ([`MkvAudioTrack::number`], not a + /// position), for a file carrying more than one -- a dual-audio remux, where + /// which track is heard is the user's pick and not the muxer's order. + /// `Ok(None)` for a number this file does not have, or one whose codec is + /// not AC-3, exactly as [`open`](Self::open) answers for the first track. + pub fn open_track(path: &Path, number: u64) -> crate::Result> { + Self::open_inner(path, Some(number)) + } + + fn open_inner(path: &Path, number: Option) -> crate::Result> { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; - let Some((number, codec, unpack)) = audio else { + let Some(MkvAudioTrack { + number, + codec, + unpack, + .. + }) = (match number { + Some(number) => audio.into_iter().find(|t| t.number == number), + None => audio.into_iter().next(), + }) + else { return Ok(None); }; let codec = match codec.as_str() { @@ -752,6 +801,8 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +const TRACK_LANGUAGE: u32 = 0x22B59C; +const TRACK_NAME: u32 = 0x536E; const CONTENT_ENCODINGS: u32 = 0x6D80; const CONTENT_ENCODING: u32 = 0x6240; const CONTENT_ENCODING_SCOPE: u32 = 0x5032; @@ -778,25 +829,21 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { Err("no Segment element: not a Matroska file".into()) } -/// The video track of `segment`, the number and codec id of its first audio -/// track, the codec id of a video track this cannot read, and the segment's -/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a -/// sound track from; it and the other codec id are what tell a user why a file -/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to -/// open at all. +/// The video track of `segment`, **every** audio track in file order, the codec +/// id of a video track this cannot read, and the segment's `TimestampScale` in +/// nanoseconds. The audio list is what [`MkvAudio`] reads a sound track from and +/// what [`matroska_audio_tracks`] hands a stream picker; it and the other codec +/// id are what tell a user why a file plays silent +/// ([`crate::audio::AudioSession::unsupported`]) or refuses to open at all. /// /// Header only: the walk stops at the first `Cluster`, so this costs a handful /// of seeks whatever the file weighs. fn mkv_tracks( file: &mut File, segment: (u64, u64), -) -> crate::Result<( - Option, - Option<(u64, String, Unpack)>, - Option, - u64, -)> { - let (mut video, mut audio, mut other) = (None, None, None); +) -> crate::Result<(Option, Vec, Option, u64)> { + let (mut video, mut other) = (None, None); + let mut audio = Vec::new(); let mut timestamp_scale = 1_000_000; let mut at = segment.0; while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { @@ -818,9 +865,11 @@ fn mkv_tracks( match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { MkvEntry::Video(track) if video.is_none() => video = Some(track), MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), - MkvEntry::Audio(number, codec, unpack) if audio.is_none() => { - audio = Some((number, codec, unpack)) - } + // Every one of them, in the order the `Tracks` + // element lists them: that order *is* the stream + // numbering everything above hands out, so a + // careless filter here plays the wrong language. + MkvEntry::Audio(track) => audio.push(track), _ => {} } } @@ -839,10 +888,7 @@ enum MkvEntry { Video(MkvVideo), /// A video track in a codec this does not read, by the name it gives itself. OtherVideo(String), - /// An audio track: its track number, which is what [`MkvAudio`] indexes the - /// blocks of, its codec id (`A_AAC`, `A_EAC3`, ...), and what its blocks - /// have to be put back through. - Audio(u64, String, Unpack), + Audio(MkvAudioTrack), /// Subtitles, buttons: nobody's here. Other, } @@ -856,6 +902,7 @@ fn mkv_track_entry( ) -> crate::Result { let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); let (mut width, mut height, mut config) = (0, 0, Vec::new()); + let (mut language, mut name) = (String::new(), String::new()); let mut unpack = Unpack::None; let mut at = body; while let Some((id, body, stop)) = ebml_element(file, at, end)? { @@ -863,6 +910,8 @@ fn mkv_track_entry( TRACK_NUMBER => number = ebml_uint(file, body, stop)?, CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?, TRACK_TYPE => kind = ebml_uint(file, body, stop)?, + TRACK_LANGUAGE => language = string_of(file, body, stop)?, + TRACK_NAME => name = string_of(file, body, stop)?, DEFAULT_DURATION => { default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0) } @@ -906,7 +955,21 @@ fn mkv_track_entry( (Codec::H264, nal_length, sets, 8) } (1, _) => return Ok(MkvEntry::OtherVideo(codec)), - (2, _) => return Ok(MkvEntry::Audio(number, codec, unpack)), + (2, _) => { + return Ok(MkvEntry::Audio(MkvAudioTrack { + number, + codec, + // What a `TrackEntry` without a `Language` element means, by + // spec -- the same default the subtitle walk applies. + language: if language.is_empty() { + "und".into() + } else { + language + }, + name, + unpack, + })); + } _ => return Ok(MkvEntry::Other), }; Ok(MkvEntry::Video(MkvVideo { @@ -1667,8 +1730,6 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result> { /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result> { - const TRACK_LANGUAGE: u32 = 0x22B59C; - const TRACK_NAME: u32 = 0x536E; const SUBTITLE: u64 = 0x11; let (mut number, mut kind, mut codec) = (0, 0, String::new()); let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); diff --git a/crates/engine/tests/audio_streams.rs b/crates/engine/tests/audio_streams.rs index e216f47..e7a29c3 100644 --- a/crates/engine/tests/audio_streams.rs +++ b/crates/engine/tests/audio_streams.rs @@ -11,6 +11,11 @@ use engine::audio::{AudioSession, StreamInfo}; /// See `scripts/gen_fixtures.sh`. const MULTI: &str = "test_multiaudio.mp4"; +/// Two audio streams in **Matroska**, the shape a dual-audio remux has: 0 is +/// AAC 44.1k stereo 440/880 Hz English, 1 is the same shape at 220/330 Hz +/// French. See `scripts/gen_fixtures.sh`. +const MULTI_MKV: &str = "test_multiaudio.mkv"; + fn asset(name: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../assets") @@ -90,6 +95,127 @@ fn probe_streams_lists_every_audio_track_in_file_order() { } } +/// The same listing for the container a film actually arrives in. A Matroska +/// file used to be worth exactly one row here -- whichever track the readers +/// stumbled on first -- so the second language of a dual-audio remux was +/// invisible, and the language it is in was never shown at all. +#[test] +fn probe_streams_lists_every_matroska_audio_track_with_its_language() { + let streams = AudioSession::probe_streams(asset(MULTI_MKV)).expect("probes"); + assert_eq!( + streams, + vec![ + StreamInfo { + index: 0, + codec: "aac".into(), + channels: 2, + sample_rate: 44100, + lang: Some("eng".into()), + decodable: true, + }, + StreamInfo { + index: 1, + codec: "aac".into(), + channels: 2, + sample_rate: 44100, + lang: Some("fra".into()), + decodable: true, + }, + ] + ); +} + +/// The stream index is a position in the file's `Tracks` element and the reader +/// is pointed at that entry's *track number*; a mapping that drifts plays the +/// other language and saves it into the project, so it is measured by the tones +/// each track carries. +#[test] +fn a_named_matroska_stream_decodes_that_stream_and_not_the_first() { + // The left channel of each stream: 440 Hz on stream 0, 220 Hz on stream 1. + for (stream, hz) in [(0usize, 440.0f64), (1, 220.0)] { + let (meta, samples) = decode(MULTI_MKV, stream); + assert_eq!((meta.sample_rate, meta.channels), (44100, 2)); + let left: Vec = samples.chunks(2).map(|c| c[0]).collect(); + let middle = &left[left.len() / 4..left.len() * 3 / 4]; + let expected = 2.0 * hz * middle.len() as f64 / 44100.0; + let crossings = zero_crossings(middle) as f64; + assert!( + (crossings - expected).abs() < 0.05 * expected, + "stream {stream} is {crossings} crossings, {hz} Hz would be {expected}" + ); + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() + / samples.len() as f64) + .sqrt(); + assert!(rms > 0.01, "stream {stream} decoded silent: RMS {rms:.6}"); + } + + // Stream 0 is what the file has always played: the wrapper that names no + // stream and stream 0 are the same track, sample for sample. + let (wrapped, rx) = AudioSession::open(asset(MULTI_MKV)) + .expect("opens") + .expect("audio"); + let plain: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let (meta, named) = decode(MULTI_MKV, 0); + assert_eq!(wrapped, meta); + assert_eq!(plain, named); + + // ...and a stream the file does not have is refused, not quietly served the + // first track. + let err = AudioSession::open_multi_streams(&[(asset(MULTI_MKV), 2)], &[(Some(0), 0.0, 1.0)]) + .expect_err("stream 2 of 2 does not exist"); + assert!( + err.to_string().contains("audio stream 2 of 2 streams"), + "unhelpful refusal: {err}" + ); +} + +/// 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] +fn a_real_dual_audio_remux_lists_both_tracks_and_plays_the_second() { + let path = PathBuf::from( + "/path/to/\ +a-real-h264-dual-audio-film.mkv", + ); + if !path.exists() { + eprintln!("skipped: {} is not on this machine", path.display()); + return; + } + let streams = AudioSession::probe_streams(&path).expect("probes"); + assert_eq!(streams.len(), 2, "two audio tracks: {streams:?}"); + for (index, info) in streams.iter().enumerate() { + assert_eq!(info.index, index); + assert_eq!(info.codec, "aac", "{info:?}"); + assert!(info.decodable, "{info:?}"); + } + // A second of each track, ten seconds in (past the silence a title card + // opens on): both have to carry sound and they have to be *different* + // sound. The failure this guards against is a stream index that resolves to + // nothing, or to the first track again. + let mut takes = Vec::new(); + for stream in [0, 1] { + let (meta, rx) = + AudioSession::open_multi_streams(&[(path.clone(), stream)], &[(Some(0), 10.0, 11.0)]) + .expect("the stream opens") + .expect("the stream is there"); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + assert!( + samples.len() > meta.sample_rate as usize / 2, + "half a second of stream {stream} at least, got {}", + samples.len() + ); + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() + / samples.len() as f64) + .sqrt(); + assert!(rms > 1e-4, "stream {stream} came out silent: RMS {rms:.8}"); + takes.push(samples); + } + assert_ne!( + takes[0], takes[1], + "the two languages decoded to the same samples: the stream index picked one track twice" + ); +} + #[test] fn probe_streams_on_one_track_and_on_none() { let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes"); diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index a2466d6..28f3de6 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -195,6 +195,24 @@ 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 -g 30 -pix_fmt yuv420p \ -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv +# Dual audio in Matroska: the shape an anime remux has -- one picture and two +# AAC tracks that differ in language and content and *agree* on rate and layout +# (44.1k stereo), so either one can go on the same timeline. Stream 0 is +# 440/880 Hz English, stream 1 is 220/330 Hz French; the tones are what a test +# tells the two apart by, and getting the mapping wrong plays the other +# language. test_multilang.mp4 is this file's mp4 twin. +ffmpeg -y -f lavfi -i testsrc2=size=320x180: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];\ +[3:a][4:a]join=inputs=2:channel_layout=stereo[a1]" \ + -map 0:v -map "[a0]" -map "[a1]" \ + -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ + -c:a aac -ar 44100 -ac 2 \ + -metadata:s:a:0 language=eng -metadata:s:a:1 language=fra \ + assets/test_multiaudio.mkv # Sync fixture: one flash and one beep, at the same instant. Black picture with # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that # stretch — so a test can find each of them and say how far apart they came out.