diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a8e767b..ed540af 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -679,6 +679,9 @@ impl Player { match PlaybackSession::open(path) { Ok(session) => { self.fps = session.meta().frame_rate; + // Read before the session moves: a file that plays silent says + // so here or nowhere. + let silent = audio_notice(&session); self.session = Some(session); // A fresh session comes up at full volume; the player's own // setting outlives the file, so it is pushed at every new one. @@ -687,7 +690,7 @@ impl Player { self.project_path = project_path(path); self.name = file_name(path).into(); self.reset_after_reseek(); - format!("OPENED {}", file_name(path)) + format!("OPENED {}{}", file_name(path), silent.unwrap_or_default()) } Err(e) => format!("OPEN FAILED: {e}"), } @@ -733,6 +736,7 @@ impl Player { let text = match PlaybackSession::open_project(path) { Ok(session) => { self.fps = session.meta().frame_rate; + let silent = audio_notice(&session); // A project is named after itself but still exports beside its // media: that is the only place an export has ever landed. self.export_path = export_path(&session.sources()[0]); @@ -760,7 +764,7 @@ impl Player { // reaches the screen the way a seek's does. The old picture is // released by the swap in `pump`, as after any other seek. self.reset_after_reseek(); - format!("LOADED {}", file_name(path)) + format!("LOADED {}{}", file_name(path), silent.unwrap_or_default()) } Err(e) => format!("OPEN FAILED: {e}"), }; @@ -2465,6 +2469,15 @@ fn file_name(path: &std::path::Path) -> String { ) } +/// The tail an open/load notice grows when the file has sound the engine cannot +/// decode: it plays perfectly, in silence, and that is the one thing the window +/// would otherwise never say (the engine's own word for it, verbatim). +fn audio_notice(session: &PlaybackSession) -> Option { + session + .audio_disabled_reason() + .map(|reason| format!(" — NO AUDIO: {reason}")) +} + /// The sources a repaint has not asked about yet. A key that is already there /// means "asked", whatever state it is in, which is what stops a decode already /// running from being started again by the next of sixty repaints a second. @@ -3792,6 +3805,13 @@ fn main() { notice.get_or_insert(text); } } + // A file that plays silent is as much news at launch as it is on a drop, and + // behind the keymap notice for the same reason an import refusal is. + if let Some(reason) = session.as_ref().and_then(PlaybackSession::audio_disabled_reason) { + let text = format!("NO AUDIO: {reason}"); + eprintln!("{text}"); + notice.get_or_insert(text); + } let meta = session.as_ref().map(|session| *session.meta()); // Beside the media even for a project: an export has never landed anywhere // but next to the picture it came from. diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index c14e04e..8e5079d 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -179,8 +179,12 @@ impl Session { /// or before it and the pictures in between are dropped unread. fn open_at(path: &Path, target_sample: u32) -> Option { let mut session = Self::open(path)?; - let sync = session.demuxer.seek_to_sync_at_or_before(target_sample); - session.skip = target_sample.saturating_sub(sync); + // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based + // display frames -- and answers with a signed one, since a sync sample + // inside what the edit list trims sits before frame 0. + let target_frame = target_sample.saturating_sub(1); + let first = session.demuxer.seek_to_sync_at_or_before(target_frame); + session.skip = (i64::from(target_frame) - first).max(0) as u32; Some(session) } diff --git a/crates/engine/examples/probe_fps.rs b/crates/engine/examples/probe_fps.rs new file mode 100644 index 0000000..defc078 --- /dev/null +++ b/crates/engine/examples/probe_fps.rs @@ -0,0 +1,129 @@ +//! What the demuxer reads a file's frame rate as, and what that means for the +//! frame the master clock asks for ten minutes in -- the arithmetic behind A/V +//! desync on NTSC-rate files, on a file too big to keep as a fixture. +//! +//! `cargo run --release -p engine --example probe_fps -- [secs] [play]` +//! +//! With `play` it also seeks there, plays two seconds against the real audio +//! device and reports the skew between the picture on screen and the master +//! clock -- the machine-checkable half of "lip sync holds". + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +fn main() { + let mut args = std::env::args_os().skip(1); + let path = PathBuf::from(args.next().expect("usage: probe_fps [secs]")); + let secs: f64 = args + .next() + .and_then(|s| s.to_str().and_then(|s| s.parse().ok())) + .unwrap_or(600.0); + + let (meta, _) = engine::demux::Demuxer::open(&path).expect("open"); + println!( + "{}: {}x{} @ {:.9} fps, {} frames", + path.display(), + meta.width, + meta.height, + meta.frame_rate, + meta.frame_count + ); + println!(" ntsc 24000/1001 = {:.9}", 24_000.0 / 1001.0); + println!( + " target frame at t={secs}s: {:.3} (mp4 0.14's flat 23.0 would say {:.3}, {:.1} frames out)", + secs * meta.frame_rate, + secs * 23.0, + secs * (meta.frame_rate - 23.0) + ); + // Straight from the container, to show what the demuxer's frame 0 skipped. + let file = std::fs::File::open(&path).expect("open"); + let size = file.metadata().expect("stat").len(); + let reader = + mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("read header"); + for (id, track) in reader.tracks() { + let elst: Vec<(u64, u64)> = track + .trak + .edts + .as_ref() + .and_then(|e| e.elst.as_ref()) + .map(|e| { + e.entries + .iter() + .map(|e| (e.segment_duration, e.media_time)) + .collect() + }) + .unwrap_or_default(); + let ctts: Vec<(u32, u32)> = track + .trak + .mdia + .minf + .stbl + .ctts + .as_ref() + .map(|c| { + c.entries + .iter() + .take(3) + .map(|e| (e.sample_count, e.sample_offset as u32)) + .collect() + }) + .unwrap_or_default(); + println!(" ctts (first entries): {ctts:?}"); + println!( + " track {id}: {:?}, timescale {}, {} samples, elst (segment_duration, media_time) {elst:?}", + track.media_type(), + track.timescale(), + track.sample_count(), + ); + } + match engine::AudioSession::open(&path) { + Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels), + Ok(None) => println!( + " audio: none usable ({:?})", + engine::AudioSession::unsupported(&path) + ), + Err(e) => println!(" audio: refused ({e})"), + } + + if args.next().is_some_and(|a| a == *"play") { + play(&path, secs, meta.frame_rate); + } +} + +/// Seeks in, plays two seconds against the real device, and reports where the +/// picture stands against the master clock. The clock counts audio samples, so +/// `frame / fps - clock` *is* the A/V skew: a truncated frame rate shows up +/// here as tens of seconds of it, ten minutes in. +fn play(path: &std::path::Path, secs: f64, fps: f64) { + let mut session = engine::PlaybackSession::open(path).expect("open for playback"); + session.seek(secs); + session.play(); + let mut last = None; + let mut held: Option = None; + let deadline = Instant::now() + Duration::from_secs(2); + while Instant::now() < deadline { + session.tick(); + // The app's own drop-when-behind rule (`Player::pump`): show every frame + // already due and hold the first one that is not, or this would measure + // how far the decoder runs ahead instead of what is on screen. + let target = session.now() * fps; + while let Some(index) = held.take().or_else(|| session.try_frame().map(|f| f.index)) { + if f64::from(index) > target { + held = Some(index); + break; + } + last = Some(index); + } + std::thread::sleep(Duration::from_millis(4)); + } + let now = session.now(); + let Some(index) = last else { + println!(" played from {secs}s: no frame arrived, clock at {now:.3}s"); + return; + }; + let media = f64::from(index) / fps; + println!( + " played from {secs}s: clock {now:.3}s, frame {index} = media {media:.3}s, skew {:+.3}s", + media - now + ); +} diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index ea3e093..3bfa1ee 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -259,6 +259,25 @@ impl AudioSession { Ok(Some((meta, rx))) } + /// Why [`open`](Self::open) came back silent for a file that *has* sound: + /// `Some(reason)` when there is an audio track and it is not the AAC-LC + /// this decodes (an AC-3 remux, say). `None` when the file is simply silent + /// -- nothing to tell the user there. Header only, and only worth calling + /// once the open has already returned no audio. + pub fn unsupported(path: impl AsRef) -> crate::Result> { + let file = File::open(path.as_ref())?; + let size = file.metadata()?.len(); + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; + Ok(reader + .tracks() + .values() + .find(|t| matches!(t.track_type(), Ok(TrackType::Audio))) + .map(|t| match t.media_type() { + Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"), + Err(_) => "the audio track is in a codec we cannot decode (AAC-LC only)".to_string(), + })) + } + /// The audio parameters of `path`, for checking an import against the /// timeline's first source: header only, no decoder and no worker. /// `Ok(None)` means no AAC track — an audio-less file, which import pairs @@ -689,8 +708,9 @@ fn audio_specific_config(track: &Mp4Track) -> crate::Result> { } /// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`] -/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. -fn stts_pairs(track: &Mp4Track) -> impl Iterator + '_ { +/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. Shared with +/// `demux`, which walks a video trak's table with the same two helpers. +pub(crate) fn stts_pairs(track: &Mp4Track) -> impl Iterator + '_ { track .trak .mdia @@ -709,6 +729,18 @@ fn stts_pairs(track: &Mp4Track) -> impl Iterator + '_ { /// Muxers that write a zero edit list despite a primed stream would leak the /// priming; upgrade path is preferring the codec delay when it disagrees. fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { + edit_media_time(track) + .and_then(|t| scale(t, sample_rate, track.timescale())) + .unwrap_or(DEFAULT_PRIMING) +} + +/// `media_time` of the edit list's first real entry, in the track's own +/// timescale: where the presentation starts inside the media. `None` when there +/// is no edit list, or only empty entries -- those shift the timeline rather +/// than trim the media, and neither track honours that shift (see +/// [`priming_samples`]'s ponytail). Shared with `demux`, which owes the video +/// track the same trim. +pub(crate) fn edit_media_time(track: &Mp4Track) -> Option { track .trak .edts @@ -720,8 +752,6 @@ fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { .map(|e| e.media_time) .find(|&t| t != EMPTY_EDIT && t != u64::MAX) }) - .and_then(|t| scale(t, sample_rate, track.timescale())) - .unwrap_or(DEFAULT_PRIMING) } /// `value` from the track timescale into samples-per-channel. `None` on a zero @@ -749,7 +779,7 @@ fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 { /// packets of an entry boundary gets less pre-roll. AAC packets are uniformly /// 1024 frames (one entry per track), so this cannot fire here; upgrade path is /// carrying the previous entry's delta through the walk. -fn packet_at( +pub(crate) fn packet_at( entries: impl IntoIterator, target_ts: u64, pre_roll: u32, diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index d354878..a0e9d50 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -348,11 +348,11 @@ fn run( cancel: &AtomicBool, ) { let mut decoder = Decoder::new(); - // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at - // a sync sample, so pictures between it and `start_frame` are decoded (the - // target frame references them) but never converted or sent. - let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); - let mut index = sync - 1; + // Decoding has to restart at a sync sample, so pictures between it and + // `start_frame` are decoded (the target frame references them) but never + // converted or sent. Signed, because the landing sync sample can sit inside + // what the file's edit list trims, i.e. *before* frame 0. + let mut index = demuxer.seek_to_sync_at_or_before(start_frame); // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); // reordering streams need POC-sorted output before display. @@ -376,12 +376,12 @@ fn run( break; } }; - if index < start_frame { + if index < i64::from(start_frame) { index += 1; continue; } let frame = Frame { - index, + index: index as u32, width: yuv.width as u32, height: yuv.height as u32, bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), @@ -390,7 +390,7 @@ fn run( if tx.send(frame).is_err() { break; // consumer went away } - if index >= end_frame { + if index >= i64::from(end_frame) { break; // end of the requested range } } diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 1d22864..3d5fb53 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -4,7 +4,9 @@ use std::fs::File; use std::io::BufReader; use std::path::Path; -use mp4::{MediaType, Mp4Reader}; +use mp4::{MediaType, Mp4Reader, Mp4Track}; + +use crate::audio::{edit_media_time, packet_at, stts_pairs}; const START_CODE: [u8; 4] = [0, 0, 0, 1]; @@ -20,6 +22,10 @@ pub struct Demuxer { reader: Mp4Reader>, track_id: u32, sample_count: u32, + /// 1-based sample id of *frame 0*: the edit list can start the presentation + /// a couple of frames into the media, exactly as it does for audio priming + /// (`audio::priming_samples`), and frame indices count from there. + first_sample: u32, /// Annex-B SPS+PPS, re-injected ahead of every sync sample. parameter_sets: Vec, /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box @@ -44,9 +50,10 @@ impl Demuxer { let meta = VideoMeta { width: track.width() as u32, height: track.height() as u32, - frame_rate: track.frame_rate(), + frame_rate: frame_rate(track), frame_count: 0, }; + let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); let mut parameter_sets = Vec::new(); parameter_sets.extend_from_slice(&START_CODE); parameter_sets.extend_from_slice(track.sequence_parameter_set()?); @@ -63,18 +70,24 @@ impl Demuxer { .unwrap_or_default(); let sample_count = reader.sample_count(track_id)?; + // Where a seek to frame 0 would put the cursor: the samples the edit list + // trims are still read, they are references for the ones that show. + let next_sample = sync_at_or_before(&sync_samples, first_sample); Ok(( VideoMeta { - frame_count: sample_count, + // The samples the edit list trims off the front are not frames of + // the presentation, so they are not counted as ones. + frame_count: sample_count.saturating_sub(first_sample - 1), ..meta }, Self { reader, track_id, sample_count, + first_sample, parameter_sets, sync_samples, - next_sample: 1, // sample ids are 1-based + next_sample, }, )) } @@ -99,16 +112,84 @@ impl Demuxer { } /// Rewinds/forwards the read cursor to the latest sync sample at or before - /// `sample_id` (1-based), which is the earliest point a decoder can start - /// from and still reach `sample_id`. Returns the sample it landed on. - pub fn seek_to_sync_at_or_before(&mut self, sample_id: u32) -> u32 { - let target = sample_id.clamp(1, self.sample_count.max(1)); + /// display frame `frame` (0-based), which is the earliest point a decoder can + /// start from and still reach it. Returns the display index of the first + /// picture the caller will now be handed -- *negative* when the landing sync + /// sample sits inside what the edit list trims, i.e. those pictures decode as + /// references but are not frame 0 or later. + pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 { + let target = frame + .saturating_add(self.first_sample) + .clamp(1, self.sample_count.max(1)); let chosen = sync_at_or_before(&self.sync_samples, target); self.next_sample = chosen; - chosen + i64::from(chosen) - i64::from(self.first_sample) } } +/// Frames per second off the sample table. `mp4 0.14`'s own +/// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds* +/// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat +/// 23.0 -- with the audio clock as master that is 4 % of drift, five minutes of +/// it by the end of a two-hour film. +fn frame_rate(track: &Mp4Track) -> f64 { + fps_from_stts(stts_pairs(track), track.timescale()) +} + +/// Whole track over whole track: constant-delta tables (the common case) come +/// out as exactly `timescale / delta`, and a table that spreads 3753/3754 ticks +/// to average 3753.75 averages instead of truncating. All of it in `f64`, which +/// is the bug the caller above exists to avoid. +fn fps_from_stts(entries: impl IntoIterator, timescale: u32) -> f64 { + let (samples, ticks) = entries + .into_iter() + .fold((0u64, 0u64), |(samples, ticks), (count, delta)| { + ( + samples + u64::from(count), + ticks + u64::from(count) * u64::from(delta), + ) + }); + match ticks { + // No timing in the header at all; `mp4`'s own answer for that is 0.0 too. + 0 => 0.0, + ticks => samples as f64 * f64::from(timescale) / ticks as f64, + } +} + +/// What the edit list really trims off the front, in media ticks: its +/// `media_time` less the first sample's own composition offset. A stream with +/// B-frames carries a `ctts` delay, and every muxer writes `media_time` equal to +/// exactly that delay -- which is not a trim at all, it is the container saying +/// "sample 1 is still the first picture". Reading it as one drops real frames +/// (`test_high.mp4` loses two, and so did the film this bug came from). What is +/// left over after the delay is the genuine trim. +/// +/// ponytail: empty edits are ignored and `media_time` is otherwise taken at face +/// value, which is exactly what [`crate::audio::edit_media_time`] gives the audio +/// track -- symmetry between the two is the point, not a full edit-list engine. +/// Their *empty* edits can differ (83 ms of video against 62 ms of audio in that +/// film, so the picture stays 21 ms -- half a frame -- early); honouring those is +/// the upgrade path, and it belongs to both tracks at once. +fn trim_ticks(track: &Mp4Track) -> Option { + let delay = track + .trak + .mdia + .minf + .stbl + .ctts + .as_ref() + .and_then(|ctts| ctts.entries.first()) + .map_or(0, |e| e.sample_offset.max(0) as u64); + edit_media_time(track).map(|t| t.saturating_sub(delay)) +} + +/// 1-based id of the sample the presentation starts on, for a track trimmed by +/// `trim` media ticks ([`trim_ticks`]). `None` (no edit list) and zero are both +/// "no trim", i.e. the first sample. +fn first_frame_sample(entries: impl IntoIterator, trim: Option) -> u32 { + trim.map_or(1, |t| packet_at(entries, t, 0).0) +} + /// Largest entry of the ascending sync table that is `<= sample_id`. An empty /// table means every sample is a sync sample. When `sample_id` sits before the /// first sync sample there is nothing decodable earlier, so that one wins. @@ -168,6 +249,38 @@ mod tests { assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last"); } + /// The desync bug: NTSC rates must survive the sample table as themselves. + #[test] + fn ntsc_frame_rates_come_out_fractional() { + // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer + // spreads 3753/3754 and only the total is exact -- 4 frames, 15015 ticks. + let ntsc = fps_from_stts([(1u32, 3753u32), (3, 3754)], 90_000); + assert!( + (ntsc - 24_000.0 / 1001.0).abs() < 1e-9, + "23.976 fps read back as {ntsc} (mp4 0.14 says 23.0)" + ); + // Constant delta stays an exact division, not an average. + assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0); + assert_eq!(fps_from_stts([(120u32, 1001u32)], 30_000), 30_000.0 / 1001.0); + assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing"); + } + + /// A video edit list trims the head of the media exactly as the audio one + /// does; frame 0 is the first frame that is *shown*. The B-frame delay is + /// the case that must **not** move it -- that one is a lie of a `media_time` + /// and taking it literally throws two real frames away. + #[test] + fn a_video_edit_list_moves_frame_zero_but_a_ctts_delay_does_not() { + let entries = [(1u32, 3753u32), (3, 3754)]; + // The film's own numbers: media_time 7507 at 90 kHz, and a first ctts + // offset of 7507 to go with it -- nothing trimmed. + assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1); + // Two frames genuinely cut off the front. + assert_eq!(first_frame_sample(entries, Some(7507)), 3); + assert_eq!(first_frame_sample(entries, None), 1, "no edit list, no trim"); + assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim"); + } + #[test] fn rejects_misparse() { assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err()); diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 42bdcc4..f3c5f43 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -328,12 +328,14 @@ impl Enc { let bitrate = settings .bitrate .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); - // The plugin wants an exact rational; a thousandth of a frame per second - // is finer than any container fps we can read back. - let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32; + // The plugin wants an exact rational, and the muxer already picks one + // that is exact at every rate we can read -- `fps * 1000 / 1000` would + // hand 24000/1001 over as a rounded 23.976, which is the same + // truncation the container timing had. + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; if !settings.force_sw && !forced("VE_SW_ENC") - && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, 1_000, bitrate) + && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate) { eprintln!("export encoder: hardware (VA-API plugin)"); return Ok(Self::Hw(hw)); @@ -458,8 +460,9 @@ impl ClipDecoder { struct SwDecoder { demuxer: Demuxer, decoder: Decoder, - /// Display index of the next picture the decoder will produce. - index: u32, + /// Display index of the next picture the decoder will produce. Signed: a + /// sync sample inside what the edit list trims is before frame 0. + index: i64, start: u32, frame: Option, } @@ -469,12 +472,11 @@ impl SwDecoder { let (_, mut demuxer) = Demuxer::open(path)?; // Decoding restarts at a sync sample, so pictures between it and the in // point are decoded (the target references them) and then dropped. - // Sample ids are 1-based, frame indices 0-based. - let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); + let index = demuxer.seek_to_sync_at_or_before(start_frame); Ok(Self { demuxer, decoder: Decoder::new(), - index: sync - 1, + index, start: start_frame, frame: None, }) @@ -492,7 +494,7 @@ impl SwDecoder { .decode(&au) .map_err(|e| format!("decode at picture {}: {e}", self.index))?; let Some(yuv) = decoded else { continue }; - let wanted = self.index >= self.start; + let wanted = self.index >= i64::from(self.start); self.index += 1; if wanted { self.frame = Some(yuv); diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index a24cd50..ec27c0e 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -10,15 +10,14 @@ use mp4::{ Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, }; -/// 90 kHz is the H.264 convention; frame durations round to well under a -/// microsecond of error at every fps we care about. +/// 90 kHz is the H.264 convention, and it divides exactly at every *integer* +/// fps (3000 ticks at 30, 3600 at 25). The NTSC rates do not divide into it at +/// all -- 24000/1001 wants 3753.75 -- so those get their own clock; see +/// [`frame_timing`]. const VIDEO_TIMESCALE: u32 = 90_000; -/// The same as the video's, deliberately: `mp4` converts every sample duration -/// into the movie timescale with an integer division of its own (track.rs:752), -/// so a coarser movie clock loses a fraction of a millisecond *per frame* -- -/// 1 kHz makes a 4.000 s export announce itself as 3.960 s. Equal timescales -/// make the video conversion exact. -const MOVIE_TIMESCALE: u32 = VIDEO_TIMESCALE; +/// Ticks per frame for a rate the 90 kHz clock cannot express: every NTSC rate +/// is `n/1001`, so 1001 ticks a frame makes the timescale a whole `n`. +const NTSC_TICKS: u32 = 1001; /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the /// per-packet duration is this constant. const AAC_PACKET_SAMPLES: u32 = 1024; @@ -78,6 +77,7 @@ impl Mp4Muxer { return Err("no usable SPS/PPS for the video track".into()); } + let (timescale, frame_duration) = frame_timing(video.frame_rate)?; let mut writer = Mp4Writer::write_start( BufWriter::new(File::create(path)?), &Mp4Config { @@ -89,12 +89,18 @@ impl Mp4Muxer { FourCC::from(*b"avc1"), FourCC::from(*b"mp41"), ], - timescale: MOVIE_TIMESCALE, + // The video track's own, deliberately: `mp4` converts every + // sample duration into the movie timescale with an integer + // division of its own (track.rs:752), so a coarser movie clock + // loses a fraction of a millisecond *per frame* -- 1 kHz makes a + // 4.000 s export announce itself as 3.960 s. Equal timescales + // make the video conversion exact. + timescale, }, )?; writer.add_track(&TrackConfig { track_type: TrackType::Video, - timescale: VIDEO_TIMESCALE, + timescale, language: "und".to_string(), media_conf: MediaConfig::AvcConfig(AvcConfig { width: video.width as u16, @@ -121,7 +127,7 @@ impl Mp4Muxer { Ok(Self { writer, - frame_duration: (VIDEO_TIMESCALE as f64 / video.frame_rate).round() as u32, + frame_duration, has_audio: audio.is_some(), }) } @@ -171,6 +177,25 @@ impl Mp4Muxer { } } +/// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole* +/// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so +/// those exports stay byte for byte what they were), and `round(fps * 1001)` +/// over [`NTSC_TICKS`] otherwise, which is exact for the whole `n/1001` family. +/// A fixed 90 kHz clock leaves 24000/1001 a quarter tick short *per frame* -- +/// half a second of drift against the audio track by the end of a two-hour +/// export, which is this bug's own truncation reborn at the writing end. +pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> { + let ticks = f64::from(VIDEO_TIMESCALE) / fps; + if (ticks - ticks.round()).abs() < 1e-9 && (1.0..=f64::from(u32::MAX)).contains(&ticks.round()) { + return Ok((VIDEO_TIMESCALE, ticks.round() as u32)); + } + let timescale = (fps * f64::from(NTSC_TICKS)).round(); + if !(1.0..=f64::from(u32::MAX)).contains(×cale) { + return Err(format!("frame rate {fps} has no usable timescale").into()); + } + Ok((timescale as u32, NTSC_TICKS)) +} + /// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the /// unit does not carry both, which the first exported unit always must. pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { @@ -318,6 +343,26 @@ mod tests { ); } + /// Every frame must be a whole number of ticks, or the video track drifts + /// against the audio one over a long export -- the truncation this bug is. + #[test] + fn frame_timing_is_exact_at_ntsc_and_unchanged_at_integer_rates() { + assert_eq!(frame_timing(30.0).unwrap(), (90_000, 3_000), "was 90k/3000"); + assert_eq!(frame_timing(25.0).unwrap(), (90_000, 3_600)); + assert_eq!(frame_timing(24_000.0 / 1001.0).unwrap(), (24_000, 1_001)); + // 29.97 is the one NTSC rate 90 kHz already counts exactly (3003 ticks), + // so it keeps the conventional clock rather than growing its own. + assert_eq!(frame_timing(30_000.0 / 1001.0).unwrap(), (90_000, 3_003)); + // And the pair plays back as the rate it came from, to the last bit. + for fps in [30.0, 25.0, 24_000.0 / 1001.0, 30_000.0 / 1001.0, 60.0] { + let (ts, ticks) = frame_timing(fps).unwrap(); + let played = f64::from(ts) / f64::from(ticks); + assert!((played - fps).abs() < 1e-9, "{fps} writes back as {played}"); + } + // Rate so low the 90 kHz clock cannot count it: refused, not truncated. + assert!(frame_timing(1e-9).is_err()); + } + #[test] fn create_rejects_unusable_config() { let out = std::env::temp_dir().join("ve_mux_never_written.mp4"); @@ -437,4 +482,44 @@ mod tests { std::fs::remove_file(&out).unwrap(); } + + /// The whole pipe at an NTSC rate: what we write is what we read back, to + /// the ninth decimal. Before this bug was fixed the same round trip lost + /// 23.976 on the way out (a rounded frame duration) *and* on the way back + /// in (`mp4`'s integer `frame_rate`), and an hour of export drifted a second. + #[test] + fn an_ntsc_rate_survives_the_round_trip() { + const NTSC: f64 = 24_000.0 / 1001.0; + let out = std::env::temp_dir().join(format!("ve_mux_ntsc_{}.mp4", std::process::id())); + let mut muxer = Mp4Muxer::create( + &out, + &VideoParams { + width: 640, + height: 360, + frame_rate: NTSC, + sps: SPS, + pps: PPS, + }, + None, + ) + .unwrap(); + muxer.write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]])).unwrap(); + muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap(); + muxer.finish().unwrap(); + + let file = File::open(&out).unwrap(); + let size = file.metadata().unwrap().len(); + let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + assert_eq!(reader.tracks()[&VIDEO_TRACK].timescale(), 24_000); + let first = reader.read_sample(VIDEO_TRACK, 1).unwrap().unwrap(); + assert_eq!(first.duration, 1_001, "one frame is a whole 1001 ticks"); + + let (meta, _) = crate::demux::Demuxer::open(&out).unwrap(); + assert!( + (meta.frame_rate - NTSC).abs() < 1e-9, + "read back as {} fps, not {NTSC}", + meta.frame_rate + ); + std::fs::remove_file(&out).unwrap(); + } } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 79cc2f3..958f1ec 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -101,6 +101,11 @@ pub struct PlaybackSession { retired: Vec, clock: PlaybackClock, audio: Option