diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index c81c8a0..483b7f9 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -63,10 +63,6 @@ const PRE_ROLL: u32 = 2; /// Frames per channel one AAC-LC packet carries. Fixed by the codec. const SAMPLES_PER_PACKET: u32 = 1024; -/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks -/// of 256), the way 1024 is fixed for AAC-LC. -const AC3_SAMPLES_PER_FRAME: u32 = 1536; - /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the /// 256-sample overlap-add the target frame is reconstructed with. const AC3_PRE_ROLL: u32 = 1; @@ -490,16 +486,26 @@ impl AudioSession { /// -- nothing to tell the user there. Header only, and only worth calling /// once the open has already returned no audio. pub fn unsupported(path: impl AsRef) -> crate::Result> { - // Matroska: the demuxer reads its picture and nothing else yet, so a - // file that has sound is told so by name rather than playing silent - // with no reason given. A Matroska file with no audio track at all - // returns `None` here like any other silent file. + // Matroska: the demuxer reads its picture and its AC-3 sound, so a file + // whose audio is in any other codec is told so by name rather than + // playing silent with no reason given. A Matroska file with no audio + // track at all returns `None` here like any other silent file. if crate::demux::is_matroska(path.as_ref()) { - return Ok( - crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { + let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { + return Ok(None); + }; + // ...except AC-3 and E-AC-3, which are read out of the blocks + // themselves now ([`MkvAc3Track`]). If one of those still came up + // silent it is the track that could not be read, and the reader's + // own words -- a laced block, an unreadable syncframe -- are the + // ones worth showing. + return Ok(Some(match MkvAc3Track::open(path.as_ref()) { + Ok(Some(_)) => return Ok(None), + Ok(None) => { format!("{codec} audio in a Matroska file is not wired to the decoder yet") - }), - ); + } + Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), + })); } let file = File::open(path.as_ref())?; let size = file.metadata()?.len(); @@ -546,11 +552,26 @@ 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's audio tracks are not readable here yet ([`Track`]), - // and a stream nothing can open is not one to offer: an mkv lists as - // the silent source it currently is. + // A Matroska file offers the one AC-3 / E-AC-3 track [`MkvAc3Track`] + // reads, in the shape it decodes to (stereo, per the §7.8 downmix), and + // nothing else: a stream nothing can open is not one to offer, so an + // mkv whose sound is in any other codec still lists as the silent + // source it currently is. if crate::demux::is_matroska(path) { - return Ok(Vec::new()); + return Ok(MkvAc3Track::open(path) + .ok() + .flatten() + .map(|track| { + 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), + }] + }) + .unwrap_or_default()); } if crate::is_audio(path) { let track = SymTrack::open(path)?; @@ -838,7 +859,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result> { // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` // sample table can hold, and there is no AAC encoder here to turn it // into one. A WAV/FLAC export of the same timeline decodes fine. - Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), + Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), } } @@ -860,6 +881,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error { enum Track { Aac(AacTrack), Ac3(Ac3Track), + /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an + /// mp4's sample table. + Mkv(MkvAc3Track), Sym(SymTrack), } @@ -878,11 +902,18 @@ impl Track { /// has exactly one, so any `stream` above 0 there is a promise the file /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. fn open(path: &Path, stream: usize) -> crate::Result> { - // A Matroska file's sound is not wired to either reader yet: its picture - // is what this slice delivers, and the source counts as a silent one -- - // which `AudioSession::unsupported` puts into words for the user. + // A Matroska file's sound reaches neither mp4 reader: its AC-3 and + // E-AC-3 tracks come out of the blocks themselves and everything else + // in one is still a silent source -- which `AudioSession::unsupported` + // puts into words for the user. A track that *is* AC-3 and will not + // open (a laced block, an unreadable syncframe) stays a silent source + // too rather than failing the import: an mkv has never been refused + // over its sound, and `unsupported` says what went wrong. if crate::demux::is_matroska(path) { - return Ok(None); + return Ok((stream == 0) + .then(|| MkvAc3Track::open(path).ok().flatten()) + .flatten() + .map(Self::Mkv)); } let audio_file = crate::is_audio(path); // Ahead of the AAC reader, because that one answers "not AAC" for a @@ -910,6 +941,7 @@ impl Track { match self { Self::Aac(t) => t.sample_rate, Self::Ac3(t) => t.sample_rate, + Self::Mkv(t) => t.sample_rate, Self::Sym(t) => t.sample_rate, } } @@ -925,6 +957,11 @@ impl Track { 1 | 2 => Ok(t.channels), n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), }, + // Downmixed by the very same decoder, out of a Matroska file. + Self::Mkv(t) => match t.channels { + 1 | 2 => Ok(t.channels), + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), + }, Self::Sym(t) => match t.channels { 1 | 2 => Ok(t.channels), n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), @@ -937,6 +974,7 @@ impl Track { match self { Self::Aac(t) => t.total_samples, Self::Ac3(t) => t.total_samples, + Self::Mkv(t) => t.total_samples, Self::Sym(t) => t.total_samples, } } @@ -946,6 +984,9 @@ impl Track { match self { Self::Aac(t) => t.priming, Self::Ac3(t) => t.priming, + // Matroska writes no edit list and AC-3 has no encoder delay: + // block 0 is sample 0. + Self::Mkv(_) => 0, Self::Sym(t) => t.priming, } } @@ -956,6 +997,7 @@ impl Track { match self { Self::Aac(t) => t.segment(source, start_secs, end_secs), Self::Ac3(t) => t.segment(source, start_secs, end_secs), + Self::Mkv(t) => t.segment(source, start_secs, end_secs), Self::Sym(t) => { let media_target = t.media(start_secs); Segment { @@ -977,7 +1019,10 @@ impl Track { AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; } Self::Ac3(t) => { - ac3_decoder(t.requested)?; + ac3_decoder("ac3", t.requested)?; + } + Self::Mkv(t) => { + ac3_decoder(t.mkv.codec, t.requested)?; } Self::Sym(t) => { t.decoder()?; @@ -1143,9 +1188,9 @@ impl Ac3Track { .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? .nfchans; let requested = (nfchans > 1).then_some(2); - let mut decoder = ac3_decoder(requested)?; + let mut decoder = ac3_decoder("ac3", requested)?; let channels = decode_ac3(&mut decoder, &first.bytes)? - .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16) + .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) .filter(|&c| c > 0) .ok_or("the first AC-3 syncframe decoded to nothing")?; @@ -1190,6 +1235,101 @@ impl Ac3Track { } } +/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same +/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of +/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux +/// therefore arrives on the timeline as an ordinary stereo source, exactly as +/// the mp4 path's does, and the mono passthrough quirk is the same one. +/// +/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side +/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): +/// one block is one packet, one packet is one syncframe, and a seek lands on +/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in +/// front of it. +struct MkvAc3Track { + mkv: crate::demux::MkvAudio, + sample_rate: u32, + /// What comes *out* of the decoder, measured on the first frame — 2 for + /// anything from stereo to 5.1, 1 for a mono track (see `requested`). + channels: u16, + total_samples: Option, + /// What the decoder is asked to hand out, from this track's own layout: + /// `Some(2)` for anything with more than one front channel, `None` for a + /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's. + requested: Option, +} + +impl MkvAc3Track { + /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 — + /// that mkv is the silent source it has always been. An `Err` is a track + /// 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 { + return Ok(None); + }; + let first = mkv + .frame(0)? + .ok_or("the AC-3 track of this Matroska file has no blocks")?; + // Rate and layout come out of the bit stream, which is where AC-3 + // states them: Matroska's `Audio` element repeats them and muxers get + // that wrong often enough that the frame is the better source. + // `nfchans` excludes the LFE in both syntaxes, which is what the + // downmix decision wants. + let (sample_rate, nfchans) = if mkv.codec == "eac3" { + // Annex E's BSI starts right after the 16-bit syncword. + let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) + .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; + (bsi.sample_rate, bsi.nfchans) + } else { + let sync = oxideav_ac3::syncinfo::parse(&first) + .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; + let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) + .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; + (sync.sample_rate, bsi.nfchans) + }; + let requested = (nfchans > 1).then_some(2); + let mut decoder = ac3_decoder(mkv.codec, requested)?; + let (pcm, samples) = + decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; + let channels = (pcm.len() as u64 / samples.max(1)) as u16; + if channels == 0 { + return Err("the first AC-3 syncframe decoded to nothing".into()); + } + // The track runs to the last block's timestamp plus that block's own + // frame -- a container that indexes nothing states no duration either, + // and every frame of a syncframe stream is the same length. + let last = mkv.secs(mkv.blocks().saturating_sub(1)); + Ok(Some(Self { + total_samples: Some((last * f64::from(sample_rate)) as u64 + samples), + sample_rate, + channels, + requested, + mkv, + })) + } + + /// `secs` on this source's timeline into media samples. No priming: the + /// container carries no edit list and AC-3 no encoder delay. + fn media(&self, secs: f64) -> u64 { + (secs.max(0.0) * f64::from(self.sample_rate)) as u64 + } + + /// One `[start, end)` window, resolved to blocks and media samples — + /// [`Ac3Track::segment`] against block timestamps instead of an `stts`. + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { + let media_target = self.media(start_secs); + let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize); + Segment { + source: Some(source), + start_id: start_id as u32, + start_pos: self.media(self.mkv.secs(start_id)), + media_target, + media_end: self.media(end_secs).max(media_target), + } + } +} + /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a /// 5.1 track at all. Fresh per segment for the same reason every other decoder @@ -1200,32 +1340,47 @@ impl Ac3Track { /// mono track asks for no downmix at all and stays the mono source it is. The /// upgrade path is `Some(2)` unconditionally once the library duplicates the /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. -fn ac3_decoder(channels: Option) -> crate::Result> { +/// +/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers +/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct +/// behind both dispatches per packet on `bsid` in any case, so what this picks +/// is the capability set, not the syntax. +fn ac3_decoder(codec: &str, channels: Option) -> crate::Result> { let mut registry = CodecRegistry::new(); oxideav_ac3::register_codecs(&mut registry); - let mut params = CodecParameters::audio(CodecId::new("ac3")); + let mut params = CodecParameters::audio(CodecId::new(codec)); params.channels = channels; registry .first_decoder(¶ms) .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) } -/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the -/// decoder wants more input before it can hand a frame back, which is not an -/// error. The library speaks S16 little-endian; `/32768` is the whole -/// conversion, and it lands in the `[-1, 1)` every other reader here emits. -fn decode_ac3(decoder: &mut Box, bytes: &[u8]) -> crate::Result>> { +/// One syncframe in, one buffer of interleaved f32 out and the frames per +/// channel it holds. `Ok(None)` when the decoder wants more input before it can +/// hand a frame back, which is not an error. The library speaks S16 +/// little-endian; `/32768` is the whole conversion, and it lands in the +/// `[-1, 1)` every other reader here emits. +/// +/// The frame count comes back beside the samples because an E-AC-3 frame is not +/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 +/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the +/// channel count and every media position after it out. +fn decode_ac3( + decoder: &mut Box, + bytes: &[u8], +) -> crate::Result, u64)>> { let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); decoder .send_packet(&packet) .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; match decoder.receive_frame() { - Ok(Frame::Audio(audio)) => Ok(Some( + Ok(Frame::Audio(audio)) => Ok(Some(( audio.data[0] .chunks_exact(2) .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) .collect(), - )), + u64::from(audio.samples), + ))), Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), Err(oxideav_core::Error::NeedMore) => Ok(None), Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), @@ -1817,6 +1972,21 @@ fn run(mut w: Worker) { } continue; } + Track::Mkv(track) => { + if !run_mkv_ac3( + track, + seg, + eq.as_mut(), + speed, + channels, + &mut timeline, + &w.tx, + ) || !settle(speed, channels, &mut timeline, &w.tx) + { + return; // consumer went away + } + continue; + } Track::Ac3(track) => { if !run_ac3( track, @@ -1982,7 +2152,7 @@ fn run_ac3( timeline: &mut u64, tx: &SyncSender, ) -> bool { - let mut decoder = match ac3_decoder(track.requested) { + let mut decoder = match ac3_decoder("ac3", track.requested) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); @@ -1991,7 +2161,6 @@ fn run_ac3( }; let mut pos = seg.start_pos; for id in seg.start_id..=track.sample_count { - let mut interleaved; if pos >= seg.media_end { return true; // segment done, on to the next one } @@ -2003,15 +2172,75 @@ fn run_ac3( return true; } }; - match decode_ac3(&mut decoder, &sample.bytes) { - Ok(Some(pcm)) => interleaved = pcm, + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) { + Ok(Some(decoded)) => decoded, Ok(None) => continue, // the decoder wants another frame first Err(e) => { eprintln!("audio decode error at sample {id}: {e}"); return true; } + }; + let next = pos + samples; + if !emit( + &mut interleaved, + channels, + seg, + eq.as_deref_mut(), + speed.as_mut(), + pos, + next, + timeline, + tx, + ) { + return false; } - let next = pos + (interleaved.len() / channels) as u64; + pos = next; + } + true +} + +/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks +/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the +/// stereo downmix are the same ones; only where a packet comes from differs. +/// `false` means the consumer went away. +fn run_mkv_ac3( + track: &mut MkvAc3Track, + seg: &Segment, + mut eq: Option<&mut EqState>, + speed: &mut Option, + channels: usize, + timeline: &mut u64, + tx: &SyncSender, +) -> bool { + let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { + Ok(decoder) => decoder, + Err(e) => { + eprintln!("audio decoder init failed: {e}"); + return true; + } + }; + let mut pos = seg.start_pos; + for id in seg.start_id as usize.. { + if pos >= seg.media_end { + return true; // segment done, on to the next one + } + let block = match track.mkv.frame(id) { + Ok(Some(bytes)) => bytes, + Ok(None) => return true, // end of the track + Err(e) => { + eprintln!("audio demux error at block {id}: {e}"); + return true; + } + }; + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) { + Ok(Some(decoded)) => decoded, + Ok(None) => continue, // the decoder wants another frame first + Err(e) => { + eprintln!("audio decode error at block {id}: {e}"); + return true; + } + }; + let next = pos + samples; if !emit( &mut interleaved, channels, diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 00584e7..144ed01 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -280,15 +280,18 @@ impl Mp4Demuxer { } } -/// One Matroska block of the video track: where its bytes are and whether a -/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7 -/// MB of index -- the price of knowing the frame count and the sync points of a +/// One Matroska block of an indexed track: where its bytes are, whether a +/// decoder may start on it, and when it is presented (in `TimestampScale` +/// ticks, which is what a sound track seeks against -- Matroska indexes no +/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of +/// index -- the price of knowing the frame count and the sync points of a /// container that indexes neither. #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Block { at: u64, len: usize, key: bool, + ts: i64, } /// AV1 out of a Matroska file (`.mkv`/`.webm`). @@ -314,7 +317,7 @@ impl MkvDemuxer { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - let (video, _) = mkv_tracks(&mut file, segment)?; + let (video, _, _) = mkv_tracks(&mut file, segment)?; let video = video.ok_or( "no AV1 video track in this Matroska file — AV1 is the only codec read from one", )?; @@ -398,7 +401,92 @@ pub fn matroska_audio_codec(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) + Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec)| codec)) +} + +/// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio +/// track, in storage order, with the timestamp a seek resolves against. The +/// same walk the picture costs ([`MkvDemuxer`]), on the other track number, and +/// the two keep their own file handle and their own index -- the sound is +/// opened by the audio worker and the picture by the decoder, never together. +/// +/// Matroska carries no sample table, so a block's own timestamp is the only +/// thing a window can be resolved against; [`Self::block_at`] is what an `stts` +/// lookup is on the mp4 side. +pub struct MkvAudio { + file: File, + blocks: Vec, + /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`. + pub codec: &'static str, + /// Seconds one `TimestampScale` tick is worth, resolved once at open. + secs_per_tick: f64, +} + +impl MkvAudio { + /// `Ok(None)` when `path` has no audio track at all, or when its first one + /// 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. + pub fn open(path: &Path) -> 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)) = audio else { + return Ok(None); + }; + let codec = match codec.as_str() { + "A_AC3" => "ac3", + "A_EAC3" => "eac3", + _ => return Ok(None), + }; + let (blocks, _) = mkv_blocks(&mut file, segment, number)?; + if blocks.is_empty() { + return Err("the AC-3 track in this Matroska file has no blocks".into()); + } + Ok(Some(Self { + file, + blocks, + codec, + secs_per_tick: timestamp_scale as f64 / 1e9, + })) + } + + /// How many blocks the track has; one syncframe each, lacing being refused + /// in [`mkv_blocks`]. + pub fn blocks(&self) -> usize { + self.blocks.len() + } + + /// The bytes of block `index` -- one whole packet for the decoder, an + /// E-AC-3 frame's dependent substreams included. `None` past the last one. + pub fn frame(&mut self, index: usize) -> crate::Result>> { + let Some(&block) = self.blocks.get(index) else { + return Ok(None); + }; + let mut bytes = vec![0u8; block.len]; + read_exact_at(&mut self.file, block.at, &mut bytes)?; + Ok(Some(bytes)) + } + + /// When block `index` is presented, in seconds on the file's own clock. The + /// last block's time for anything past the end, which is what a duration + /// wants. + pub fn secs(&self, index: usize) -> f64 { + let index = index.min(self.blocks.len().saturating_sub(1)); + self.blocks.get(index).map_or(0.0, |b| b.ts as f64) * self.secs_per_tick + } + + /// The block a decoder is started from to hear `secs`: the last one at or + /// before it, `pre_roll` blocks earlier so the decoder has something to warm + /// up on before the audible part. Blocks are in storage order, which for a + /// sound track is presentation order (no reordering exists in AC-3). + pub fn block_at(&self, secs: f64, pre_roll: usize) -> usize { + let ticks = (secs / self.secs_per_tick) as i64; + self.blocks + .partition_point(|b| b.ts <= ticks) + .saturating_sub(1 + pre_roll) + } } /// What the `Tracks` element says about the AV1 track. @@ -445,16 +533,17 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { Err("no Segment element: not a Matroska file".into()) } -/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be -/// named -- the second is what tells a user why a file with sound plays silent -/// ([`crate::audio::AudioSession::unsupported`]). +/// The AV1 video track of `segment`, the number and codec id of its first audio +/// track, and the segment's `TimestampScale` in nanoseconds. The audio pair is +/// what [`MkvAudio`] reads a sound track from and what tells a user why a file +/// with sound plays silent ([`crate::audio::AudioSession::unsupported`]). /// /// 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)> { +) -> crate::Result<(Option, Option<(u64, String)>, u64)> { let (mut video, mut audio) = (None, None); let mut timestamp_scale = 1_000_000; let mut at = segment.0; @@ -476,7 +565,7 @@ fn mkv_tracks( if e.0 == TRACK_ENTRY { match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { (Some(track), _) if video.is_none() => video = Some(track), - (_, Some(codec)) if audio.is_none() => audio = Some(codec), + (_, Some(track)) if audio.is_none() => audio = Some(track), _ => {} } } @@ -487,17 +576,17 @@ fn mkv_tracks( } at = stop; } - Ok((video, audio)) + Ok((video, audio, timestamp_scale)) } -/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id -/// of an audio track otherwise. +/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the number +/// and codec id of an audio track otherwise. fn mkv_track_entry( file: &mut File, body: u64, end: u64, timestamp_scale: u64, -) -> crate::Result<(Option, Option)> { +) -> crate::Result<(Option, Option<(u64, String)>)> { 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 at = body; @@ -540,7 +629,7 @@ fn mkv_track_entry( }), None, )), - (2, _) => Ok((None, Some(codec))), + (2, _) => Ok((None, Some((number, codec)))), _ => Ok((None, None)), } } @@ -628,11 +717,17 @@ fn mkv_blocks( if block.number != number { continue; } - // Lacing packs several frames into one block. Audio muxers use it, - // video ones do not, and guessing at frame boundaries inside a laced - // block is not something to do silently. + // Lacing packs several frames into one block, behind a header of + // frame sizes this does not read. Video muxers write none; an audio + // muxer may, and guessing at frame boundaries inside a laced block + // is not something to do silently. + // + // ponytail: a laced audio track is refused by name rather than + // played. The upgrade path is the three lace headers of the spec + // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg, + // which writes the fixtures and most remuxes, laces nothing. if block.flags & 0x06 != 0 { - return Err("laced video blocks are not supported".into()); + return Err("laced Matroska blocks are not supported".into()); } let ts = cluster_ts + i64::from(block.rel); span = Some(match span { @@ -643,6 +738,7 @@ fn mkv_blocks( at: block.at, len: block.len, key, + ts, }); } } diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index 4348dc4..802f7cc 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -160,6 +160,98 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { } } +/// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and +/// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" +/// refusal used to fire on -- both come out of the blocks, both arrive as the +/// stereo the §7.8 downmix hands the timeline, and neither owes the session an +/// excuse any more. +#[test] +fn matroska_ac3_and_eac3_decode_out_of_the_blocks() { + for (name, codec) in [("test_ac3.mkv", "ac-3"), ("test_eac3.mkv", "e-ac-3")] { + let path = asset(name); + let (meta, rx) = AudioSession::open(&path) + .expect("open") + .expect("Matroska AC-3 decodes now"); + assert_eq!((meta.sample_rate, meta.channels), (48000, 2), "{name}"); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let secs = (samples.len() / 2) as f64 / 48000.0; + assert!( + (1.9..2.1).contains(&secs), + "{name} is two seconds, decoded {secs:.3}s" + ); + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() + / samples.len() as f64) + .sqrt(); + assert!( + (0.005..0.75).contains(&rms), + "{name}: RMS {rms:.6} is not a sine at a sane level" + ); + assert!( + samples.iter().all(|s| s.abs() <= 1.0), + "{name}: the decode must not leave the device's range" + ); + // The user-facing half: the session comes up with sound and no notice, + // and the file's one audio stream is offered by the name it is in. + let session = engine::PlaybackSession::open(&path).expect("open for playback"); + assert_eq!( + session.audio_disabled_reason(), + None, + "{name}: a track that decodes owes no excuse" + ); + let streams = AudioSession::probe_streams(&path).expect("streams"); + assert_eq!(streams.len(), 1, "{name}: one audio track, one row"); + assert_eq!(streams[0].codec, codec, "{name}"); + assert!(streams[0].decodable, "{name}"); + assert_eq!( + AudioSession::unsupported(&path).expect("unsupported"), + None, + "{name}: nothing to excuse when it plays" + ); + } + // The invariant, stated as an assert: a Matroska file whose sound is in a + // codec this still cannot read is named, not silently silent. + let reason = AudioSession::unsupported(asset("test_av1.mkv")) + .expect("unsupported") + .expect("the AAC track of an mkv is still named"); + assert!(reason.contains("A_AAC") && reason.contains("not wired"), "{reason}"); +} + +/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block +/// a decode starts on is found by the blocks' own timestamps -- and getting that +/// wrong is a tail that is the wrong length or lands in the wrong place. It is +/// the same check `audio_seek` makes of the mp4 path, on the container that has +/// no sample table. +#[test] +fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() { + let path = asset("test_eac3.mkv"); + let full: Vec = AudioSession::open(&path) + .expect("open") + .expect("audio") + .1 + .into_iter() + .flat_map(|c| c.samples) + .collect(); + let start = 48_000u64; // one second in, in frames per channel + let mut next = start; + let mut tail = Vec::new(); + for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 { + assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek"); + next += (chunk.samples.len() / 2) as u64; + tail.extend(chunk.samples); + } + let want = &full[start as usize * 2..]; + assert_eq!(tail.len(), want.len(), "the seeked run is a different length"); + let diff = tail + .iter() + .zip(want) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, f32::max); + // One syncframe of pre-roll is what the 256-sample overlap-add needs, so + // this is exact in practice; the tolerance is for a decoder that carries + // more state than the frame before, not for a wrong block. + assert!(diff < 1e-3, "max abs diff {diff} after the seek"); +} + /// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC /// encoder here -- and that refusal is named, never a silent silent export. #[test] diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 12106b6..4349779 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -113,6 +113,22 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -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 libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av1.mkv +# Matroska sound: the two Dolby codecs that arrive in one and are read straight +# out of its blocks (`demux::MkvAudio`). Stereo AC-3 for the plain syntax and +# **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must +# come down to stereo through the same A/52 7.8 downmix the mp4 path uses. +# 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small +# picture on purpose: these two are about the sound. +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ + -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \ + -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -c:a ac3 -b:a 192k assets/test_ac3.mkv +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 libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.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.