forge
Explore
Log in

Don't you dare go Hollow

MP4 mux interleaves audio under the picture (~2s hold + pts-merged drain)

Browse files at this commit

eda44941603eae5108892f2545bbc40c4243b9afAhmet Kaan GümüşParent: 459d6b42f0f298
  • fix
    • MP4 mux interleaves audio under the picture (~2s hold + pts-merged drain)
Show full message
🐛 fix(engine): MP4 mux interleaves audio under the picture (~2s hold + pts-merged drain)
crates/engine/src/export.rsmodified+46 -3
@@ -2334,6 +2334,33 @@ fn publish_seats(
2334 *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}"));2334 *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}"));
2335 }2335 }
2336 2336
2337+/// Hands a mix that finished mixing early to the mp4 it belongs in, the
2338+/// moment both exist: `late` may land before the first coded picture has
2339+/// opened `muxer` at all, so this is tried both right where the mix lands
2340+/// and after every picture written afterwards, and does nothing once
2341+/// `*fed` says an earlier try already succeeded. Declaring the track and
2342+/// queuing its packets here is what lets [`crate::mux::Mp4Muxer`]'s own
2343+/// hold interleave them under the pictures still to come, rather than the
2344+/// track landing all at once after the picture is done.
2345+fn feed_late_audio(
2346+ muxer: &mut Option<Muxer>,
2347+ late: &Option<ExportAudio>,
2348+ fed: &mut bool,
2349+) -> crate::Result<()> {
2350+ if *fed {
2351+ return Ok(());
2352+ }
2353+ let (Some(track), Some(Muxer::Mp4(mp4))) = (late.as_ref(), muxer.as_mut()) else {
2354+ return Ok(());
2355+ };
2356+ mp4.add_audio_track(&params_of(track))?;
2357+ for packet in &track.packets {
2358+ mp4.write_audio_packet(&packet.bytes)?;
2359+ }
2360+ *fed = true;
2361+ Ok(())
2362+}
2363+
2337 fn params_of(track: &ExportAudio) -> AudioParams {2364 fn params_of(track: &ExportAudio) -> AudioParams {
2338 AudioParams {2365 AudioParams {
2339 freq_index: track.params.freq_index,2366 freq_index: track.params.freq_index,
@@ -2554,10 +2581,16 @@ fn run(
2554 // the sound landed -- the one number that says whether the two passes2581 // the sound landed -- the one number that says whether the two passes
2555 // really overlapped, in the same voice as `encode_audio`'s own timers.2582 // really overlapped, in the same voice as `encode_audio`'s own timers.
2556 let picture_started = std::time::Instant::now();2583 let picture_started = std::time::Instant::now();
2557- // The sound, once the pass beside this one has finished with it: an mp42584+ // The sound, once the pass beside this one has finished with it: joined
2558- // declares its audio track and writes its packets after the picture, so2585+ // here the moment it lands rather than only after the picture, so
2559- // this is where they arrive.2586+ // `feed_late_audio` below can hand it to the muxer while pictures are
2587+ // still being coded and let `Mp4Muxer`'s own hold interleave the two
2588+ // ([`crate::mux::Mp4Muxer`]).
2560 let mut late: Option<ExportAudio> = None;2589 let mut late: Option<ExportAudio> = None;
2590+ // Set once `late`'s track has been handed to the muxer -- so the final
2591+ // join below, which still exists for a mix that never lands mid-picture,
2592+ // knows not to declare the track or write its packets a second time.
2593+ let mut audio_fed = false;
2561 let mut muxer = None;2594 let mut muxer = None;
2562 let mut done = 0u32;2595 let mut done = 0u32;
2563 let black = Black::new(meta);2596 let black = Black::new(meta);
@@ -2718,6 +2751,7 @@ fn run(
2718 "export audio: done {:.1} s into the picture",2751 "export audio: done {:.1} s into the picture",
2719 picture_started.elapsed().as_secs_f64()2752 picture_started.elapsed().as_secs_f64()
2720 );2753 );
2754+ feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
2721 }2755 }
2722 let want = source_at(done_here);2756 let want = source_at(done_here);
2723 // How many timeline frames from here show that same picture: one at2757 // How many timeline frames from here show that same picture: one at
@@ -2826,6 +2860,11 @@ fn run(
2826 au,2860 au,
2827 key,2861 key,
2828 )?;2862 )?;
2863+ // Retried here rather than only where the mix lands: the
2864+ // very first coded picture is what creates `muxer`, and a
2865+ // mix that lands before it (a short film, or a slow first
2866+ // frame) has nothing to hand it to until now.
2867+ feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
2829 }2868 }
2830 done += 1;2869 done += 1;
2831 // Forwards only: an audio pass still running beside this one2870 // Forwards only: an audio pass still running beside this one
@@ -2898,6 +2937,10 @@ fn run(
2898 );2937 );
2899 track2938 track
2900 }2939 }
2940+ // `late` was already handed to `mp4` inside the picture loop
2941+ // ([`feed_late_audio`]) unless the mix never landed there, in
2942+ // which case it is still `None` and there was nothing to feed.
2943+ None if audio_fed => None,
2901 None => late,2944 None => late,
2902 };2945 };
2903 if let Some(track) = &track {2946 if let Some(track) = &track {
crates/engine/src/mux.rsmodified+169 -24
@@ -15,6 +15,7 @@
15 //! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`])15 //! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`])
16 //! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were.16 //! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were.
17 17
18+use std::collections::VecDeque;
18 use std::fs::{File, OpenOptions};19 use std::fs::{File, OpenOptions};
19 use std::io::{BufWriter, Read, Seek, SeekFrom, Write};20 use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
20 use std::path::{Path, PathBuf};21 use std::path::{Path, PathBuf};
@@ -41,6 +42,13 @@ const AAC_PACKET_SAMPLES: u32 = 1024;
41 /// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on42 /// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on
42 /// the same instant whichever of the two containers carries it.43 /// the same instant whichever of the two containers carries it.
43 const SUB_TIMESCALE: u32 = 1_000;44 const SUB_TIMESCALE: u32 = 1_000;
45+/// How much coded picture [`Mp4Muxer`] holds unwritten waiting for the sound
46+/// to catch up ([`Mp4Muxer::hold`]) before it gives up and flushes video-only.
47+/// Two seconds is the ceiling `export`'s own progress granularity already
48+/// tolerates (`AUDIO_BAND`), and it bounds the hold's memory to two seconds
49+/// of coded pictures -- kilobytes, not the tens of megabytes a whole film's
50+/// worth would be.
51+const HOLD_SECONDS: u64 = 2;
44 52
45 const NAL_IDR: u8 = 5;53 const NAL_IDR: u8 = 5;
46 const NAL_SEI: u8 = 6;54 const NAL_SEI: u8 = 6;
@@ -105,6 +113,41 @@ pub struct Mp4Muxer {
105 /// beside the sample entry. Empty where no track carries a title, which is113 /// beside the sample entry. Empty where no track carries a title, which is
106 /// every file that has no subtitles at all.114 /// every file that has no subtitles at all.
107 sub_names: Vec<String>,115 sub_names: Vec<String>,
116+ /// Coded pictures not yet handed to the writer, oldest first -- how the
117+ /// overlapped audio pass gets to land *under* the picture instead of
118+ /// after all of it: every `write_video_au`/`write_coded_sample` queues
119+ /// here and [`drain`](Mp4Muxer::drain) interleaves it against
120+ /// [`audio_queue`](Mp4Muxer::audio_queue) by presentation time, so the
121+ /// two tracks' bytes end up beside each other in `mdat` rather than one
122+ /// whole track then the other. `(bytes, is_sync)`.
123+ ///
124+ /// NONDETERMINISM: how tightly the two interleave depends on when the
125+ /// mix thread's join lands relative to the picture loop -- a mix that
126+ /// finishes before this hold fills stays byte-interleaved from the
127+ /// start; a mix that lands late only interleaves the tail. A test on
128+ /// this has to pin that landing (force the join before frame N in a
129+ /// fixture) rather than race the real mixer thread.
130+ hold: VecDeque<(Vec<u8>, bool)>,
131+ /// `hold`'s span, in the video track's own ticks -- flushed video-only
132+ /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands
133+ /// very late) cannot stall the encode behind an unbounded queue.
134+ hold_ticks: u64,
135+ /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet)
136+ /// before `drain` has caught up to them -- normally empty the instant
137+ /// after that call returns; only grows past one packet where the whole
138+ /// track lands in one call while the hold is still short (a picture that
139+ /// finished before its own sound).
140+ audio_queue: VecDeque<Vec<u8>>,
141+ /// Ticks, in the audio track's own rate, already written to the file --
142+ /// `drain`'s clock for comparing against `flushed_video_ticks`.
143+ audio_ticks: u64,
144+ /// Ticks, in the video track's own timescale, already written to the
145+ /// file (as opposed to merely queued in `hold`).
146+ flushed_video_ticks: u64,
147+ /// The audio track's sample rate, once [`add_audio_track`](Mp4Muxer::add_audio_track)
148+ /// has declared one -- `drain`'s clock for `audio_ticks`. 0 until then,
149+ /// which is also exactly when `audio_queue` can have nothing in it.
150+ audio_rate: u32,
108 }151 }
109 152
110 /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag153 /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag
@@ -278,6 +321,12 @@ impl Mp4Muxer {
278 timescale,321 timescale,
279 frames: 0,322 frames: 0,
280 sub_names: Vec::new(),323 sub_names: Vec::new(),
324+ hold: VecDeque::new(),
325+ hold_ticks: 0,
326+ audio_queue: VecDeque::new(),
327+ audio_ticks: 0,
328+ flushed_video_ticks: 0,
329+ audio_rate: 0,
281 };330 };
282 if let Some(audio) = audio {331 if let Some(audio) = audio {
283 muxer.add_audio_track(audio)?;332 muxer.add_audio_track(audio)?;
@@ -326,6 +375,7 @@ impl Mp4Muxer {
326 }),375 }),
327 })?;376 })?;
328 self.has_audio = true;377 self.has_audio = true;
378+ self.audio_rate = sample_rate;
329 Ok(())379 Ok(())
330 }380 }
331 381
@@ -343,18 +393,7 @@ impl Mp4Muxer {
343 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.393 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.
344 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {394 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {
345 let (bytes, is_sync) = annex_b_to_avcc(annex_b)?;395 let (bytes, is_sync) = annex_b_to_avcc(annex_b)?;
346- self.writer.write_sample(396+ self.queue_video(bytes, is_sync)
347- VIDEO_TRACK,
348- &Mp4Sample {
349- start_time: 0, // ignored by the writer; timing is duration-accumulated
350- duration: self.frame_duration,
351- rendering_offset: 0, // no B-frames on either encode path
352- is_sync,
353- bytes: Bytes::from(bytes),
354- },
355- )?;
356- self.frames += 1;
357- Ok(())
358 }397 }
359 398
360 /// One coded picture already framed the way its sample carries it: an AV1399 /// One coded picture already framed the way its sample carries it: an AV1
@@ -367,27 +406,82 @@ impl Mp4Muxer {
367 if obus.is_empty() {406 if obus.is_empty() {
368 return Err("an empty coded picture".into());407 return Err("an empty coded picture".into());
369 }408 }
409+ self.queue_video(obus.to_vec(), key)
410+ }
411+
412+ /// Queues one coded picture and tries to advance the interleave --
413+ /// shared by [`write_video_au`](Mp4Muxer::write_video_au) and
414+ /// [`write_coded_sample`](Mp4Muxer::write_coded_sample), which differ
415+ /// only in how the bytes were framed before they got here.
416+ fn queue_video(&mut self, bytes: Vec<u8>, is_sync: bool) -> crate::Result<()> {
417+ self.hold.push_back((bytes, is_sync));
418+ self.hold_ticks += u64::from(self.frame_duration);
419+ self.drain()
420+ }
421+
422+ /// Advances the interleave as far as it currently can, called after
423+ /// every single sample either track hands over: for as long as both
424+ /// queues have something in them, writes whichever track's next sample
425+ /// has the earlier presentation time -- which is what makes the release
426+ /// of a mix that landed all at once ([`write_audio_packet`](Mp4Muxer::write_audio_packet)
427+ /// fed in one tight loop) paced by how much *video* keeps arriving to
428+ /// match it against, rather than dumped in one uninterrupted run the
429+ /// moment it lands.
430+ ///
431+ /// Video queued with nothing to interleave against yet -- no audio
432+ /// track, or one declared but not fed this far ahead -- is left held,
433+ /// unless the hold has grown past [`HOLD_SECONDS`], which gives up
434+ /// waiting and writes video-only to relieve it (a mix that never lands,
435+ /// or one running well behind the picture). Audio queued with no video
436+ /// to interleave against is always left held: nothing bounds how far
437+ /// *behind* the sound the picture may run, but every path that can end
438+ /// the file ([`finish`](Mp4Muxer::finish), [`write_subtitles`](Mp4Muxer::write_subtitles))
439+ /// drains it in full first.
440+ fn drain(&mut self) -> crate::Result<()> {
441+ loop {
442+ match (self.hold.front(), self.audio_queue.front()) {
443+ (Some(_), Some(_)) => {
444+ let video_pts = self.flushed_video_ticks as f64 / f64::from(self.timescale);
445+ let audio_pts = self.audio_ticks as f64 / f64::from(self.audio_rate);
446+ if audio_pts <= video_pts {
447+ self.flush_audio_front()?;
448+ } else {
449+ self.flush_video_front()?;
450+ }
451+ }
452+ (Some(_), None) if self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) => {
453+ self.flush_video_front()?;
454+ }
455+ (Some(_), None) | (None, Some(_)) | (None, None) => break,
456+ }
457+ }
458+ Ok(())
459+ }
460+
461+ fn flush_video_front(&mut self) -> crate::Result<()> {
462+ let Some((bytes, is_sync)) = self.hold.pop_front() else {
463+ return Ok(());
464+ };
465+ self.hold_ticks -= u64::from(self.frame_duration);
370 self.writer.write_sample(466 self.writer.write_sample(
371 VIDEO_TRACK,467 VIDEO_TRACK,
372 &Mp4Sample {468 &Mp4Sample {
373- start_time: 0,469+ start_time: 0, // ignored by the writer; timing is duration-accumulated
374 duration: self.frame_duration,470 duration: self.frame_duration,
375- rendering_offset: 0,471+ rendering_offset: 0, // no B-frames on either encode path
376- is_sync: key,472+ is_sync,
377- bytes: Bytes::copy_from_slice(obus),473+ bytes: Bytes::from(bytes),
378 },474 },
379 )?;475 )?;
380 self.frames += 1;476 self.frames += 1;
477+ self.flushed_video_ticks += u64::from(self.frame_duration);
381 Ok(())478 Ok(())
382 }479 }
383 480
384- /// One raw AAC packet (no ADTS header), copied verbatim from the source --481+ fn flush_audio_front(&mut self) -> crate::Result<()> {
385- /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC482+ let Some(bytes) = self.audio_queue.pop_front() else {
386- /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.483+ return Ok(());
387- pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {484+ };
388- if !self.has_audio {
389- return Err("audio packet written to a video-only file".into());
390- }
391 self.writer.write_sample(485 self.writer.write_sample(
392 AUDIO_TRACK,486 AUDIO_TRACK,
393 &Mp4Sample {487 &Mp4Sample {
@@ -397,12 +491,54 @@ impl Mp4Muxer {
397 // Every AAC packet is a sync point; saying so per-sample would emit491 // Every AAC packet is a sync point; saying so per-sample would emit
398 // an `stss` listing all of them, while no `stss` means the same thing.492 // an `stss` listing all of them, while no `stss` means the same thing.
399 is_sync: false,493 is_sync: false,
400- bytes: Bytes::copy_from_slice(bytes),494+ bytes: Bytes::from(bytes),
401 },495 },
402 )?;496 )?;
497+ self.audio_ticks += u64::from(AAC_PACKET_SAMPLES);
498+ Ok(())
499+ }
500+
501+ /// Everything either queue has left, in presentation order regardless of
502+ /// the hold cap -- called from [`finish`](Mp4Muxer::finish), where there
503+ /// is no more picture coming for a short hold to wait on.
504+ fn drain_all(&mut self) -> crate::Result<()> {
505+ loop {
506+ match (self.hold.front(), self.audio_queue.front()) {
507+ (Some(_), Some(_)) => {
508+ let video_pts = self.flushed_video_ticks as f64 / f64::from(self.timescale);
509+ let audio_pts = self.audio_ticks as f64 / f64::from(self.audio_rate);
510+ if audio_pts <= video_pts {
511+ self.flush_audio_front()?;
512+ } else {
513+ self.flush_video_front()?;
514+ }
515+ }
516+ (Some(_), None) => self.flush_video_front()?,
517+ (None, Some(_)) => self.flush_audio_front()?,
518+ (None, None) => break,
519+ }
520+ }
403 Ok(())521 Ok(())
404 }522 }
405 523
524+ /// One raw AAC packet (no ADTS header), copied verbatim from the source --
525+ /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
526+ /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
527+ ///
528+ /// Queues rather than writes straight through: a caller feeding packets
529+ /// while the picture is still running (the overlapped export path,
530+ /// [`crate::export::run`]) gets them woven into the file under the
531+ /// pictures still queued in [`hold`](Mp4Muxer::hold) instead of parked
532+ /// until the picture ends, which is the whole point of calling this
533+ /// before the picture loop is done rather than after.
534+ pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {
535+ if !self.has_audio {
536+ return Err("audio packet written to a video-only file".into());
537+ }
538+ self.audio_queue.push_back(bytes.to_vec());
539+ self.drain()
540+ }
541+
406 /// The soft subtitle tracks this file carries, written after the picture and542 /// The soft subtitle tracks this file carries, written after the picture and
407 /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one543 /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one
408 /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says544 /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says
@@ -432,6 +568,11 @@ impl Mp4Muxer {
432 if subs.is_empty() {568 if subs.is_empty() {
433 return Ok(());569 return Ok(());
434 }570 }
571+ // `self.frames` below counts only pictures already handed to the
572+ // writer, and the interleave above can still be holding some back:
573+ // drained first, or a text track written under a short hold would
574+ // end short of the picture that has not landed yet.
575+ self.drain_all()?;
435 // Where the picture ends, in the text track's own tick: the last sample576 // Where the picture ends, in the text track's own tick: the last sample
436 // runs out to it, so the track covers the film rather than stopping at577 // runs out to it, so the track covers the film rather than stopping at
437 // the last thing anybody says.578 // the last thing anybody says.
@@ -478,6 +619,10 @@ impl Mp4Muxer {
478 }619 }
479 620
480 pub fn finish(mut self) -> crate::Result<()> {621 pub fn finish(mut self) -> crate::Result<()> {
622+ // Whatever the hold and the audio queue still carry: nothing further
623+ // is coming for either to wait on, so this drains both fully rather
624+ // than leaving a video-only tail queued.
625+ self.drain_all()?;
481 self.writer.write_end()?;626 self.writer.write_end()?;
482 let Self {627 let Self {
483 writer,628 writer,
crates/engine/tests/export.rsmodified+211 -1
@@ -31,7 +31,7 @@ static PROXY_FILM: Mutex<()> = Mutex::new(());
31 31
32 use engine::export::ExportSettings;32 use engine::export::ExportSettings;
33 use engine::hw::HwEncoder;33 use engine::hw::HwEncoder;
34-use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};34+use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets};
35 use engine::project::{Lane, Source, Speed};35 use engine::project::{Lane, Source, Speed};
36 use engine::scale::FitPolicy;36 use engine::scale::FitPolicy;
37 use engine::scratch::Scratch;37 use engine::scratch::Scratch;
@@ -782,6 +782,216 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<
782 )782 )
783 }783 }
784 784
785+/// One throwaway IDR slice NAL -- not a real picture (nothing here decodes
786+/// it), just something `Mp4Muxer::write_video_au` accepts and ffprobe can
787+/// see as one packet on the video track.
788+fn fake_au(n: u8) -> Vec<u8> {
789+ vec![0, 0, 1, 0x65, n, n.wrapping_add(1), 0xA5]
790+}
791+
792+/// `Mp4Muxer` holds coded pictures back until the sound can be interleaved
793+/// under them ([`Mp4Muxer::hold`], mux.rs), so that a streaming reader sees
794+/// both tracks advancing together rather than the whole picture and only
795+/// then the whole track. This pins the boundary the muxer's own doc comment
796+/// on `hold` states in words: how tightly the two interleave depends on
797+/// *when* the mix lands relative to the picture, which on a real export is a
798+/// race against a mixer thread this test does not want to run. So it forces
799+/// the landing itself -- writing straight to `Mp4Muxer`, exactly the shape
800+/// `export::run`'s `feed_late_audio` uses it in (a burst of video, then the
801+/// whole mix handed over in one tight loop, then the rest of the picture) --
802+/// rather than the real threaded export.
803+#[test]
804+fn mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture() {
805+ let out = out_path("interleave");
806+ let (width, height, fps) = (64u32, 64u32, 30.0);
807+ let (sps, pps) = ([0x67, 0x42, 0x00, 0x1E], [0x68, 0xCE, 0x3C, 0x80]);
808+ let mut muxer = Mp4Muxer::create(
809+ &out,
810+ &VideoParams {
811+ width,
812+ height,
813+ frame_rate: fps,
814+ sps: &sps,
815+ pps: &pps,
816+ },
817+ None,
818+ )
819+ .expect("create");
820+
821+ // 15 frames (0.5 s) of a head start for the picture -- the file always
822+ // wrote this stretch video-only, mix or no mix, and this test is about
823+ // the file *after* it.
824+ for i in 0..15u8 {
825+ muxer.write_video_au(&fake_au(i)).expect("write video");
826+ }
827+ muxer
828+ .add_audio_track(&AudioParams {
829+ freq_index: 3, // mp4::SampleFreqIndex::Freq48000
830+ chan_conf: 2, // ChannelConfig::Stereo
831+ sample_rate: 48_000,
832+ opus_pre_skip: None,
833+ })
834+ .expect("declare audio");
835+ // The whole mix, handed over in one tight loop exactly as
836+ // `export::feed_late_audio` does: 200 packets of 1024/48000 s each is
837+ // ~4.27 s, well past the picture's 0.5 s head start, so releasing it
838+ // correctly needs the *rest* of the picture below to pace it out.
839+ let silence = [0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c];
840+ for _ in 0..200u32 {
841+ muxer.write_audio_packet(&silence).expect("write audio");
842+ }
843+ // The rest of the picture: 135 more frames, 4.5 s, what the mix above is
844+ // paced against.
845+ for i in 15..150u8 {
846+ muxer.write_video_au(&fake_au(i)).expect("write video");
847+ }
848+ muxer.write_subtitles(&[]).expect("no subtitles");
849+ muxer.finish().expect("finish");
850+
851+ assert_no_single_stream_span_over(&out, 2.0);
852+ std::fs::remove_file(&out).unwrap();
853+}
854+
855+/// Reads `path`'s packets back with ffprobe (pts + byte position) and fails
856+/// if any run of file-order-consecutive same-stream packets spans more media
857+/// time than `seconds` -- the numeric shape of "no byte-span longer than 2 s
858+/// of media contains packets from only one stream".
859+fn assert_no_single_stream_span_over(path: &Path, seconds: f64) {
860+ let output = std::process::Command::new("ffprobe")
861+ .args([
862+ "-v",
863+ "error",
864+ "-show_entries",
865+ "packet=stream_index,pts_time,pos",
866+ "-of",
867+ "csv=p=0",
868+ ])
869+ .arg(path)
870+ .output()
871+ .expect("run ffprobe");
872+ assert!(
873+ output.status.success(),
874+ "ffprobe failed: {}",
875+ String::from_utf8_lossy(&output.stderr)
876+ );
877+ let text = String::from_utf8_lossy(&output.stdout);
878+ let mut packets: Vec<(i64, u32, f64)> = text
879+ .lines()
880+ .filter(|line| !line.is_empty())
881+ .map(|line| {
882+ let mut fields = line.split(',');
883+ let stream: u32 = fields.next().unwrap().parse().unwrap();
884+ let pts: f64 = fields.next().unwrap().parse().unwrap();
885+ let pos: i64 = fields.next().unwrap().parse().unwrap();
886+ (pos, stream, pts)
887+ })
888+ .collect();
889+ assert!(packets.len() > 10, "ffprobe saw only {} packets", packets.len());
890+ packets.sort_by_key(|&(pos, ..)| pos);
891+
892+ let streams: std::collections::HashSet<u32> = packets.iter().map(|&(_, s, _)| s).collect();
893+ assert_eq!(
894+ streams.len(),
895+ 2,
896+ "expected one video and one audio stream, ffprobe saw {streams:?}"
897+ );
898+
899+ let (mut run_stream, mut run_start) = (packets[0].1, packets[0].2);
900+ for &(_, stream, pts) in &packets[1..] {
901+ if stream != run_stream {
902+ run_stream = stream;
903+ run_start = pts;
904+ continue;
905+ }
906+ let span = pts - run_start;
907+ assert!(
908+ span <= seconds,
909+ "a run of stream {run_stream} packets alone spans {span:.2} s (from {run_start:.2} s) -- over the {seconds} s bound"
910+ );
911+ }
912+}
913+
914+/// The first `pts_time` ffprobe reports for stream kind `select` ("v" or
915+/// "a") in `path` -- just enough of [`assert_no_single_stream_span_over`]'s
916+/// ffprobe call, restricted to one stream, to check A/V sync independently of
917+/// the interleave order.
918+fn first_pts(path: &Path, select: &str) -> f64 {
919+ let output = std::process::Command::new("ffprobe")
920+ .args([
921+ "-v",
922+ "error",
923+ "-select_streams",
924+ select,
925+ "-show_entries",
926+ "packet=pts_time",
927+ "-of",
928+ "csv=p=0",
929+ ])
930+ .arg(path)
931+ .output()
932+ .expect("run ffprobe");
933+ assert!(
934+ output.status.success(),
935+ "ffprobe failed: {}",
936+ String::from_utf8_lossy(&output.stderr)
937+ );
938+ String::from_utf8_lossy(&output.stdout)
939+ .lines()
940+ .find(|line| !line.is_empty())
941+ .expect("stream has at least one packet")
942+ .parse()
943+ .expect("pts_time")
944+}
945+
946+/// An mp4 export used to write every video sample and only then the whole
947+/// audio track: byte-correct, and silent for as long as the picture took on
948+/// any player that reads the file as it streams in rather than seeking to the
949+/// end first. This proves the interleave holds on the real, threaded export
950+/// path end to end -- `mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture`
951+/// above pins the same boundary by writing straight to `Mp4Muxer`, forcing the
952+/// mix to land early rather than racing the mixer thread for it.
953+#[test]
954+fn mp4_audio_interleaves_with_the_picture() {
955+ let _seat = pin_software();
956+ let source = asset("test_av.mp4");
957+ let mut session = PlaybackSession::open(&source).expect("open source");
958+ // A cut, so the audio copy runs as two segments and the join is real --
959+ // the same edit `exports_audio_alongside_the_video` makes, reused here so
960+ // the interleave is proven on a timeline that was actually cut, not a
961+ // straight passthrough.
962+ assert!(session.cut_at(2.0));
963+ session.pause();
964+ let timeline = session.timeline_duration();
965+ let out = out_path("interleave-e2e");
966+
967+ let handle = session.export_to(&out);
968+ wait(&handle, Duration::from_secs(600)).expect("export");
969+
970+ // A/V sync: the first audio sample starts at movie time zero either way --
971+ // interleaving moves *where in the file* a packet sits, never what `stts`
972+ // says it plays at.
973+ assert_eq!(first_pts(&out, "a"), 0.0, "first audio pts is media time zero");
974+
975+ assert_no_single_stream_span_over(&out, 2.0);
976+
977+ // Nothing else about the file moved: same duration, same sample counts,
978+ // to within the packet the two sibling tests above already allow.
979+ let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap();
980+ assert_eq!(video_meta.frame_count, 150, "video track unaffected by interleaving");
981+ let (audio_meta, chunks) = engine::AudioSession::open(&out)
982+ .unwrap()
983+ .expect("export has an audio track");
984+ assert_eq!((audio_meta.sample_rate, audio_meta.channels), (44_100, 2));
985+ let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum();
986+ let wanted = timeline * f64::from(audio_meta.sample_rate);
987+ assert!(
988+ (decoded as f64 / f64::from(audio_meta.channels) - wanted).abs() < 3.0 * 1024.0,
989+ "audio length {decoded} drifted from {wanted} samples of timeline"
990+ );
991+
992+ std::fs::remove_file(&out).unwrap();
993+}
994+
785 /// A timeline whose *first* second of sound was lifted. A reader drops the995 /// A timeline whose *first* second of sound was lifted. A reader drops the
786 /// first packet of an AAC track as encoder priming, so a track that opens on a996 /// first packet of an AAC track as encoder priming, so a track that opens on a
787 /// hole has to carry one extra packet of silence for it to drop -- without it997 /// hole has to carry one extra packet of silence for it to drop -- without it