forge
Explore
Log in

Don't you dare go Hollow

Interleave the overlapped mp4 audio pass under the picture

Browse files at this commit

4ba4015e224e6e93a71753b8a2e67ff8ebee17d7Ahmet Kaan GümüşParent: 9e3e5bc
  • feat
    • interleave the overlapped mp4 audio pass under the picture
Show full message
✨ feat(engine): interleave the overlapped mp4 audio pass under the picture

Mp4Muxer holds ~2s of pictures and releases them merged by pts against
landed sound instead of writing whole-picture-then-whole-track;
feed_late_audio hands the mix over the moment it lands.
crates/engine/src/export.rsmodified+46 -3
@@ -2334,6 +2334,33 @@ fn publish_seats(
23342334 *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}"));
23352335 }
23362336
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+
23372364 fn params_of(track: &ExportAudio) -> AudioParams {
23382365 AudioParams {
23392366 freq_index: track.params.freq_index,
@@ -2554,10 +2581,16 @@ fn run(
25542581 // the sound landed -- the one number that says whether the two passes
25552582 // really overlapped, in the same voice as `encode_audio`'s own timers.
25562583 let picture_started = std::time::Instant::now();
2557- // The sound, once the pass beside this one has finished with it: an mp4
2558- // declares its audio track and writes its packets after the picture, so
2559- // this is where they arrive.
2584+ // The sound, once the pass beside this one has finished with it: joined
2585+ // here the moment it lands rather than only after the picture, so
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`]).
25602589 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;
25612594 let mut muxer = None;
25622595 let mut done = 0u32;
25632596 let black = Black::new(meta);
@@ -2718,6 +2751,7 @@ fn run(
27182751 "export audio: done {:.1} s into the picture",
27192752 picture_started.elapsed().as_secs_f64()
27202753 );
2754+ feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
27212755 }
27222756 let want = source_at(done_here);
27232757 // How many timeline frames from here show that same picture: one at
@@ -2826,6 +2860,11 @@ fn run(
28262860 au,
28272861 key,
28282862 )?;
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)?;
28292868 }
28302869 done += 1;
28312870 // Forwards only: an audio pass still running beside this one
@@ -2898,6 +2937,10 @@ fn run(
28982937 );
28992938 track
29002939 }
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,
29012944 None => late,
29022945 };
29032946 if let Some(track) = &track {
crates/engine/src/mux.rsmodified+169 -24
@@ -15,6 +15,7 @@
1515 //! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`])
1616 //! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were.
1717
18+use std::collections::VecDeque;
1819 use std::fs::{File, OpenOptions};
1920 use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
2021 use std::path::{Path, PathBuf};
@@ -41,6 +42,13 @@ const AAC_PACKET_SAMPLES: u32 = 1024;
4142 /// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on
4243 /// the same instant whichever of the two containers carries it.
4344 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;
4452
4553 const NAL_IDR: u8 = 5;
4654 const NAL_SEI: u8 = 6;
@@ -105,6 +113,41 @@ pub struct Mp4Muxer {
105113 /// beside the sample entry. Empty where no track carries a title, which is
106114 /// every file that has no subtitles at all.
107115 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,
108151 }
109152
110153 /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag
@@ -278,6 +321,12 @@ impl Mp4Muxer {
278321 timescale,
279322 frames: 0,
280323 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,
281330 };
282331 if let Some(audio) = audio {
283332 muxer.add_audio_track(audio)?;
@@ -326,6 +375,7 @@ impl Mp4Muxer {
326375 }),
327376 })?;
328377 self.has_audio = true;
378+ self.audio_rate = sample_rate;
329379 Ok(())
330380 }
331381
@@ -343,18 +393,7 @@ impl Mp4Muxer {
343393 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.
344394 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {
345395 let (bytes, is_sync) = annex_b_to_avcc(annex_b)?;
346- self.writer.write_sample(
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(())
396+ self.queue_video(bytes, is_sync)
358397 }
359398
360399 /// One coded picture already framed the way its sample carries it: an AV1
@@ -367,27 +406,82 @@ impl Mp4Muxer {
367406 if obus.is_empty() {
368407 return Err("an empty coded picture".into());
369408 }
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);
370466 self.writer.write_sample(
371467 VIDEO_TRACK,
372468 &Mp4Sample {
373- start_time: 0,
469+ start_time: 0, // ignored by the writer; timing is duration-accumulated
374470 duration: self.frame_duration,
375- rendering_offset: 0,
376- is_sync: key,
377- bytes: Bytes::copy_from_slice(obus),
471+ rendering_offset: 0, // no B-frames on either encode path
472+ is_sync,
473+ bytes: Bytes::from(bytes),
378474 },
379475 )?;
380476 self.frames += 1;
477+ self.flushed_video_ticks += u64::from(self.frame_duration);
381478 Ok(())
382479 }
383480
384- /// One raw AAC packet (no ADTS header), copied verbatim from the source --
385- /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
386- /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
387- pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {
388- if !self.has_audio {
389- return Err("audio packet written to a video-only file".into());
390- }
481+ fn flush_audio_front(&mut self) -> crate::Result<()> {
482+ let Some(bytes) = self.audio_queue.pop_front() else {
483+ return Ok(());
484+ };
391485 self.writer.write_sample(
392486 AUDIO_TRACK,
393487 &Mp4Sample {
@@ -397,12 +491,54 @@ impl Mp4Muxer {
397491 // Every AAC packet is a sync point; saying so per-sample would emit
398492 // an `stss` listing all of them, while no `stss` means the same thing.
399493 is_sync: false,
400- bytes: Bytes::copy_from_slice(bytes),
494+ bytes: Bytes::from(bytes),
401495 },
402496 )?;
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+ }
403521 Ok(())
404522 }
405523
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+
406542 /// The soft subtitle tracks this file carries, written after the picture and
407543 /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one
408544 /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says
@@ -432,6 +568,11 @@ impl Mp4Muxer {
432568 if subs.is_empty() {
433569 return Ok(());
434570 }
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()?;
435576 // Where the picture ends, in the text track's own tick: the last sample
436577 // runs out to it, so the track covers the film rather than stopping at
437578 // the last thing anybody says.
@@ -478,6 +619,10 @@ impl Mp4Muxer {
478619 }
479620
480621 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()?;
481626 self.writer.write_end()?;
482627 let Self {
483628 writer,
crates/engine/tests/export.rsmodified+130 -1
@@ -31,7 +31,7 @@ static PROXY_FILM: Mutex<()> = Mutex::new(());
3131
3232 use engine::export::ExportSettings;
3333 use engine::hw::HwEncoder;
34-use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
34+use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets};
3535 use engine::project::{Lane, Source, Speed};
3636 use engine::scale::FitPolicy;
3737 use engine::scratch::Scratch;
@@ -782,6 +782,135 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<
782782 )
783783 }
784784
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+
785914 /// A timeline whose *first* second of sound was lifted. A reader drops the
786915 /// first packet of an AAC track as encoder priming, so a track that opens on a
787916 /// hole has to carry one extra packet of silence for it to drop -- without it