diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 56fae47..5bbe1b6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -2334,6 +2334,33 @@ fn publish_seats( *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}")); } +/// Hands a mix that finished mixing early to the mp4 it belongs in, the +/// moment both exist: `late` may land before the first coded picture has +/// opened `muxer` at all, so this is tried both right where the mix lands +/// and after every picture written afterwards, and does nothing once +/// `*fed` says an earlier try already succeeded. Declaring the track and +/// queuing its packets here is what lets [`crate::mux::Mp4Muxer`]'s own +/// hold interleave them under the pictures still to come, rather than the +/// track landing all at once after the picture is done. +fn feed_late_audio( + muxer: &mut Option, + late: &Option, + fed: &mut bool, +) -> crate::Result<()> { + if *fed { + return Ok(()); + } + let (Some(track), Some(Muxer::Mp4(mp4))) = (late.as_ref(), muxer.as_mut()) else { + return Ok(()); + }; + mp4.add_audio_track(¶ms_of(track))?; + for packet in &track.packets { + mp4.write_audio_packet(&packet.bytes)?; + } + *fed = true; + Ok(()) +} + fn params_of(track: &ExportAudio) -> AudioParams { AudioParams { freq_index: track.params.freq_index, @@ -2554,10 +2581,16 @@ fn run( // the sound landed -- the one number that says whether the two passes // really overlapped, in the same voice as `encode_audio`'s own timers. let picture_started = std::time::Instant::now(); - // The sound, once the pass beside this one has finished with it: an mp4 - // declares its audio track and writes its packets after the picture, so - // this is where they arrive. + // The sound, once the pass beside this one has finished with it: joined + // here the moment it lands rather than only after the picture, so + // `feed_late_audio` below can hand it to the muxer while pictures are + // still being coded and let `Mp4Muxer`'s own hold interleave the two + // ([`crate::mux::Mp4Muxer`]). let mut late: Option = None; + // Set once `late`'s track has been handed to the muxer -- so the final + // join below, which still exists for a mix that never lands mid-picture, + // knows not to declare the track or write its packets a second time. + let mut audio_fed = false; let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); @@ -2718,6 +2751,7 @@ fn run( "export audio: done {:.1} s into the picture", picture_started.elapsed().as_secs_f64() ); + feed_late_audio(&mut muxer, &late, &mut audio_fed)?; } let want = source_at(done_here); // How many timeline frames from here show that same picture: one at @@ -2826,6 +2860,11 @@ fn run( au, key, )?; + // Retried here rather than only where the mix lands: the + // very first coded picture is what creates `muxer`, and a + // mix that lands before it (a short film, or a slow first + // frame) has nothing to hand it to until now. + feed_late_audio(&mut muxer, &late, &mut audio_fed)?; } done += 1; // Forwards only: an audio pass still running beside this one @@ -2898,6 +2937,10 @@ fn run( ); track } + // `late` was already handed to `mp4` inside the picture loop + // ([`feed_late_audio`]) unless the mix never landed there, in + // which case it is still `None` and there was nothing to feed. + None if audio_fed => None, None => late, }; if let Some(track) = &track { diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 7faaa4a..828da74 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -15,6 +15,7 @@ //! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`]) //! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were. +use std::collections::VecDeque; use std::fs::{File, OpenOptions}; use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; @@ -41,6 +42,13 @@ const AAC_PACKET_SAMPLES: u32 = 1024; /// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on /// the same instant whichever of the two containers carries it. const SUB_TIMESCALE: u32 = 1_000; +/// How much coded picture [`Mp4Muxer`] holds unwritten waiting for the sound +/// to catch up ([`Mp4Muxer::hold`]) before it gives up and flushes video-only. +/// Two seconds is the ceiling `export`'s own progress granularity already +/// tolerates (`AUDIO_BAND`), and it bounds the hold's memory to two seconds +/// of coded pictures -- kilobytes, not the tens of megabytes a whole film's +/// worth would be. +const HOLD_SECONDS: u64 = 2; const NAL_IDR: u8 = 5; const NAL_SEI: u8 = 6; @@ -105,6 +113,41 @@ pub struct Mp4Muxer { /// beside the sample entry. Empty where no track carries a title, which is /// every file that has no subtitles at all. sub_names: Vec, + /// Coded pictures not yet handed to the writer, oldest first -- how the + /// overlapped audio pass gets to land *under* the picture instead of + /// after all of it: every `write_video_au`/`write_coded_sample` queues + /// here and [`drain`](Mp4Muxer::drain) interleaves it against + /// [`audio_queue`](Mp4Muxer::audio_queue) by presentation time, so the + /// two tracks' bytes end up beside each other in `mdat` rather than one + /// whole track then the other. `(bytes, is_sync)`. + /// + /// NONDETERMINISM: how tightly the two interleave depends on when the + /// mix thread's join lands relative to the picture loop -- a mix that + /// finishes before this hold fills stays byte-interleaved from the + /// start; a mix that lands late only interleaves the tail. A test on + /// this has to pin that landing (force the join before frame N in a + /// fixture) rather than race the real mixer thread. + hold: VecDeque<(Vec, bool)>, + /// `hold`'s span, in the video track's own ticks -- flushed video-only + /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands + /// very late) cannot stall the encode behind an unbounded queue. + hold_ticks: u64, + /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet) + /// before `drain` has caught up to them -- normally empty the instant + /// after that call returns; only grows past one packet where the whole + /// track lands in one call while the hold is still short (a picture that + /// finished before its own sound). + audio_queue: VecDeque>, + /// Ticks, in the audio track's own rate, already written to the file -- + /// `drain`'s clock for comparing against `flushed_video_ticks`. + audio_ticks: u64, + /// Ticks, in the video track's own timescale, already written to the + /// file (as opposed to merely queued in `hold`). + flushed_video_ticks: u64, + /// The audio track's sample rate, once [`add_audio_track`](Mp4Muxer::add_audio_track) + /// has declared one -- `drain`'s clock for `audio_ticks`. 0 until then, + /// which is also exactly when `audio_queue` can have nothing in it. + audio_rate: u32, } /// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag @@ -278,6 +321,12 @@ impl Mp4Muxer { timescale, frames: 0, sub_names: Vec::new(), + hold: VecDeque::new(), + hold_ticks: 0, + audio_queue: VecDeque::new(), + audio_ticks: 0, + flushed_video_ticks: 0, + audio_rate: 0, }; if let Some(audio) = audio { muxer.add_audio_track(audio)?; @@ -326,6 +375,7 @@ impl Mp4Muxer { }), })?; self.has_audio = true; + self.audio_rate = sample_rate; Ok(()) } @@ -343,18 +393,7 @@ impl Mp4Muxer { /// (they are already in `avcC`); an IDR slice marks the sample as a sync point. pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> { let (bytes, is_sync) = annex_b_to_avcc(annex_b)?; - self.writer.write_sample( - VIDEO_TRACK, - &Mp4Sample { - start_time: 0, // ignored by the writer; timing is duration-accumulated - duration: self.frame_duration, - rendering_offset: 0, // no B-frames on either encode path - is_sync, - bytes: Bytes::from(bytes), - }, - )?; - self.frames += 1; - Ok(()) + self.queue_video(bytes, is_sync) } /// One coded picture already framed the way its sample carries it: an AV1 @@ -367,27 +406,82 @@ impl Mp4Muxer { if obus.is_empty() { return Err("an empty coded picture".into()); } + self.queue_video(obus.to_vec(), key) + } + + /// Queues one coded picture and tries to advance the interleave -- + /// shared by [`write_video_au`](Mp4Muxer::write_video_au) and + /// [`write_coded_sample`](Mp4Muxer::write_coded_sample), which differ + /// only in how the bytes were framed before they got here. + fn queue_video(&mut self, bytes: Vec, is_sync: bool) -> crate::Result<()> { + self.hold.push_back((bytes, is_sync)); + self.hold_ticks += u64::from(self.frame_duration); + self.drain() + } + + /// Advances the interleave as far as it currently can, called after + /// every single sample either track hands over: for as long as both + /// queues have something in them, writes whichever track's next sample + /// has the earlier presentation time -- which is what makes the release + /// of a mix that landed all at once ([`write_audio_packet`](Mp4Muxer::write_audio_packet) + /// fed in one tight loop) paced by how much *video* keeps arriving to + /// match it against, rather than dumped in one uninterrupted run the + /// moment it lands. + /// + /// Video queued with nothing to interleave against yet -- no audio + /// track, or one declared but not fed this far ahead -- is left held, + /// unless the hold has grown past [`HOLD_SECONDS`], which gives up + /// waiting and writes video-only to relieve it (a mix that never lands, + /// or one running well behind the picture). Audio queued with no video + /// to interleave against is always left held: nothing bounds how far + /// *behind* the sound the picture may run, but every path that can end + /// the file ([`finish`](Mp4Muxer::finish), [`write_subtitles`](Mp4Muxer::write_subtitles)) + /// drains it in full first. + fn drain(&mut self) -> crate::Result<()> { + loop { + match (self.hold.front(), self.audio_queue.front()) { + (Some(_), Some(_)) => { + let video_pts = self.flushed_video_ticks as f64 / f64::from(self.timescale); + let audio_pts = self.audio_ticks as f64 / f64::from(self.audio_rate); + if audio_pts <= video_pts { + self.flush_audio_front()?; + } else { + self.flush_video_front()?; + } + } + (Some(_), None) if self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) => { + self.flush_video_front()?; + } + (Some(_), None) | (None, Some(_)) | (None, None) => break, + } + } + Ok(()) + } + + fn flush_video_front(&mut self) -> crate::Result<()> { + let Some((bytes, is_sync)) = self.hold.pop_front() else { + return Ok(()); + }; + self.hold_ticks -= u64::from(self.frame_duration); self.writer.write_sample( VIDEO_TRACK, &Mp4Sample { - start_time: 0, + start_time: 0, // ignored by the writer; timing is duration-accumulated duration: self.frame_duration, - rendering_offset: 0, - is_sync: key, - bytes: Bytes::copy_from_slice(obus), + rendering_offset: 0, // no B-frames on either encode path + is_sync, + bytes: Bytes::from(bytes), }, )?; self.frames += 1; + self.flushed_video_ticks += u64::from(self.frame_duration); Ok(()) } - /// One raw AAC packet (no ADTS header), copied verbatim from the source -- - /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC - /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. - pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> { - if !self.has_audio { - return Err("audio packet written to a video-only file".into()); - } + fn flush_audio_front(&mut self) -> crate::Result<()> { + let Some(bytes) = self.audio_queue.pop_front() else { + return Ok(()); + }; self.writer.write_sample( AUDIO_TRACK, &Mp4Sample { @@ -397,12 +491,54 @@ impl Mp4Muxer { // Every AAC packet is a sync point; saying so per-sample would emit // an `stss` listing all of them, while no `stss` means the same thing. is_sync: false, - bytes: Bytes::copy_from_slice(bytes), + bytes: Bytes::from(bytes), }, )?; + self.audio_ticks += u64::from(AAC_PACKET_SAMPLES); + Ok(()) + } + + /// Everything either queue has left, in presentation order regardless of + /// the hold cap -- called from [`finish`](Mp4Muxer::finish), where there + /// is no more picture coming for a short hold to wait on. + fn drain_all(&mut self) -> crate::Result<()> { + loop { + match (self.hold.front(), self.audio_queue.front()) { + (Some(_), Some(_)) => { + let video_pts = self.flushed_video_ticks as f64 / f64::from(self.timescale); + let audio_pts = self.audio_ticks as f64 / f64::from(self.audio_rate); + if audio_pts <= video_pts { + self.flush_audio_front()?; + } else { + self.flush_video_front()?; + } + } + (Some(_), None) => self.flush_video_front()?, + (None, Some(_)) => self.flush_audio_front()?, + (None, None) => break, + } + } Ok(()) } + /// One raw AAC packet (no ADTS header), copied verbatim from the source -- + /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC + /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. + /// + /// Queues rather than writes straight through: a caller feeding packets + /// while the picture is still running (the overlapped export path, + /// [`crate::export::run`]) gets them woven into the file under the + /// pictures still queued in [`hold`](Mp4Muxer::hold) instead of parked + /// until the picture ends, which is the whole point of calling this + /// before the picture loop is done rather than after. + pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> { + if !self.has_audio { + return Err("audio packet written to a video-only file".into()); + } + self.audio_queue.push_back(bytes.to_vec()); + self.drain() + } + /// The soft subtitle tracks this file carries, written after the picture and /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says @@ -432,6 +568,11 @@ impl Mp4Muxer { if subs.is_empty() { return Ok(()); } + // `self.frames` below counts only pictures already handed to the + // writer, and the interleave above can still be holding some back: + // drained first, or a text track written under a short hold would + // end short of the picture that has not landed yet. + self.drain_all()?; // Where the picture ends, in the text track's own tick: the last sample // runs out to it, so the track covers the film rather than stopping at // the last thing anybody says. @@ -478,6 +619,10 @@ impl Mp4Muxer { } pub fn finish(mut self) -> crate::Result<()> { + // Whatever the hold and the audio queue still carry: nothing further + // is coming for either to wait on, so this drains both fully rather + // than leaving a video-only tail queued. + self.drain_all()?; self.writer.write_end()?; let Self { writer, diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index d3c8071..f69e844 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -31,7 +31,7 @@ static PROXY_FILM: Mutex<()> = Mutex::new(()); use engine::export::ExportSettings; use engine::hw::HwEncoder; -use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; +use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets}; use engine::project::{Lane, Source, Speed}; use engine::scale::FitPolicy; use engine::scratch::Scratch; @@ -782,6 +782,216 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec< ) } +/// One throwaway IDR slice NAL -- not a real picture (nothing here decodes +/// it), just something `Mp4Muxer::write_video_au` accepts and ffprobe can +/// see as one packet on the video track. +fn fake_au(n: u8) -> Vec { + vec![0, 0, 1, 0x65, n, n.wrapping_add(1), 0xA5] +} + +/// `Mp4Muxer` holds coded pictures back until the sound can be interleaved +/// under them ([`Mp4Muxer::hold`], mux.rs), so that a streaming reader sees +/// both tracks advancing together rather than the whole picture and only +/// then the whole track. This pins the boundary the muxer's own doc comment +/// on `hold` states in words: how tightly the two interleave depends on +/// *when* the mix lands relative to the picture, which on a real export is a +/// race against a mixer thread this test does not want to run. So it forces +/// the landing itself -- writing straight to `Mp4Muxer`, exactly the shape +/// `export::run`'s `feed_late_audio` uses it in (a burst of video, then the +/// whole mix handed over in one tight loop, then the rest of the picture) -- +/// rather than the real threaded export. +#[test] +fn mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture() { + let out = out_path("interleave"); + let (width, height, fps) = (64u32, 64u32, 30.0); + let (sps, pps) = ([0x67, 0x42, 0x00, 0x1E], [0x68, 0xCE, 0x3C, 0x80]); + let mut muxer = Mp4Muxer::create( + &out, + &VideoParams { + width, + height, + frame_rate: fps, + sps: &sps, + pps: &pps, + }, + None, + ) + .expect("create"); + + // 15 frames (0.5 s) of a head start for the picture -- the file always + // wrote this stretch video-only, mix or no mix, and this test is about + // the file *after* it. + for i in 0..15u8 { + muxer.write_video_au(&fake_au(i)).expect("write video"); + } + muxer + .add_audio_track(&AudioParams { + freq_index: 3, // mp4::SampleFreqIndex::Freq48000 + chan_conf: 2, // ChannelConfig::Stereo + sample_rate: 48_000, + opus_pre_skip: None, + }) + .expect("declare audio"); + // The whole mix, handed over in one tight loop exactly as + // `export::feed_late_audio` does: 200 packets of 1024/48000 s each is + // ~4.27 s, well past the picture's 0.5 s head start, so releasing it + // correctly needs the *rest* of the picture below to pace it out. + let silence = [0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c]; + for _ in 0..200u32 { + muxer.write_audio_packet(&silence).expect("write audio"); + } + // The rest of the picture: 135 more frames, 4.5 s, what the mix above is + // paced against. + for i in 15..150u8 { + muxer.write_video_au(&fake_au(i)).expect("write video"); + } + muxer.write_subtitles(&[]).expect("no subtitles"); + muxer.finish().expect("finish"); + + assert_no_single_stream_span_over(&out, 2.0); + std::fs::remove_file(&out).unwrap(); +} + +/// Reads `path`'s packets back with ffprobe (pts + byte position) and fails +/// if any run of file-order-consecutive same-stream packets spans more media +/// time than `seconds` -- the numeric shape of "no byte-span longer than 2 s +/// of media contains packets from only one stream". +fn assert_no_single_stream_span_over(path: &Path, seconds: f64) { + let output = std::process::Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "packet=stream_index,pts_time,pos", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("run ffprobe"); + assert!( + output.status.success(), + "ffprobe failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8_lossy(&output.stdout); + let mut packets: Vec<(i64, u32, f64)> = text + .lines() + .filter(|line| !line.is_empty()) + .map(|line| { + let mut fields = line.split(','); + let stream: u32 = fields.next().unwrap().parse().unwrap(); + let pts: f64 = fields.next().unwrap().parse().unwrap(); + let pos: i64 = fields.next().unwrap().parse().unwrap(); + (pos, stream, pts) + }) + .collect(); + assert!(packets.len() > 10, "ffprobe saw only {} packets", packets.len()); + packets.sort_by_key(|&(pos, ..)| pos); + + let streams: std::collections::HashSet = packets.iter().map(|&(_, s, _)| s).collect(); + assert_eq!( + streams.len(), + 2, + "expected one video and one audio stream, ffprobe saw {streams:?}" + ); + + let (mut run_stream, mut run_start) = (packets[0].1, packets[0].2); + for &(_, stream, pts) in &packets[1..] { + if stream != run_stream { + run_stream = stream; + run_start = pts; + continue; + } + let span = pts - run_start; + assert!( + span <= seconds, + "a run of stream {run_stream} packets alone spans {span:.2} s (from {run_start:.2} s) -- over the {seconds} s bound" + ); + } +} + +/// The first `pts_time` ffprobe reports for stream kind `select` ("v" or +/// "a") in `path` -- just enough of [`assert_no_single_stream_span_over`]'s +/// ffprobe call, restricted to one stream, to check A/V sync independently of +/// the interleave order. +fn first_pts(path: &Path, select: &str) -> f64 { + let output = std::process::Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + select, + "-show_entries", + "packet=pts_time", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("run ffprobe"); + assert!( + output.status.success(), + "ffprobe failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout) + .lines() + .find(|line| !line.is_empty()) + .expect("stream has at least one packet") + .parse() + .expect("pts_time") +} + +/// An mp4 export used to write every video sample and only then the whole +/// audio track: byte-correct, and silent for as long as the picture took on +/// any player that reads the file as it streams in rather than seeking to the +/// end first. This proves the interleave holds on the real, threaded export +/// path end to end -- `mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture` +/// above pins the same boundary by writing straight to `Mp4Muxer`, forcing the +/// mix to land early rather than racing the mixer thread for it. +#[test] +fn mp4_audio_interleaves_with_the_picture() { + let _seat = pin_software(); + let source = asset("test_av.mp4"); + let mut session = PlaybackSession::open(&source).expect("open source"); + // A cut, so the audio copy runs as two segments and the join is real -- + // the same edit `exports_audio_alongside_the_video` makes, reused here so + // the interleave is proven on a timeline that was actually cut, not a + // straight passthrough. + assert!(session.cut_at(2.0)); + session.pause(); + let timeline = session.timeline_duration(); + let out = out_path("interleave-e2e"); + + let handle = session.export_to(&out); + wait(&handle, Duration::from_secs(600)).expect("export"); + + // A/V sync: the first audio sample starts at movie time zero either way -- + // interleaving moves *where in the file* a packet sits, never what `stts` + // says it plays at. + assert_eq!(first_pts(&out, "a"), 0.0, "first audio pts is media time zero"); + + assert_no_single_stream_span_over(&out, 2.0); + + // Nothing else about the file moved: same duration, same sample counts, + // to within the packet the two sibling tests above already allow. + let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap(); + assert_eq!(video_meta.frame_count, 150, "video track unaffected by interleaving"); + let (audio_meta, chunks) = engine::AudioSession::open(&out) + .unwrap() + .expect("export has an audio track"); + assert_eq!((audio_meta.sample_rate, audio_meta.channels), (44_100, 2)); + let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); + let wanted = timeline * f64::from(audio_meta.sample_rate); + assert!( + (decoded as f64 / f64::from(audio_meta.channels) - wanted).abs() < 3.0 * 1024.0, + "audio length {decoded} drifted from {wanted} samples of timeline" + ); + + std::fs::remove_file(&out).unwrap(); +} + /// A timeline whose *first* second of sound was lifted. A reader drops the /// first packet of an AAC track as encoder priming, so a track that opens on a /// hole has to carry one extra packet of silence for it to drop -- without it