diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index d53be99..c891e19 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -66,10 +66,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; @@ -541,17 +537,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: AAC is read out of one ([`Track::open`]) and everything - // else -- Opus, AC-3, DTS, none of which symphonia decodes at any - // version -- is named rather than left playing silent with no reason - // given. A Matroska file with no audio track at all returns `None` here - // like any other silent file. + // Matroska: what symphonia reads out of one ([`Track::open`]) plus the + // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder + // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here + // has at any version -- is named rather than left 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| { - format!("the {codec} track of this Matroska file cannot be decoded (AAC only)") - }), - ); + let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { + return Ok(None); + }; + // An AC-3 track that came up silent all the same is one that could + // not be read -- a laced block, an unreadable syncframe -- and the + // reader's own words are the ones worth showing. + return Ok(Some(match MkvAc3Track::open(path.as_ref()) { + Ok(Some(_)) => return Ok(None), + Ok(None) => format!( + "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" + ), + 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(); @@ -599,10 +604,24 @@ impl AudioSession { 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`]) -- so it lists like a + // 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. 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 Ok(track) = SymTrack::open(path) else { return Ok(Vec::new()); }; @@ -924,7 +943,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. The export decodes it and encodes AAC, exactly // as it does for every other source no copy reaches. - Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), + Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), } } @@ -947,6 +966,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), } @@ -965,16 +987,27 @@ 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 goes straight to symphonia, whose `mkv` reader is the - // one thing here that reads its packets -- neither mp4 reader can open - // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia - // has no such decoder at any version) leaves the source the silent one - // it always was, which `AudioSession::unsupported` puts into words, - // rather than failing the import of a file whose picture is fine. + // A Matroska file goes to symphonia, whose `mkv` reader is the one thing + // here that reads its packets -- neither mp4 reader can open the file at + // all -- except for the two codecs symphonia has no decoder for at any + // version and this project does: AC-3 and E-AC-3 are handed to the Dolby + // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither + // one can decode (Opus, DTS) leaves the source the silent one it always + // was, which `AudioSession::unsupported` puts into words, rather than + // failing the import of a file whose picture is fine -- and so does an + // AC-3 track that will not open, a laced block say. if crate::demux::is_matroska(path) { if stream > 0 { return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); } + match MkvAc3Track::open(path) { + Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), + Ok(None) => {} + // Named on the way past for the same reason symphonia's failure + // is, below: an AC-3 track that broke is a bug, not a codec we + // never had. + Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), + } // Logged on the way past: "silent" here covers both a codec nothing // decodes and a track that genuinely broke, and only the second is a // bug -- with no trace at all it reaches the user as a lane that @@ -1015,6 +1048,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, } } @@ -1030,6 +1064,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()), @@ -1042,6 +1081,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, } } @@ -1051,6 +1091,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, } } @@ -1061,6 +1104,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 { @@ -1082,7 +1126,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()?; @@ -1335,9 +1382,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")?; @@ -1382,6 +1429,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 @@ -1392,32 +1534,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()), @@ -2035,6 +2192,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, @@ -2200,7 +2372,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}"); @@ -2209,7 +2381,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 } @@ -2221,15 +2392,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 06e7f6c..324c0b0 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -329,15 +329,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, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). @@ -378,7 +381,7 @@ impl MkvDemuxer { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - let (video, _, other) = mkv_tracks(&mut file, segment)?; + let (video, _, other, _) = mkv_tracks(&mut file, segment)?; let video = match video { Some(video) => video, // Named, because "no video track" is a lie about a file that has one @@ -487,13 +490,99 @@ impl MkvDemuxer { /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or /// `None` for a Matroska file with no sound at all. Header only, and only worth -/// calling once a session has come up silent: no audio track of a Matroska file -/// is decoded yet, so this exists to say which one is being left out. +/// calling once a session has come up silent: a Matroska file's sound is read +/// 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> { 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 video track. @@ -543,17 +632,19 @@ 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 codec id of its first audio track, and the -/// codec id of a video track this cannot read -- the last two 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`, 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. /// /// 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, Option)> { +) -> crate::Result<(Option, Option<(u64, String)>, Option, u64)> { let (mut video, mut audio, mut other) = (None, None, None); let mut timestamp_scale = 1_000_000; let mut at = segment.0; @@ -576,7 +667,9 @@ 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(codec) if audio.is_none() => audio = Some(codec), + MkvEntry::Audio(number, codec) if audio.is_none() => { + audio = Some((number, codec)) + } _ => {} } } @@ -587,7 +680,7 @@ fn mkv_tracks( } at = stop; } - Ok((video, audio, other)) + Ok((video, audio, other, timestamp_scale)) } /// What one `TrackEntry` turned out to be. @@ -595,8 +688,9 @@ 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, likewise by its codec id (`A_AAC`, `A_OPUS`, ...). - Audio(String), + /// An audio track: its track number, which is what [`MkvAudio`] indexes the + /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...). + Audio(u64, String), /// Subtitles, buttons: nobody's here. Other, } @@ -658,7 +752,7 @@ fn mkv_track_entry( (Codec::H264, nal_length, sets, 8) } (1, _) => return Ok(MkvEntry::OtherVideo(codec)), - (2, _) => return Ok(MkvEntry::Audio(codec)), + (2, _) => return Ok(MkvEntry::Audio(number, codec)), _ => return Ok(MkvEntry::Other), }; Ok(MkvEntry::Video(MkvVideo { @@ -807,11 +901,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 { @@ -822,6 +922,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 d259ab9..e02ea9a 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -160,6 +160,103 @@ 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: the AAC track of a Matroska file is + // still symphonia's, listed and decoded exactly as it was. + let streams = AudioSession::probe_streams(asset("test_av1.mkv")).expect("streams"); + assert_eq!(streams.len(), 1); + assert_eq!(streams[0].codec, "aac", "AAC in an mkv is untouched by this"); + assert!( + AudioSession::open(asset("test_av1.mkv")) + .expect("open") + .is_some(), + "AAC in an mkv still decodes" + ); +} + +/// 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 syncframe is not something an `mp4a` sample table holds, so the /// *copy* path names it and hands the export on to the re-encode (which decodes /// this very source: the downmix above is what it encodes). Named either way -- diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index d48498b..a2466d6 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -104,8 +104,9 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ # the others so the tests measure the codec and nothing else -- but `-g 30` is # not a preference: it puts a second keyframe at frame 30, which is what the # sync index and the seek test are checked against. 8-bit Main profile here; the -# 10-bit twin is below. Its AAC track is deliberate too: Matroska audio is not -# wired to the decoder yet, and the notice that says so needs a track to name. +# 10-bit twin is below. Its AAC track is deliberate too: it is the AAC a Matroska +# file's sound is read out of through symphonia, beside the AC-3 fixtures further +# down that no symphonia version decodes. ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2" \ -f lavfi -i "sine=frequency=880:duration=2" \ @@ -176,6 +177,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ -c:a aac -b:a 384k assets/test_hevc10.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 +# H.264 picture on purpose: these two are about the sound, and the software +# decoder reads that one, so an audio test needs no VA-API plugin to open a +# session on them. +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 libx264 -profile:v baseline -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 libx264 -profile:v baseline -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.