Declare an audio encoder's priming so no-elst/no-CodecDelay means zero delay
Browse files at this commitf40e85cc619058a8d7bbbbeab4964c3018bca8d9Parent: 8ec0f40- feat
- declare an audio encoder's priming so no-elst/no-CodecDelay means zero delay
4 changed files +119 -8
- crates/ec-matroska/src/demux.rs +11 -0
- crates/ec-matroska/tests/matroska.rs +39 -2
- crates/ec-mp4/src/mux.rs +28 -6
- crates/ec-mp4/tests/mp4.rs +41 -0
crates/ec-matroska/src/demux.rsmodified+11 -0
| @@ -1174,12 +1174,18 @@ fn parse_tracks( | |||
| 1174 | let mut display = (0u64, 0u64); | 1174 | let mut display = (0u64, 0u64); |
| 1175 | let mut light = ContentLight::default(); | 1175 | let mut light = ContentLight::default(); |
| 1176 | let (mut rate, mut channels, mut bits) = (0f64, 0u64, 0u64); | 1176 | let (mut rate, mut channels, mut bits) = (0f64, 0u64, 0u64); |
| 1177 | + // `CodecDelay`, nanoseconds: an AAC/Opus encoder's priming, the same | ||
| 1178 | + // samples-before-the-first-audible-one an mp4's `elst` or an mp3's LAME | ||
| 1179 | + // tag states — converted to a sample count once the track's own rate | ||
| 1180 | + // is known, below. | ||
| 1181 | + let mut delay_ns = 0u64; | ||
| 1177 | for (id, child) in Elements::new(&buf[range]) { | 1182 | for (id, child) in Elements::new(&buf[range]) { |
| 1178 | let child = start + child.start..start + child.end; | 1183 | let child = start + child.start..start + child.end; |
| 1179 | match id { | 1184 | match id { |
| 1180 | ebml::TRACK_NUMBER => number = ebml::uint_of(&buf[child]), | 1185 | ebml::TRACK_NUMBER => number = ebml::uint_of(&buf[child]), |
| 1181 | ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]), | 1186 | ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]), |
| 1182 | ebml::CODEC_ID => codec = ebml::string_of(&buf[child]), | 1187 | ebml::CODEC_ID => codec = ebml::string_of(&buf[child]), |
| 1188 | + ebml::CODEC_DELAY => delay_ns = ebml::uint_of(&buf[child]), | ||
| 1183 | ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])), | 1189 | ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])), |
| 1184 | ebml::TRACK_NAME => name = ebml::string_of(&buf[child]), | 1190 | ebml::TRACK_NAME => name = ebml::string_of(&buf[child]), |
| 1185 | ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]), | 1191 | ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]), |
| @@ -1287,6 +1293,11 @@ fn parse_tracks( | |||
| 1287 | info.start_time = Some(0); | 1293 | info.start_time = Some(0); |
| 1288 | info.language = Some(language_of(&language, &bcp47)); | 1294 | info.language = Some(language_of(&language, &bcp47)); |
| 1289 | info.default = flag_default; | 1295 | info.default = flag_default; |
| 1296 | + if media == MediaType::Audio && delay_ns > 0 { | ||
| 1297 | + let sample_rate = u64::from(info.params.audio().map_or(8_000, |a| a.sample_rate)); | ||
| 1298 | + info.initial_padding = | ||
| 1299 | + ((delay_ns * sample_rate + 500_000_000) / 1_000_000_000) as u32; | ||
| 1300 | + } | ||
| 1290 | streams.push(info); | 1301 | streams.push(info); |
| 1291 | Some(index) | 1302 | Some(index) |
| 1292 | } | 1303 | } |
crates/ec-matroska/tests/matroska.rsmodified+39 -2
| @@ -8,9 +8,47 @@ use std::io::BufReader; | |||
| 8 | use std::path::{Path, PathBuf}; | 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::process::Command; | 9 | use std::process::Command; |
| 10 | 10 | ||
| 11 | -use ec_core::{Demuxer, Error, MediaType, Muxer, SeekMode, TimeBase, Timestamp}; | 11 | +use ec_core::{ |
| 12 | + CodecId, Demuxer, Error, MediaParameters, MediaType, Muxer, Packet, SeekMode, StreamInfo, | ||
| 13 | + TimeBase, Timestamp, | ||
| 14 | +}; | ||
| 12 | use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; | 15 | use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; |
| 13 | 16 | ||
| 17 | +/// An AAC track's encoder priming round trips as `CodecDelay`: the demuxer | ||
| 18 | +/// converts the stated nanoseconds back to a sample count on | ||
| 19 | +/// [`ec_core::StreamInfo::initial_padding`] — the same field an mp3's LAME tag | ||
| 20 | +/// or an Opus pre-skip fills, since a Matroska `CodecDelay` names the identical | ||
| 21 | +/// thing (decode-but-don't-play priming), not a timeline shift. | ||
| 22 | +#[test] | ||
| 23 | +fn aac_priming_round_trips_through_codec_delay() { | ||
| 24 | + let rate = TimeBase::from_rate(48_000); | ||
| 25 | + let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac)); | ||
| 26 | + if let MediaParameters::Audio(a) = &mut info.params.media { | ||
| 27 | + a.sample_rate = 48_000; | ||
| 28 | + a.layout = ec_core::ChannelLayout::Stereo; | ||
| 29 | + } | ||
| 30 | + info.params.extradata = Some(ec_core::Buf::copy_from_slice(&[0x11, 0x90])); | ||
| 31 | + | ||
| 32 | + let dst = work().join("aac-priming-round-trip.mkv"); | ||
| 33 | + let mut muxer = MatroskaMuxer::new(File::create(&dst).expect("output")); | ||
| 34 | + let stream = muxer.add_stream(info).expect("stream declared"); | ||
| 35 | + muxer.set_track_delay(stream, 21_333_333).expect("declare delay"); // 1024/48000s | ||
| 36 | + for _ in 0..10i64 { | ||
| 37 | + let mut packet = Packet::new(0, rate, vec![0u8; 8]); | ||
| 38 | + packet.duration = Some(1024); | ||
| 39 | + packet.flags.keyframe = true; | ||
| 40 | + muxer.write_packet(&packet).expect("packet written"); | ||
| 41 | + } | ||
| 42 | + muxer.finish().expect("finished"); | ||
| 43 | + | ||
| 44 | + let demuxer = | ||
| 45 | + MatroskaDemuxer::new(BufReader::new(File::open(&dst).expect("opens"))).expect("reopens"); | ||
| 46 | + assert_eq!( | ||
| 47 | + demuxer.streams()[0].initial_padding, 1024, | ||
| 48 | + "CodecDelay round trips to a sample count" | ||
| 49 | + ); | ||
| 50 | +} | ||
| 51 | + | ||
| 14 | fn fixtures() -> PathBuf { | 52 | fn fixtures() -> PathBuf { |
| 15 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") | 53 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") |
| 16 | } | 54 | } |
| @@ -987,7 +1025,6 @@ fn real_hdr_film_container_states_no_light_metadata() { | |||
| 987 | 1025 | ||
| 988 | use ec_ac3::Ac3Decoder; | 1026 | use ec_ac3::Ac3Decoder; |
| 989 | use ec_aac::AacDecoder; | 1027 | use ec_aac::AacDecoder; |
| 990 | -use ec_core::CodecId; | ||
| 991 | 1028 | ||
| 992 | /// Opens whichever container `path` actually is — both crates implement the | 1029 | /// Opens whichever container `path` actually is — both crates implement the |
| 993 | /// same `Demuxer` trait, so the rest of the harness never has to know which. | 1030 | /// same `Demuxer` trait, so the rest of the harness never has to know which. |
crates/ec-mp4/src/mux.rsmodified+28 -6
| @@ -38,6 +38,11 @@ struct Track { | |||
| 38 | /// new one". | 38 | /// new one". |
| 39 | chunk_end: u64, | 39 | chunk_end: u64, |
| 40 | title: Option<String>, | 40 | title: Option<String>, |
| 41 | + /// An audio encoder's priming: samples it emits before the first audible | ||
| 42 | + /// one (an AAC-LC encoder's 1024-sample delay), in this track's | ||
| 43 | + /// timescale. Written the same way as a video track's reorder delay: an | ||
| 44 | + /// `edts/elst` media_time shift, never a trim. | ||
| 45 | + audio_delay: i64, | ||
| 41 | } | 46 | } |
| 42 | 47 | ||
| 43 | /// An MP4 writer over anything seekable. | 48 | /// An MP4 writer over anything seekable. |
| @@ -117,6 +122,21 @@ impl<W: Write + Seek> Mp4Muxer<W> { | |||
| 117 | Ok(()) | 122 | Ok(()) |
| 118 | } | 123 | } |
| 119 | 124 | ||
| 125 | + /// Declare an audio track's encoder delay: `priming_samples` produced | ||
| 126 | + /// before the first audible one, in the track's own sample rate (which is | ||
| 127 | + /// its timescale, so this is a sample count with no conversion). Written | ||
| 128 | + /// as an `edts/elst` media_time shift at [`Muxer::finish`] — the same | ||
| 129 | + /// mechanism a reordered video track's `elst` uses, and the ISO | ||
| 130 | + /// 14496-14 convention for AAC priming. | ||
| 131 | + pub fn set_audio_delay(&mut self, stream: u32, priming_samples: u32) -> Result<()> { | ||
| 132 | + let track = self | ||
| 133 | + .tracks | ||
| 134 | + .get_mut(stream as usize) | ||
| 135 | + .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to delay")))?; | ||
| 136 | + track.audio_delay = i64::from(priming_samples); | ||
| 137 | + Ok(()) | ||
| 138 | + } | ||
| 139 | + | ||
| 120 | /// Take the writer back once the file is finished. | 140 | /// Take the writer back once the file is finished. |
| 121 | pub fn into_inner(self) -> W { | 141 | pub fn into_inner(self) -> W { |
| 122 | self.w | 142 | self.w |
| @@ -242,12 +262,13 @@ impl<W: Write + Seek> Mp4Muxer<W> { | |||
| 242 | out.extend_from_slice(&(height << 16).to_be_bytes()); | 262 | out.extend_from_slice(&(height << 16).to_be_bytes()); |
| 243 | close(out, tkhd); | 263 | close(out, tkhd); |
| 244 | 264 | ||
| 245 | - // An `elst`, where the first picture is not the first *decoded* one: a | 265 | + // An `elst`, where the first picture is not the first *decoded* one, or |
| 246 | - // reordered stream's earliest composition time is the reorder delay, and | 266 | + // an audio track's encoder primed samples ahead of the first audible |
| 247 | - // without an edit saying so every player starts the track that much | 267 | + // one (`set_audio_delay`): a reordered stream's earliest composition |
| 248 | - // late. This is where a demuxer's `media_time` comes from, and it is a | 268 | + // time is the reorder delay, and without an edit saying so every |
| 249 | - // shift, never a trim. | 269 | + // player starts the track that much late. This is where a demuxer's |
| 250 | - let priming = presentation_start(track); | 270 | + // `media_time` comes from, and it is a shift, never a trim. |
| 271 | + let priming = presentation_start(track).max(track.audio_delay); | ||
| 251 | if priming > 0 { | 272 | if priming > 0 { |
| 252 | let edts = open(out, b"edts"); | 273 | let edts = open(out, b"edts"); |
| 253 | let elst = open(out, b"elst"); | 274 | let elst = open(out, b"elst"); |
| @@ -368,6 +389,7 @@ impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> { | |||
| 368 | chunks: Vec::new(), | 389 | chunks: Vec::new(), |
| 369 | chunk_end: u64::MAX, | 390 | chunk_end: u64::MAX, |
| 370 | title: None, | 391 | title: None, |
| 392 | + audio_delay: 0, | ||
| 371 | }); | 393 | }); |
| 372 | Ok(index) | 394 | Ok(index) |
| 373 | } | 395 | } |
crates/ec-mp4/tests/mp4.rsmodified+41 -0
| @@ -658,6 +658,47 @@ fn ntsc_timing_survives_a_round_trip_exactly() { | |||
| 658 | assert_eq!(keys, 4); | 658 | assert_eq!(keys, 4); |
| 659 | } | 659 | } |
| 660 | 660 | ||
| 661 | +/// An AAC track's encoder priming round trips as an `edts/elst` media_time | ||
| 662 | +/// shift: the demuxer reports it back on [`Mp4Demuxer::tracks`] and every | ||
| 663 | +/// packet's timeline is shifted by exactly that much, never trimmed. | ||
| 664 | +#[test] | ||
| 665 | +fn aac_priming_round_trips_through_an_elst() { | ||
| 666 | + let rate = TimeBase::from_rate(48_000); | ||
| 667 | + let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac)); | ||
| 668 | + if let MediaParameters::Audio(a) = &mut info.params.media { | ||
| 669 | + a.sample_rate = 48_000; | ||
| 670 | + a.layout = ec_core::ChannelLayout::Stereo; | ||
| 671 | + } | ||
| 672 | + info.params.extradata = Some(Buf::copy_from_slice(&[0x11, 0x90])); // AAC-LC 48k stereo ASC | ||
| 673 | + | ||
| 674 | + let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); | ||
| 675 | + let stream = muxer.add_stream(info).expect("stream"); | ||
| 676 | + muxer.set_audio_delay(stream, 1024).expect("declare delay"); | ||
| 677 | + // ~1 s of AAC frames, one 1024-sample frame each, no explicit pts/dts: a | ||
| 678 | + // constant-rate track lays out end to end. | ||
| 679 | + for _ in 0..47i64 { | ||
| 680 | + let mut packet = Packet::new(0, rate, vec![0u8; 8]); | ||
| 681 | + packet.duration = Some(1024); | ||
| 682 | + packet.flags.keyframe = true; | ||
| 683 | + muxer.write_packet(&packet).expect("packet"); | ||
| 684 | + } | ||
| 685 | + muxer.finish().expect("finish"); | ||
| 686 | + let file = muxer.into_inner().into_inner(); | ||
| 687 | + | ||
| 688 | + let mut demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens"); | ||
| 689 | + assert_eq!( | ||
| 690 | + demuxer.tracks()[0].media_time, | ||
| 691 | + Some(1024), | ||
| 692 | + "the elst's media_time is the declared priming" | ||
| 693 | + ); | ||
| 694 | + let first = demuxer.next_packet().expect("first packet"); | ||
| 695 | + assert_eq!( | ||
| 696 | + first.pts, | ||
| 697 | + Some(-1024), | ||
| 698 | + "the demuxer applies the elst as a pure shift, never a trim" | ||
| 699 | + ); | ||
| 700 | +} | ||
| 701 | + | ||
| 661 | /// The real library, end to end: every mp4-family file the manifest lists | 702 | /// The real library, end to end: every mp4-family file the manifest lists |
| 662 | /// demuxes to EOF with the packet counts ffprobe counts. | 703 | /// demuxes to EOF with the packet counts ffprobe counts. |
| 663 | /// | 704 | /// |