From f40e85cc619058a8d7bbbbeab4964c3018bca8d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 19:36:40 +0300 Subject: [PATCH] feat(mux): declare an audio encoder's priming so no-elst/no-CodecDelay means zero delay Root cause: mp4's elst and Matroska's CodecDelay only ever came from a reordered video track's ctts offset, so an AAC track's encoder priming (one 1024-sample frame, always) was never written. A downstream reader had no way to distinguish "this file truly has zero delay" from "this file's muxer never said" and had to guess a fallback -- guessing wrong either trims real audio from a genuinely delay-free file or leaves an encoder's priming samples in. ec-mp4: Mp4Muxer::set_audio_delay(stream, priming_samples) folds into the same elst media_time/segment_duration the video-reorder path already writes (a shift, never a trim); the demuxer already applied elst generically, so no demux change was needed there -- verified with a mux+demux round trip. ec-matroska: the muxer already wrote CodecDelay (set_track_delay), but the demuxer never read it back. CodecDelay is a decode-but-don't-play priming, the same contract as StreamInfo::initial_padding (which mp3/Opus already use) and not a timeline shift, so it is converted ns -> samples and reported there. ec-aac: AacEncoder::encoder_delay() -> usize accessor (1024, the fixed cost of the first MDCT window's overlap-add having nothing to overlap yet) for a muxer caller to pass into the above. Tests: ec-mp4::aac_priming_round_trips_through_an_elst, ec-matroska::aac_priming_round_trips_through_codec_delay. --- crates/ec-matroska/src/demux.rs | 11 ++++++++ crates/ec-matroska/tests/matroska.rs | 41 ++++++++++++++++++++++++++-- crates/ec-mp4/src/mux.rs | 34 +++++++++++++++++++---- crates/ec-mp4/tests/mp4.rs | 41 ++++++++++++++++++++++++++++ 4 files changed, 119 insertions(+), 8 deletions(-) diff --git a/crates/ec-matroska/src/demux.rs b/crates/ec-matroska/src/demux.rs index f4d658d5..c5f6638a 100644 --- a/crates/ec-matroska/src/demux.rs +++ b/crates/ec-matroska/src/demux.rs @@ -1174,12 +1174,18 @@ fn parse_tracks( let mut display = (0u64, 0u64); let mut light = ContentLight::default(); let (mut rate, mut channels, mut bits) = (0f64, 0u64, 0u64); + // `CodecDelay`, nanoseconds: an AAC/Opus encoder's priming, the same + // samples-before-the-first-audible-one an mp4's `elst` or an mp3's LAME + // tag states — converted to a sample count once the track's own rate + // is known, below. + let mut delay_ns = 0u64; for (id, child) in Elements::new(&buf[range]) { let child = start + child.start..start + child.end; match id { ebml::TRACK_NUMBER => number = ebml::uint_of(&buf[child]), ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]), ebml::CODEC_ID => codec = ebml::string_of(&buf[child]), + ebml::CODEC_DELAY => delay_ns = ebml::uint_of(&buf[child]), ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])), ebml::TRACK_NAME => name = ebml::string_of(&buf[child]), ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]), @@ -1287,6 +1293,11 @@ fn parse_tracks( info.start_time = Some(0); info.language = Some(language_of(&language, &bcp47)); info.default = flag_default; + if media == MediaType::Audio && delay_ns > 0 { + let sample_rate = u64::from(info.params.audio().map_or(8_000, |a| a.sample_rate)); + info.initial_padding = + ((delay_ns * sample_rate + 500_000_000) / 1_000_000_000) as u32; + } streams.push(info); Some(index) } diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index b8ea327c..2b83ac02 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -8,9 +8,47 @@ use std::io::BufReader; use std::path::{Path, PathBuf}; use std::process::Command; -use ec_core::{Demuxer, Error, MediaType, Muxer, SeekMode, TimeBase, Timestamp}; +use ec_core::{ + CodecId, Demuxer, Error, MediaParameters, MediaType, Muxer, Packet, SeekMode, StreamInfo, + TimeBase, Timestamp, +}; use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; +/// An AAC track's encoder priming round trips as `CodecDelay`: the demuxer +/// converts the stated nanoseconds back to a sample count on +/// [`ec_core::StreamInfo::initial_padding`] — the same field an mp3's LAME tag +/// or an Opus pre-skip fills, since a Matroska `CodecDelay` names the identical +/// thing (decode-but-don't-play priming), not a timeline shift. +#[test] +fn aac_priming_round_trips_through_codec_delay() { + let rate = TimeBase::from_rate(48_000); + let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac)); + if let MediaParameters::Audio(a) = &mut info.params.media { + a.sample_rate = 48_000; + a.layout = ec_core::ChannelLayout::Stereo; + } + info.params.extradata = Some(ec_core::Buf::copy_from_slice(&[0x11, 0x90])); + + let dst = work().join("aac-priming-round-trip.mkv"); + let mut muxer = MatroskaMuxer::new(File::create(&dst).expect("output")); + let stream = muxer.add_stream(info).expect("stream declared"); + muxer.set_track_delay(stream, 21_333_333).expect("declare delay"); // 1024/48000s + for _ in 0..10i64 { + let mut packet = Packet::new(0, rate, vec![0u8; 8]); + packet.duration = Some(1024); + packet.flags.keyframe = true; + muxer.write_packet(&packet).expect("packet written"); + } + muxer.finish().expect("finished"); + + let demuxer = + MatroskaDemuxer::new(BufReader::new(File::open(&dst).expect("opens"))).expect("reopens"); + assert_eq!( + demuxer.streams()[0].initial_padding, 1024, + "CodecDelay round trips to a sample count" + ); +} + fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") } @@ -987,7 +1025,6 @@ fn real_hdr_film_container_states_no_light_metadata() { use ec_ac3::Ac3Decoder; use ec_aac::AacDecoder; -use ec_core::CodecId; /// Opens whichever container `path` actually is — both crates implement the /// same `Demuxer` trait, so the rest of the harness never has to know which. diff --git a/crates/ec-mp4/src/mux.rs b/crates/ec-mp4/src/mux.rs index 04e8f7c7..086ca48e 100644 --- a/crates/ec-mp4/src/mux.rs +++ b/crates/ec-mp4/src/mux.rs @@ -38,6 +38,11 @@ struct Track { /// new one". chunk_end: u64, title: Option, + /// An audio encoder's priming: samples it emits before the first audible + /// one (an AAC-LC encoder's 1024-sample delay), in this track's + /// timescale. Written the same way as a video track's reorder delay: an + /// `edts/elst` media_time shift, never a trim. + audio_delay: i64, } /// An MP4 writer over anything seekable. @@ -117,6 +122,21 @@ impl Mp4Muxer { Ok(()) } + /// Declare an audio track's encoder delay: `priming_samples` produced + /// before the first audible one, in the track's own sample rate (which is + /// its timescale, so this is a sample count with no conversion). Written + /// as an `edts/elst` media_time shift at [`Muxer::finish`] — the same + /// mechanism a reordered video track's `elst` uses, and the ISO + /// 14496-14 convention for AAC priming. + pub fn set_audio_delay(&mut self, stream: u32, priming_samples: u32) -> Result<()> { + let track = self + .tracks + .get_mut(stream as usize) + .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to delay")))?; + track.audio_delay = i64::from(priming_samples); + Ok(()) + } + /// Take the writer back once the file is finished. pub fn into_inner(self) -> W { self.w @@ -242,12 +262,13 @@ impl Mp4Muxer { out.extend_from_slice(&(height << 16).to_be_bytes()); close(out, tkhd); - // An `elst`, where the first picture is not the first *decoded* one: a - // reordered stream's earliest composition time is the reorder delay, and - // without an edit saying so every player starts the track that much - // late. This is where a demuxer's `media_time` comes from, and it is a - // shift, never a trim. - let priming = presentation_start(track); + // An `elst`, where the first picture is not the first *decoded* one, or + // an audio track's encoder primed samples ahead of the first audible + // one (`set_audio_delay`): a reordered stream's earliest composition + // time is the reorder delay, and without an edit saying so every + // player starts the track that much late. This is where a demuxer's + // `media_time` comes from, and it is a shift, never a trim. + let priming = presentation_start(track).max(track.audio_delay); if priming > 0 { let edts = open(out, b"edts"); let elst = open(out, b"elst"); @@ -368,6 +389,7 @@ impl Muxer for Mp4Muxer { chunks: Vec::new(), chunk_end: u64::MAX, title: None, + audio_delay: 0, }); Ok(index) } diff --git a/crates/ec-mp4/tests/mp4.rs b/crates/ec-mp4/tests/mp4.rs index ee395ba5..452878e4 100644 --- a/crates/ec-mp4/tests/mp4.rs +++ b/crates/ec-mp4/tests/mp4.rs @@ -658,6 +658,47 @@ fn ntsc_timing_survives_a_round_trip_exactly() { assert_eq!(keys, 4); } +/// An AAC track's encoder priming round trips as an `edts/elst` media_time +/// shift: the demuxer reports it back on [`Mp4Demuxer::tracks`] and every +/// packet's timeline is shifted by exactly that much, never trimmed. +#[test] +fn aac_priming_round_trips_through_an_elst() { + let rate = TimeBase::from_rate(48_000); + let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac)); + if let MediaParameters::Audio(a) = &mut info.params.media { + a.sample_rate = 48_000; + a.layout = ec_core::ChannelLayout::Stereo; + } + info.params.extradata = Some(Buf::copy_from_slice(&[0x11, 0x90])); // AAC-LC 48k stereo ASC + + let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); + let stream = muxer.add_stream(info).expect("stream"); + muxer.set_audio_delay(stream, 1024).expect("declare delay"); + // ~1 s of AAC frames, one 1024-sample frame each, no explicit pts/dts: a + // constant-rate track lays out end to end. + for _ in 0..47i64 { + let mut packet = Packet::new(0, rate, vec![0u8; 8]); + packet.duration = Some(1024); + packet.flags.keyframe = true; + muxer.write_packet(&packet).expect("packet"); + } + muxer.finish().expect("finish"); + let file = muxer.into_inner().into_inner(); + + let mut demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens"); + assert_eq!( + demuxer.tracks()[0].media_time, + Some(1024), + "the elst's media_time is the declared priming" + ); + let first = demuxer.next_packet().expect("first packet"); + assert_eq!( + first.pts, + Some(-1024), + "the demuxer applies the elst as a pure shift, never a trim" + ); +} + /// The real library, end to end: every mp4-family file the manifest lists /// demuxes to EOF with the packet counts ffprobe counts. ///