NTSC frame rates survive the sample table
Browse files at this commit3f81ef82a2cac88426c905e84a372e71d875126aParent: 771cd4a- fix
- NTSC frame rates survive the sample table
11 changed files +502 -55
- crates/app/src/main.rs +22 -2
- crates/engine-hw/src/lib.rs +6 -2
- crates/engine/examples/probe_fps.rs +129 -0
- crates/engine/src/audio.rs +36 -6
- crates/engine/src/decode.rs +8 -8
- crates/engine/src/demux.rs +122 -9
- crates/engine/src/export.rs +12 -10
- crates/engine/src/mux.rs +96 -11
- crates/engine/src/playback.rs +37 -7
- crates/engine/tests/audio_decode.rs +28 -0
- scripts/gen_fixtures.sh +6 -0
crates/app/src/main.rsmodified+22 -2
| @@ -614,6 +614,9 @@ impl Player { | |||
| 614 | match PlaybackSession::open(path) { | 614 | match PlaybackSession::open(path) { |
| 615 | Ok(session) => { | 615 | Ok(session) => { |
| 616 | self.fps = session.meta().frame_rate; | 616 | self.fps = session.meta().frame_rate; |
| 617 | + // Read before the session moves: a file that plays silent says | ||
| 618 | + // so here or nowhere. | ||
| 619 | + let silent = audio_notice(&session); | ||
| 617 | self.session = Some(session); | 620 | self.session = Some(session); |
| 618 | // A fresh session comes up at full volume; the player's own | 621 | // A fresh session comes up at full volume; the player's own |
| 619 | // setting outlives the file, so it is pushed at every new one. | 622 | // setting outlives the file, so it is pushed at every new one. |
| @@ -622,7 +625,7 @@ impl Player { | |||
| 622 | self.project_path = project_path(path); | 625 | self.project_path = project_path(path); |
| 623 | self.name = file_name(path).into(); | 626 | self.name = file_name(path).into(); |
| 624 | self.reset_after_reseek(); | 627 | self.reset_after_reseek(); |
| 625 | - format!("OPENED {}", file_name(path)) | 628 | + format!("OPENED {}{}", file_name(path), silent.unwrap_or_default()) |
| 626 | } | 629 | } |
| 627 | Err(e) => format!("OPEN FAILED: {e}"), | 630 | Err(e) => format!("OPEN FAILED: {e}"), |
| 628 | } | 631 | } |
| @@ -668,6 +671,7 @@ impl Player { | |||
| 668 | let text = match PlaybackSession::open_project(path) { | 671 | let text = match PlaybackSession::open_project(path) { |
| 669 | Ok(session) => { | 672 | Ok(session) => { |
| 670 | self.fps = session.meta().frame_rate; | 673 | self.fps = session.meta().frame_rate; |
| 674 | + let silent = audio_notice(&session); | ||
| 671 | // A project is named after itself but still exports beside its | 675 | // A project is named after itself but still exports beside its |
| 672 | // media: that is the only place an export has ever landed. | 676 | // media: that is the only place an export has ever landed. |
| 673 | self.export_path = export_path(&session.sources()[0]); | 677 | self.export_path = export_path(&session.sources()[0]); |
| @@ -691,7 +695,7 @@ impl Player { | |||
| 691 | // reaches the screen the way a seek's does. The old picture is | 695 | // reaches the screen the way a seek's does. The old picture is |
| 692 | // released by the swap in `pump`, as after any other seek. | 696 | // released by the swap in `pump`, as after any other seek. |
| 693 | self.reset_after_reseek(); | 697 | self.reset_after_reseek(); |
| 694 | - format!("LOADED {}", file_name(path)) | 698 | + format!("LOADED {}{}", file_name(path), silent.unwrap_or_default()) |
| 695 | } | 699 | } |
| 696 | Err(e) => format!("OPEN FAILED: {e}"), | 700 | Err(e) => format!("OPEN FAILED: {e}"), |
| 697 | }; | 701 | }; |
| @@ -2155,6 +2159,15 @@ fn file_name(path: &std::path::Path) -> String { | |||
| 2155 | ) | 2159 | ) |
| 2156 | } | 2160 | } |
| 2157 | 2161 | ||
| 2162 | +/// The tail an open/load notice grows when the file has sound the engine cannot | ||
| 2163 | +/// decode: it plays perfectly, in silence, and that is the one thing the window | ||
| 2164 | +/// would otherwise never say (the engine's own word for it, verbatim). | ||
| 2165 | +fn audio_notice(session: &PlaybackSession) -> Option<String> { | ||
| 2166 | + session | ||
| 2167 | + .audio_disabled_reason() | ||
| 2168 | + .map(|reason| format!(" — NO AUDIO: {reason}")) | ||
| 2169 | +} | ||
| 2170 | + | ||
| 2158 | /// The sources a repaint has not asked about yet. A key that is already there | 2171 | /// The sources a repaint has not asked about yet. A key that is already there |
| 2159 | /// means "asked", whatever state it is in, which is what stops a decode already | 2172 | /// means "asked", whatever state it is in, which is what stops a decode already |
| 2160 | /// running from being started again by the next of sixty repaints a second. | 2173 | /// running from being started again by the next of sixty repaints a second. |
| @@ -3329,6 +3342,13 @@ fn main() { | |||
| 3329 | notice.get_or_insert(text); | 3342 | notice.get_or_insert(text); |
| 3330 | } | 3343 | } |
| 3331 | } | 3344 | } |
| 3345 | + // A file that plays silent is as much news at launch as it is on a drop, and | ||
| 3346 | + // behind the keymap notice for the same reason an import refusal is. | ||
| 3347 | + if let Some(reason) = session.as_ref().and_then(PlaybackSession::audio_disabled_reason) { | ||
| 3348 | + let text = format!("NO AUDIO: {reason}"); | ||
| 3349 | + eprintln!("{text}"); | ||
| 3350 | + notice.get_or_insert(text); | ||
| 3351 | + } | ||
| 3332 | let meta = session.as_ref().map(|session| *session.meta()); | 3352 | let meta = session.as_ref().map(|session| *session.meta()); |
| 3333 | // Beside the media even for a project: an export has never landed anywhere | 3353 | // Beside the media even for a project: an export has never landed anywhere |
| 3334 | // but next to the picture it came from. | 3354 | // but next to the picture it came from. |
crates/engine-hw/src/lib.rsmodified+6 -2
| @@ -179,8 +179,12 @@ impl Session { | |||
| 179 | /// or before it and the pictures in between are dropped unread. | 179 | /// or before it and the pictures in between are dropped unread. |
| 180 | fn open_at(path: &Path, target_sample: u32) -> Option<Self> { | 180 | fn open_at(path: &Path, target_sample: u32) -> Option<Self> { |
| 181 | let mut session = Self::open(path)?; | 181 | let mut session = Self::open(path)?; |
| 182 | - let sync = session.demuxer.seek_to_sync_at_or_before(target_sample); | 182 | + // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based |
| 183 | - session.skip = target_sample.saturating_sub(sync); | 183 | + // display frames -- and answers with a signed one, since a sync sample |
| 184 | + // inside what the edit list trims sits before frame 0. | ||
| 185 | + let target_frame = target_sample.saturating_sub(1); | ||
| 186 | + let first = session.demuxer.seek_to_sync_at_or_before(target_frame); | ||
| 187 | + session.skip = (i64::from(target_frame) - first).max(0) as u32; | ||
| 184 | Some(session) | 188 | Some(session) |
| 185 | } | 189 | } |
| 186 | 190 | ||
crates/engine/examples/probe_fps.rsadded+129 -0
| @@ -0,0 +1,129 @@ | |||
| 1 | +//! What the demuxer reads a file's frame rate as, and what that means for the | ||
| 2 | +//! frame the master clock asks for ten minutes in -- the arithmetic behind A/V | ||
| 3 | +//! desync on NTSC-rate files, on a file too big to keep as a fixture. | ||
| 4 | +//! | ||
| 5 | +//! `cargo run --release -p engine --example probe_fps -- <file.mp4> [secs] [play]` | ||
| 6 | +//! | ||
| 7 | +//! With `play` it also seeks there, plays two seconds against the real audio | ||
| 8 | +//! device and reports the skew between the picture on screen and the master | ||
| 9 | +//! clock -- the machine-checkable half of "lip sync holds". | ||
| 10 | + | ||
| 11 | +use std::path::PathBuf; | ||
| 12 | +use std::time::{Duration, Instant}; | ||
| 13 | + | ||
| 14 | +fn main() { | ||
| 15 | + let mut args = std::env::args_os().skip(1); | ||
| 16 | + let path = PathBuf::from(args.next().expect("usage: probe_fps <file.mp4> [secs]")); | ||
| 17 | + let secs: f64 = args | ||
| 18 | + .next() | ||
| 19 | + .and_then(|s| s.to_str().and_then(|s| s.parse().ok())) | ||
| 20 | + .unwrap_or(600.0); | ||
| 21 | + | ||
| 22 | + let (meta, _) = engine::demux::Demuxer::open(&path).expect("open"); | ||
| 23 | + println!( | ||
| 24 | + "{}: {}x{} @ {:.9} fps, {} frames", | ||
| 25 | + path.display(), | ||
| 26 | + meta.width, | ||
| 27 | + meta.height, | ||
| 28 | + meta.frame_rate, | ||
| 29 | + meta.frame_count | ||
| 30 | + ); | ||
| 31 | + println!(" ntsc 24000/1001 = {:.9}", 24_000.0 / 1001.0); | ||
| 32 | + println!( | ||
| 33 | + " target frame at t={secs}s: {:.3} (mp4 0.14's flat 23.0 would say {:.3}, {:.1} frames out)", | ||
| 34 | + secs * meta.frame_rate, | ||
| 35 | + secs * 23.0, | ||
| 36 | + secs * (meta.frame_rate - 23.0) | ||
| 37 | + ); | ||
| 38 | + // Straight from the container, to show what the demuxer's frame 0 skipped. | ||
| 39 | + let file = std::fs::File::open(&path).expect("open"); | ||
| 40 | + let size = file.metadata().expect("stat").len(); | ||
| 41 | + let reader = | ||
| 42 | + mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("read header"); | ||
| 43 | + for (id, track) in reader.tracks() { | ||
| 44 | + let elst: Vec<(u64, u64)> = track | ||
| 45 | + .trak | ||
| 46 | + .edts | ||
| 47 | + .as_ref() | ||
| 48 | + .and_then(|e| e.elst.as_ref()) | ||
| 49 | + .map(|e| { | ||
| 50 | + e.entries | ||
| 51 | + .iter() | ||
| 52 | + .map(|e| (e.segment_duration, e.media_time)) | ||
| 53 | + .collect() | ||
| 54 | + }) | ||
| 55 | + .unwrap_or_default(); | ||
| 56 | + let ctts: Vec<(u32, u32)> = track | ||
| 57 | + .trak | ||
| 58 | + .mdia | ||
| 59 | + .minf | ||
| 60 | + .stbl | ||
| 61 | + .ctts | ||
| 62 | + .as_ref() | ||
| 63 | + .map(|c| { | ||
| 64 | + c.entries | ||
| 65 | + .iter() | ||
| 66 | + .take(3) | ||
| 67 | + .map(|e| (e.sample_count, e.sample_offset as u32)) | ||
| 68 | + .collect() | ||
| 69 | + }) | ||
| 70 | + .unwrap_or_default(); | ||
| 71 | + println!(" ctts (first entries): {ctts:?}"); | ||
| 72 | + println!( | ||
| 73 | + " track {id}: {:?}, timescale {}, {} samples, elst (segment_duration, media_time) {elst:?}", | ||
| 74 | + track.media_type(), | ||
| 75 | + track.timescale(), | ||
| 76 | + track.sample_count(), | ||
| 77 | + ); | ||
| 78 | + } | ||
| 79 | + match engine::AudioSession::open(&path) { | ||
| 80 | + Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels), | ||
| 81 | + Ok(None) => println!( | ||
| 82 | + " audio: none usable ({:?})", | ||
| 83 | + engine::AudioSession::unsupported(&path) | ||
| 84 | + ), | ||
| 85 | + Err(e) => println!(" audio: refused ({e})"), | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + if args.next().is_some_and(|a| a == *"play") { | ||
| 89 | + play(&path, secs, meta.frame_rate); | ||
| 90 | + } | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// Seeks in, plays two seconds against the real device, and reports where the | ||
| 94 | +/// picture stands against the master clock. The clock counts audio samples, so | ||
| 95 | +/// `frame / fps - clock` *is* the A/V skew: a truncated frame rate shows up | ||
| 96 | +/// here as tens of seconds of it, ten minutes in. | ||
| 97 | +fn play(path: &std::path::Path, secs: f64, fps: f64) { | ||
| 98 | + let mut session = engine::PlaybackSession::open(path).expect("open for playback"); | ||
| 99 | + session.seek(secs); | ||
| 100 | + session.play(); | ||
| 101 | + let mut last = None; | ||
| 102 | + let mut held: Option<u32> = None; | ||
| 103 | + let deadline = Instant::now() + Duration::from_secs(2); | ||
| 104 | + while Instant::now() < deadline { | ||
| 105 | + session.tick(); | ||
| 106 | + // The app's own drop-when-behind rule (`Player::pump`): show every frame | ||
| 107 | + // already due and hold the first one that is not, or this would measure | ||
| 108 | + // how far the decoder runs ahead instead of what is on screen. | ||
| 109 | + let target = session.now() * fps; | ||
| 110 | + while let Some(index) = held.take().or_else(|| session.try_frame().map(|f| f.index)) { | ||
| 111 | + if f64::from(index) > target { | ||
| 112 | + held = Some(index); | ||
| 113 | + break; | ||
| 114 | + } | ||
| 115 | + last = Some(index); | ||
| 116 | + } | ||
| 117 | + std::thread::sleep(Duration::from_millis(4)); | ||
| 118 | + } | ||
| 119 | + let now = session.now(); | ||
| 120 | + let Some(index) = last else { | ||
| 121 | + println!(" played from {secs}s: no frame arrived, clock at {now:.3}s"); | ||
| 122 | + return; | ||
| 123 | + }; | ||
| 124 | + let media = f64::from(index) / fps; | ||
| 125 | + println!( | ||
| 126 | + " played from {secs}s: clock {now:.3}s, frame {index} = media {media:.3}s, skew {:+.3}s", | ||
| 127 | + media - now | ||
| 128 | + ); | ||
| 129 | +} | ||
crates/engine/src/audio.rsmodified+36 -6
| @@ -8,7 +8,7 @@ use std::path::{Path, PathBuf}; | |||
| 8 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | 8 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 9 | use std::thread; | 9 | use std::thread; |
| 10 | 10 | ||
| 11 | -use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track}; | 11 | +use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; |
| 12 | use symphonia_codec_aac::AacDecoder; | 12 | use symphonia_codec_aac::AacDecoder; |
| 13 | use symphonia_core::codecs::audio::{ | 13 | use symphonia_core::codecs::audio::{ |
| 14 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, | 14 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, |
| @@ -216,6 +216,25 @@ impl AudioSession { | |||
| 216 | Ok(Some((meta, rx))) | 216 | Ok(Some((meta, rx))) |
| 217 | } | 217 | } |
| 218 | 218 | ||
| 219 | + /// Why [`open`](Self::open) came back silent for a file that *has* sound: | ||
| 220 | + /// `Some(reason)` when there is an audio track and it is not the AAC-LC | ||
| 221 | + /// this decodes (an AC-3 remux, say). `None` when the file is simply silent | ||
| 222 | + /// -- nothing to tell the user there. Header only, and only worth calling | ||
| 223 | + /// once the open has already returned no audio. | ||
| 224 | + pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { | ||
| 225 | + let file = File::open(path.as_ref())?; | ||
| 226 | + let size = file.metadata()?.len(); | ||
| 227 | + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; | ||
| 228 | + Ok(reader | ||
| 229 | + .tracks() | ||
| 230 | + .values() | ||
| 231 | + .find(|t| matches!(t.track_type(), Ok(TrackType::Audio))) | ||
| 232 | + .map(|t| match t.media_type() { | ||
| 233 | + Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"), | ||
| 234 | + Err(_) => "the audio track is in a codec we cannot decode (AAC-LC only)".to_string(), | ||
| 235 | + })) | ||
| 236 | + } | ||
| 237 | + | ||
| 219 | /// The audio parameters of `path`, for checking an import against the | 238 | /// The audio parameters of `path`, for checking an import against the |
| 220 | /// timeline's first source: header only, no decoder and no worker. | 239 | /// timeline's first source: header only, no decoder and no worker. |
| 221 | /// `Ok(None)` means no AAC track — an audio-less file, which import pairs | 240 | /// `Ok(None)` means no AAC track — an audio-less file, which import pairs |
| @@ -559,8 +578,9 @@ fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> { | |||
| 559 | } | 578 | } |
| 560 | 579 | ||
| 561 | /// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`] | 580 | /// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`] |
| 562 | -/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. | 581 | +/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. Shared with |
| 563 | -fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ { | 582 | +/// `demux`, which walks a video trak's table with the same two helpers. |
| 583 | +pub(crate) fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ { | ||
| 564 | track | 584 | track |
| 565 | .trak | 585 | .trak |
| 566 | .mdia | 586 | .mdia |
| @@ -579,6 +599,18 @@ fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ { | |||
| 579 | /// Muxers that write a zero edit list despite a primed stream would leak the | 599 | /// Muxers that write a zero edit list despite a primed stream would leak the |
| 580 | /// priming; upgrade path is preferring the codec delay when it disagrees. | 600 | /// priming; upgrade path is preferring the codec delay when it disagrees. |
| 581 | fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { | 601 | fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { |
| 602 | + edit_media_time(track) | ||
| 603 | + .and_then(|t| scale(t, sample_rate, track.timescale())) | ||
| 604 | + .unwrap_or(DEFAULT_PRIMING) | ||
| 605 | +} | ||
| 606 | + | ||
| 607 | +/// `media_time` of the edit list's first real entry, in the track's own | ||
| 608 | +/// timescale: where the presentation starts inside the media. `None` when there | ||
| 609 | +/// is no edit list, or only empty entries -- those shift the timeline rather | ||
| 610 | +/// than trim the media, and neither track honours that shift (see | ||
| 611 | +/// [`priming_samples`]'s ponytail). Shared with `demux`, which owes the video | ||
| 612 | +/// track the same trim. | ||
| 613 | +pub(crate) fn edit_media_time(track: &Mp4Track) -> Option<u64> { | ||
| 582 | track | 614 | track |
| 583 | .trak | 615 | .trak |
| 584 | .edts | 616 | .edts |
| @@ -590,8 +622,6 @@ fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { | |||
| 590 | .map(|e| e.media_time) | 622 | .map(|e| e.media_time) |
| 591 | .find(|&t| t != EMPTY_EDIT && t != u64::MAX) | 623 | .find(|&t| t != EMPTY_EDIT && t != u64::MAX) |
| 592 | }) | 624 | }) |
| 593 | - .and_then(|t| scale(t, sample_rate, track.timescale())) | ||
| 594 | - .unwrap_or(DEFAULT_PRIMING) | ||
| 595 | } | 625 | } |
| 596 | 626 | ||
| 597 | /// `value` from the track timescale into samples-per-channel. `None` on a zero | 627 | /// `value` from the track timescale into samples-per-channel. `None` on a zero |
| @@ -619,7 +649,7 @@ fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 { | |||
| 619 | /// packets of an entry boundary gets less pre-roll. AAC packets are uniformly | 649 | /// packets of an entry boundary gets less pre-roll. AAC packets are uniformly |
| 620 | /// 1024 frames (one entry per track), so this cannot fire here; upgrade path is | 650 | /// 1024 frames (one entry per track), so this cannot fire here; upgrade path is |
| 621 | /// carrying the previous entry's delta through the walk. | 651 | /// carrying the previous entry's delta through the walk. |
| 622 | -fn packet_at( | 652 | +pub(crate) fn packet_at( |
| 623 | entries: impl IntoIterator<Item = (u32, u32)>, | 653 | entries: impl IntoIterator<Item = (u32, u32)>, |
| 624 | target_ts: u64, | 654 | target_ts: u64, |
| 625 | pre_roll: u32, | 655 | pre_roll: u32, |
crates/engine/src/decode.rsmodified+8 -8
| @@ -348,11 +348,11 @@ fn run( | |||
| 348 | cancel: &AtomicBool, | 348 | cancel: &AtomicBool, |
| 349 | ) { | 349 | ) { |
| 350 | let mut decoder = Decoder::new(); | 350 | let mut decoder = Decoder::new(); |
| 351 | - // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at | 351 | + // Decoding has to restart at a sync sample, so pictures between it and |
| 352 | - // a sync sample, so pictures between it and `start_frame` are decoded (the | 352 | + // `start_frame` are decoded (the target frame references them) but never |
| 353 | - // target frame references them) but never converted or sent. | 353 | + // converted or sent. Signed, because the landing sync sample can sit inside |
| 354 | - let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); | 354 | + // what the file's edit list trims, i.e. *before* frame 0. |
| 355 | - let mut index = sync - 1; | 355 | + let mut index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 356 | 356 | ||
| 357 | // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); | 357 | // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); |
| 358 | // reordering streams need POC-sorted output before display. | 358 | // reordering streams need POC-sorted output before display. |
| @@ -376,12 +376,12 @@ fn run( | |||
| 376 | break; | 376 | break; |
| 377 | } | 377 | } |
| 378 | }; | 378 | }; |
| 379 | - if index < start_frame { | 379 | + if index < i64::from(start_frame) { |
| 380 | index += 1; | 380 | index += 1; |
| 381 | continue; | 381 | continue; |
| 382 | } | 382 | } |
| 383 | let frame = Frame { | 383 | let frame = Frame { |
| 384 | - index, | 384 | + index: index as u32, |
| 385 | width: yuv.width as u32, | 385 | width: yuv.width as u32, |
| 386 | height: yuv.height as u32, | 386 | height: yuv.height as u32, |
| 387 | bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), | 387 | bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), |
| @@ -390,7 +390,7 @@ fn run( | |||
| 390 | if tx.send(frame).is_err() { | 390 | if tx.send(frame).is_err() { |
| 391 | break; // consumer went away | 391 | break; // consumer went away |
| 392 | } | 392 | } |
| 393 | - if index >= end_frame { | 393 | + if index >= i64::from(end_frame) { |
| 394 | break; // end of the requested range | 394 | break; // end of the requested range |
| 395 | } | 395 | } |
| 396 | } | 396 | } |
crates/engine/src/demux.rsmodified+122 -9
| @@ -4,7 +4,9 @@ use std::fs::File; | |||
| 4 | use std::io::BufReader; | 4 | use std::io::BufReader; |
| 5 | use std::path::Path; | 5 | use std::path::Path; |
| 6 | 6 | ||
| 7 | -use mp4::{MediaType, Mp4Reader}; | 7 | +use mp4::{MediaType, Mp4Reader, Mp4Track}; |
| 8 | + | ||
| 9 | +use crate::audio::{edit_media_time, packet_at, stts_pairs}; | ||
| 8 | 10 | ||
| 9 | const START_CODE: [u8; 4] = [0, 0, 0, 1]; | 11 | const START_CODE: [u8; 4] = [0, 0, 0, 1]; |
| 10 | 12 | ||
| @@ -20,6 +22,10 @@ pub struct Demuxer { | |||
| 20 | reader: Mp4Reader<BufReader<File>>, | 22 | reader: Mp4Reader<BufReader<File>>, |
| 21 | track_id: u32, | 23 | track_id: u32, |
| 22 | sample_count: u32, | 24 | sample_count: u32, |
| 25 | + /// 1-based sample id of *frame 0*: the edit list can start the presentation | ||
| 26 | + /// a couple of frames into the media, exactly as it does for audio priming | ||
| 27 | + /// (`audio::priming_samples`), and frame indices count from there. | ||
| 28 | + first_sample: u32, | ||
| 23 | /// Annex-B SPS+PPS, re-injected ahead of every sync sample. | 29 | /// Annex-B SPS+PPS, re-injected ahead of every sync sample. |
| 24 | parameter_sets: Vec<u8>, | 30 | parameter_sets: Vec<u8>, |
| 25 | /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box | 31 | /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box |
| @@ -44,9 +50,10 @@ impl Demuxer { | |||
| 44 | let meta = VideoMeta { | 50 | let meta = VideoMeta { |
| 45 | width: track.width() as u32, | 51 | width: track.width() as u32, |
| 46 | height: track.height() as u32, | 52 | height: track.height() as u32, |
| 47 | - frame_rate: track.frame_rate(), | 53 | + frame_rate: frame_rate(track), |
| 48 | frame_count: 0, | 54 | frame_count: 0, |
| 49 | }; | 55 | }; |
| 56 | + let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); | ||
| 50 | let mut parameter_sets = Vec::new(); | 57 | let mut parameter_sets = Vec::new(); |
| 51 | parameter_sets.extend_from_slice(&START_CODE); | 58 | parameter_sets.extend_from_slice(&START_CODE); |
| 52 | parameter_sets.extend_from_slice(track.sequence_parameter_set()?); | 59 | parameter_sets.extend_from_slice(track.sequence_parameter_set()?); |
| @@ -63,18 +70,24 @@ impl Demuxer { | |||
| 63 | .unwrap_or_default(); | 70 | .unwrap_or_default(); |
| 64 | 71 | ||
| 65 | let sample_count = reader.sample_count(track_id)?; | 72 | let sample_count = reader.sample_count(track_id)?; |
| 73 | + // Where a seek to frame 0 would put the cursor: the samples the edit list | ||
| 74 | + // trims are still read, they are references for the ones that show. | ||
| 75 | + let next_sample = sync_at_or_before(&sync_samples, first_sample); | ||
| 66 | Ok(( | 76 | Ok(( |
| 67 | VideoMeta { | 77 | VideoMeta { |
| 68 | - frame_count: sample_count, | 78 | + // The samples the edit list trims off the front are not frames of |
| 79 | + // the presentation, so they are not counted as ones. | ||
| 80 | + frame_count: sample_count.saturating_sub(first_sample - 1), | ||
| 69 | ..meta | 81 | ..meta |
| 70 | }, | 82 | }, |
| 71 | Self { | 83 | Self { |
| 72 | reader, | 84 | reader, |
| 73 | track_id, | 85 | track_id, |
| 74 | sample_count, | 86 | sample_count, |
| 87 | + first_sample, | ||
| 75 | parameter_sets, | 88 | parameter_sets, |
| 76 | sync_samples, | 89 | sync_samples, |
| 77 | - next_sample: 1, // sample ids are 1-based | 90 | + next_sample, |
| 78 | }, | 91 | }, |
| 79 | )) | 92 | )) |
| 80 | } | 93 | } |
| @@ -99,16 +112,84 @@ impl Demuxer { | |||
| 99 | } | 112 | } |
| 100 | 113 | ||
| 101 | /// Rewinds/forwards the read cursor to the latest sync sample at or before | 114 | /// Rewinds/forwards the read cursor to the latest sync sample at or before |
| 102 | - /// `sample_id` (1-based), which is the earliest point a decoder can start | 115 | + /// display frame `frame` (0-based), which is the earliest point a decoder can |
| 103 | - /// from and still reach `sample_id`. Returns the sample it landed on. | 116 | + /// start from and still reach it. Returns the display index of the first |
| 104 | - pub fn seek_to_sync_at_or_before(&mut self, sample_id: u32) -> u32 { | 117 | + /// picture the caller will now be handed -- *negative* when the landing sync |
| 105 | - let target = sample_id.clamp(1, self.sample_count.max(1)); | 118 | + /// sample sits inside what the edit list trims, i.e. those pictures decode as |
| 119 | + /// references but are not frame 0 or later. | ||
| 120 | + pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 { | ||
| 121 | + let target = frame | ||
| 122 | + .saturating_add(self.first_sample) | ||
| 123 | + .clamp(1, self.sample_count.max(1)); | ||
| 106 | let chosen = sync_at_or_before(&self.sync_samples, target); | 124 | let chosen = sync_at_or_before(&self.sync_samples, target); |
| 107 | self.next_sample = chosen; | 125 | self.next_sample = chosen; |
| 108 | - chosen | 126 | + i64::from(chosen) - i64::from(self.first_sample) |
| 109 | } | 127 | } |
| 110 | } | 128 | } |
| 111 | 129 | ||
| 130 | +/// Frames per second off the sample table. `mp4 0.14`'s own | ||
| 131 | +/// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds* | ||
| 132 | +/// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat | ||
| 133 | +/// 23.0 -- with the audio clock as master that is 4 % of drift, five minutes of | ||
| 134 | +/// it by the end of a two-hour film. | ||
| 135 | +fn frame_rate(track: &Mp4Track) -> f64 { | ||
| 136 | + fps_from_stts(stts_pairs(track), track.timescale()) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Whole track over whole track: constant-delta tables (the common case) come | ||
| 140 | +/// out as exactly `timescale / delta`, and a table that spreads 3753/3754 ticks | ||
| 141 | +/// to average 3753.75 averages instead of truncating. All of it in `f64`, which | ||
| 142 | +/// is the bug the caller above exists to avoid. | ||
| 143 | +fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 { | ||
| 144 | + let (samples, ticks) = entries | ||
| 145 | + .into_iter() | ||
| 146 | + .fold((0u64, 0u64), |(samples, ticks), (count, delta)| { | ||
| 147 | + ( | ||
| 148 | + samples + u64::from(count), | ||
| 149 | + ticks + u64::from(count) * u64::from(delta), | ||
| 150 | + ) | ||
| 151 | + }); | ||
| 152 | + match ticks { | ||
| 153 | + // No timing in the header at all; `mp4`'s own answer for that is 0.0 too. | ||
| 154 | + 0 => 0.0, | ||
| 155 | + ticks => samples as f64 * f64::from(timescale) / ticks as f64, | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// What the edit list really trims off the front, in media ticks: its | ||
| 160 | +/// `media_time` less the first sample's own composition offset. A stream with | ||
| 161 | +/// B-frames carries a `ctts` delay, and every muxer writes `media_time` equal to | ||
| 162 | +/// exactly that delay -- which is not a trim at all, it is the container saying | ||
| 163 | +/// "sample 1 is still the first picture". Reading it as one drops real frames | ||
| 164 | +/// (`test_high.mp4` loses two, and so did the film this bug came from). What is | ||
| 165 | +/// left over after the delay is the genuine trim. | ||
| 166 | +/// | ||
| 167 | +/// ponytail: empty edits are ignored and `media_time` is otherwise taken at face | ||
| 168 | +/// value, which is exactly what [`crate::audio::edit_media_time`] gives the audio | ||
| 169 | +/// track -- symmetry between the two is the point, not a full edit-list engine. | ||
| 170 | +/// Their *empty* edits can differ (83 ms of video against 62 ms of audio in that | ||
| 171 | +/// film, so the picture stays 21 ms -- half a frame -- early); honouring those is | ||
| 172 | +/// the upgrade path, and it belongs to both tracks at once. | ||
| 173 | +fn trim_ticks(track: &Mp4Track) -> Option<u64> { | ||
| 174 | + let delay = track | ||
| 175 | + .trak | ||
| 176 | + .mdia | ||
| 177 | + .minf | ||
| 178 | + .stbl | ||
| 179 | + .ctts | ||
| 180 | + .as_ref() | ||
| 181 | + .and_then(|ctts| ctts.entries.first()) | ||
| 182 | + .map_or(0, |e| e.sample_offset.max(0) as u64); | ||
| 183 | + edit_media_time(track).map(|t| t.saturating_sub(delay)) | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +/// 1-based id of the sample the presentation starts on, for a track trimmed by | ||
| 187 | +/// `trim` media ticks ([`trim_ticks`]). `None` (no edit list) and zero are both | ||
| 188 | +/// "no trim", i.e. the first sample. | ||
| 189 | +fn first_frame_sample(entries: impl IntoIterator<Item = (u32, u32)>, trim: Option<u64>) -> u32 { | ||
| 190 | + trim.map_or(1, |t| packet_at(entries, t, 0).0) | ||
| 191 | +} | ||
| 192 | + | ||
| 112 | /// Largest entry of the ascending sync table that is `<= sample_id`. An empty | 193 | /// Largest entry of the ascending sync table that is `<= sample_id`. An empty |
| 113 | /// table means every sample is a sync sample. When `sample_id` sits before the | 194 | /// table means every sample is a sync sample. When `sample_id` sits before the |
| 114 | /// first sync sample there is nothing decodable earlier, so that one wins. | 195 | /// first sync sample there is nothing decodable earlier, so that one wins. |
| @@ -168,6 +249,38 @@ mod tests { | |||
| 168 | assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last"); | 249 | assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last"); |
| 169 | } | 250 | } |
| 170 | 251 | ||
| 252 | + /// The desync bug: NTSC rates must survive the sample table as themselves. | ||
| 253 | + #[test] | ||
| 254 | + fn ntsc_frame_rates_come_out_fractional() { | ||
| 255 | + // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer | ||
| 256 | + // spreads 3753/3754 and only the total is exact -- 4 frames, 15015 ticks. | ||
| 257 | + let ntsc = fps_from_stts([(1u32, 3753u32), (3, 3754)], 90_000); | ||
| 258 | + assert!( | ||
| 259 | + (ntsc - 24_000.0 / 1001.0).abs() < 1e-9, | ||
| 260 | + "23.976 fps read back as {ntsc} (mp4 0.14 says 23.0)" | ||
| 261 | + ); | ||
| 262 | + // Constant delta stays an exact division, not an average. | ||
| 263 | + assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0); | ||
| 264 | + assert_eq!(fps_from_stts([(120u32, 1001u32)], 30_000), 30_000.0 / 1001.0); | ||
| 265 | + assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing"); | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + /// A video edit list trims the head of the media exactly as the audio one | ||
| 269 | + /// does; frame 0 is the first frame that is *shown*. The B-frame delay is | ||
| 270 | + /// the case that must **not** move it -- that one is a lie of a `media_time` | ||
| 271 | + /// and taking it literally throws two real frames away. | ||
| 272 | + #[test] | ||
| 273 | + fn a_video_edit_list_moves_frame_zero_but_a_ctts_delay_does_not() { | ||
| 274 | + let entries = [(1u32, 3753u32), (3, 3754)]; | ||
| 275 | + // The film's own numbers: media_time 7507 at 90 kHz, and a first ctts | ||
| 276 | + // offset of 7507 to go with it -- nothing trimmed. | ||
| 277 | + assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1); | ||
| 278 | + // Two frames genuinely cut off the front. | ||
| 279 | + assert_eq!(first_frame_sample(entries, Some(7507)), 3); | ||
| 280 | + assert_eq!(first_frame_sample(entries, None), 1, "no edit list, no trim"); | ||
| 281 | + assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim"); | ||
| 282 | + } | ||
| 283 | + | ||
| 171 | #[test] | 284 | #[test] |
| 172 | fn rejects_misparse() { | 285 | fn rejects_misparse() { |
| 173 | assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err()); | 286 | assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err()); |
crates/engine/src/export.rsmodified+12 -10
| @@ -328,12 +328,14 @@ impl Enc { | |||
| 328 | let bitrate = settings | 328 | let bitrate = settings |
| 329 | .bitrate | 329 | .bitrate |
| 330 | .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); | 330 | .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); |
| 331 | - // The plugin wants an exact rational; a thousandth of a frame per second | 331 | + // The plugin wants an exact rational, and the muxer already picks one |
| 332 | - // is finer than any container fps we can read back. | 332 | + // that is exact at every rate we can read -- `fps * 1000 / 1000` would |
| 333 | - let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32; | 333 | + // hand 24000/1001 over as a rounded 23.976, which is the same |
| 334 | + // truncation the container timing had. | ||
| 335 | + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; | ||
| 334 | if !settings.force_sw | 336 | if !settings.force_sw |
| 335 | && !forced("VE_SW_ENC") | 337 | && !forced("VE_SW_ENC") |
| 336 | - && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, 1_000, bitrate) | 338 | + && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate) |
| 337 | { | 339 | { |
| 338 | eprintln!("export encoder: hardware (VA-API plugin)"); | 340 | eprintln!("export encoder: hardware (VA-API plugin)"); |
| 339 | return Ok(Self::Hw(hw)); | 341 | return Ok(Self::Hw(hw)); |
| @@ -458,8 +460,9 @@ impl ClipDecoder { | |||
| 458 | struct SwDecoder { | 460 | struct SwDecoder { |
| 459 | demuxer: Demuxer, | 461 | demuxer: Demuxer, |
| 460 | decoder: Decoder, | 462 | decoder: Decoder, |
| 461 | - /// Display index of the next picture the decoder will produce. | 463 | + /// Display index of the next picture the decoder will produce. Signed: a |
| 462 | - index: u32, | 464 | + /// sync sample inside what the edit list trims is before frame 0. |
| 465 | + index: i64, | ||
| 463 | start: u32, | 466 | start: u32, |
| 464 | frame: Option<YuvFrame>, | 467 | frame: Option<YuvFrame>, |
| 465 | } | 468 | } |
| @@ -469,12 +472,11 @@ impl SwDecoder { | |||
| 469 | let (_, mut demuxer) = Demuxer::open(path)?; | 472 | let (_, mut demuxer) = Demuxer::open(path)?; |
| 470 | // Decoding restarts at a sync sample, so pictures between it and the in | 473 | // Decoding restarts at a sync sample, so pictures between it and the in |
| 471 | // point are decoded (the target references them) and then dropped. | 474 | // point are decoded (the target references them) and then dropped. |
| 472 | - // Sample ids are 1-based, frame indices 0-based. | 475 | + let index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 473 | - let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); | ||
| 474 | Ok(Self { | 476 | Ok(Self { |
| 475 | demuxer, | 477 | demuxer, |
| 476 | decoder: Decoder::new(), | 478 | decoder: Decoder::new(), |
| 477 | - index: sync - 1, | 479 | + index, |
| 478 | start: start_frame, | 480 | start: start_frame, |
| 479 | frame: None, | 481 | frame: None, |
| 480 | }) | 482 | }) |
| @@ -492,7 +494,7 @@ impl SwDecoder { | |||
| 492 | .decode(&au) | 494 | .decode(&au) |
| 493 | .map_err(|e| format!("decode at picture {}: {e}", self.index))?; | 495 | .map_err(|e| format!("decode at picture {}: {e}", self.index))?; |
| 494 | let Some(yuv) = decoded else { continue }; | 496 | let Some(yuv) = decoded else { continue }; |
| 495 | - let wanted = self.index >= self.start; | 497 | + let wanted = self.index >= i64::from(self.start); |
| 496 | self.index += 1; | 498 | self.index += 1; |
| 497 | if wanted { | 499 | if wanted { |
| 498 | self.frame = Some(yuv); | 500 | self.frame = Some(yuv); |
crates/engine/src/mux.rsmodified+96 -11
| @@ -10,15 +10,14 @@ use mp4::{ | |||
| 10 | Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, | 10 | Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, |
| 11 | }; | 11 | }; |
| 12 | 12 | ||
| 13 | -/// 90 kHz is the H.264 convention; frame durations round to well under a | 13 | +/// 90 kHz is the H.264 convention, and it divides exactly at every *integer* |
| 14 | -/// microsecond of error at every fps we care about. | 14 | +/// fps (3000 ticks at 30, 3600 at 25). The NTSC rates do not divide into it at |
| 15 | +/// all -- 24000/1001 wants 3753.75 -- so those get their own clock; see | ||
| 16 | +/// [`frame_timing`]. | ||
| 15 | const VIDEO_TIMESCALE: u32 = 90_000; | 17 | const VIDEO_TIMESCALE: u32 = 90_000; |
| 16 | -/// The same as the video's, deliberately: `mp4` converts every sample duration | 18 | +/// Ticks per frame for a rate the 90 kHz clock cannot express: every NTSC rate |
| 17 | -/// into the movie timescale with an integer division of its own (track.rs:752), | 19 | +/// is `n/1001`, so 1001 ticks a frame makes the timescale a whole `n`. |
| 18 | -/// so a coarser movie clock loses a fraction of a millisecond *per frame* -- | 20 | +const NTSC_TICKS: u32 = 1001; |
| 19 | -/// 1 kHz makes a 4.000 s export announce itself as 3.960 s. Equal timescales | ||
| 20 | -/// make the video conversion exact. | ||
| 21 | -const MOVIE_TIMESCALE: u32 = VIDEO_TIMESCALE; | ||
| 22 | /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the | 21 | /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the |
| 23 | /// per-packet duration is this constant. | 22 | /// per-packet duration is this constant. |
| 24 | const AAC_PACKET_SAMPLES: u32 = 1024; | 23 | const AAC_PACKET_SAMPLES: u32 = 1024; |
| @@ -78,6 +77,7 @@ impl Mp4Muxer { | |||
| 78 | return Err("no usable SPS/PPS for the video track".into()); | 77 | return Err("no usable SPS/PPS for the video track".into()); |
| 79 | } | 78 | } |
| 80 | 79 | ||
| 80 | + let (timescale, frame_duration) = frame_timing(video.frame_rate)?; | ||
| 81 | let mut writer = Mp4Writer::write_start( | 81 | let mut writer = Mp4Writer::write_start( |
| 82 | BufWriter::new(File::create(path)?), | 82 | BufWriter::new(File::create(path)?), |
| 83 | &Mp4Config { | 83 | &Mp4Config { |
| @@ -89,12 +89,18 @@ impl Mp4Muxer { | |||
| 89 | FourCC::from(*b"avc1"), | 89 | FourCC::from(*b"avc1"), |
| 90 | FourCC::from(*b"mp41"), | 90 | FourCC::from(*b"mp41"), |
| 91 | ], | 91 | ], |
| 92 | - timescale: MOVIE_TIMESCALE, | 92 | + // The video track's own, deliberately: `mp4` converts every |
| 93 | + // sample duration into the movie timescale with an integer | ||
| 94 | + // division of its own (track.rs:752), so a coarser movie clock | ||
| 95 | + // loses a fraction of a millisecond *per frame* -- 1 kHz makes a | ||
| 96 | + // 4.000 s export announce itself as 3.960 s. Equal timescales | ||
| 97 | + // make the video conversion exact. | ||
| 98 | + timescale, | ||
| 93 | }, | 99 | }, |
| 94 | )?; | 100 | )?; |
| 95 | writer.add_track(&TrackConfig { | 101 | writer.add_track(&TrackConfig { |
| 96 | track_type: TrackType::Video, | 102 | track_type: TrackType::Video, |
| 97 | - timescale: VIDEO_TIMESCALE, | 103 | + timescale, |
| 98 | language: "und".to_string(), | 104 | language: "und".to_string(), |
| 99 | media_conf: MediaConfig::AvcConfig(AvcConfig { | 105 | media_conf: MediaConfig::AvcConfig(AvcConfig { |
| 100 | width: video.width as u16, | 106 | width: video.width as u16, |
| @@ -121,7 +127,7 @@ impl Mp4Muxer { | |||
| 121 | 127 | ||
| 122 | Ok(Self { | 128 | Ok(Self { |
| 123 | writer, | 129 | writer, |
| 124 | - frame_duration: (VIDEO_TIMESCALE as f64 / video.frame_rate).round() as u32, | 130 | + frame_duration, |
| 125 | has_audio: audio.is_some(), | 131 | has_audio: audio.is_some(), |
| 126 | }) | 132 | }) |
| 127 | } | 133 | } |
| @@ -171,6 +177,25 @@ impl Mp4Muxer { | |||
| 171 | } | 177 | } |
| 172 | } | 178 | } |
| 173 | 179 | ||
| 180 | +/// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole* | ||
| 181 | +/// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so | ||
| 182 | +/// those exports stay byte for byte what they were), and `round(fps * 1001)` | ||
| 183 | +/// over [`NTSC_TICKS`] otherwise, which is exact for the whole `n/1001` family. | ||
| 184 | +/// A fixed 90 kHz clock leaves 24000/1001 a quarter tick short *per frame* -- | ||
| 185 | +/// half a second of drift against the audio track by the end of a two-hour | ||
| 186 | +/// export, which is this bug's own truncation reborn at the writing end. | ||
| 187 | +pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> { | ||
| 188 | + let ticks = f64::from(VIDEO_TIMESCALE) / fps; | ||
| 189 | + if (ticks - ticks.round()).abs() < 1e-9 && (1.0..=f64::from(u32::MAX)).contains(&ticks.round()) { | ||
| 190 | + return Ok((VIDEO_TIMESCALE, ticks.round() as u32)); | ||
| 191 | + } | ||
| 192 | + let timescale = (fps * f64::from(NTSC_TICKS)).round(); | ||
| 193 | + if !(1.0..=f64::from(u32::MAX)).contains(×cale) { | ||
| 194 | + return Err(format!("frame rate {fps} has no usable timescale").into()); | ||
| 195 | + } | ||
| 196 | + Ok((timescale as u32, NTSC_TICKS)) | ||
| 197 | +} | ||
| 198 | + | ||
| 174 | /// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the | 199 | /// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the |
| 175 | /// unit does not carry both, which the first exported unit always must. | 200 | /// unit does not carry both, which the first exported unit always must. |
| 176 | pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { | 201 | pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { |
| @@ -318,6 +343,26 @@ mod tests { | |||
| 318 | ); | 343 | ); |
| 319 | } | 344 | } |
| 320 | 345 | ||
| 346 | + /// Every frame must be a whole number of ticks, or the video track drifts | ||
| 347 | + /// against the audio one over a long export -- the truncation this bug is. | ||
| 348 | + #[test] | ||
| 349 | + fn frame_timing_is_exact_at_ntsc_and_unchanged_at_integer_rates() { | ||
| 350 | + assert_eq!(frame_timing(30.0).unwrap(), (90_000, 3_000), "was 90k/3000"); | ||
| 351 | + assert_eq!(frame_timing(25.0).unwrap(), (90_000, 3_600)); | ||
| 352 | + assert_eq!(frame_timing(24_000.0 / 1001.0).unwrap(), (24_000, 1_001)); | ||
| 353 | + // 29.97 is the one NTSC rate 90 kHz already counts exactly (3003 ticks), | ||
| 354 | + // so it keeps the conventional clock rather than growing its own. | ||
| 355 | + assert_eq!(frame_timing(30_000.0 / 1001.0).unwrap(), (90_000, 3_003)); | ||
| 356 | + // And the pair plays back as the rate it came from, to the last bit. | ||
| 357 | + for fps in [30.0, 25.0, 24_000.0 / 1001.0, 30_000.0 / 1001.0, 60.0] { | ||
| 358 | + let (ts, ticks) = frame_timing(fps).unwrap(); | ||
| 359 | + let played = f64::from(ts) / f64::from(ticks); | ||
| 360 | + assert!((played - fps).abs() < 1e-9, "{fps} writes back as {played}"); | ||
| 361 | + } | ||
| 362 | + // Rate so low the 90 kHz clock cannot count it: refused, not truncated. | ||
| 363 | + assert!(frame_timing(1e-9).is_err()); | ||
| 364 | + } | ||
| 365 | + | ||
| 321 | #[test] | 366 | #[test] |
| 322 | fn create_rejects_unusable_config() { | 367 | fn create_rejects_unusable_config() { |
| 323 | let out = std::env::temp_dir().join("ve_mux_never_written.mp4"); | 368 | let out = std::env::temp_dir().join("ve_mux_never_written.mp4"); |
| @@ -437,4 +482,44 @@ mod tests { | |||
| 437 | 482 | ||
| 438 | std::fs::remove_file(&out).unwrap(); | 483 | std::fs::remove_file(&out).unwrap(); |
| 439 | } | 484 | } |
| 485 | + | ||
| 486 | + /// The whole pipe at an NTSC rate: what we write is what we read back, to | ||
| 487 | + /// the ninth decimal. Before this bug was fixed the same round trip lost | ||
| 488 | + /// 23.976 on the way out (a rounded frame duration) *and* on the way back | ||
| 489 | + /// in (`mp4`'s integer `frame_rate`), and an hour of export drifted a second. | ||
| 490 | + #[test] | ||
| 491 | + fn an_ntsc_rate_survives_the_round_trip() { | ||
| 492 | + const NTSC: f64 = 24_000.0 / 1001.0; | ||
| 493 | + let out = std::env::temp_dir().join(format!("ve_mux_ntsc_{}.mp4", std::process::id())); | ||
| 494 | + let mut muxer = Mp4Muxer::create( | ||
| 495 | + &out, | ||
| 496 | + &VideoParams { | ||
| 497 | + width: 640, | ||
| 498 | + height: 360, | ||
| 499 | + frame_rate: NTSC, | ||
| 500 | + sps: SPS, | ||
| 501 | + pps: PPS, | ||
| 502 | + }, | ||
| 503 | + None, | ||
| 504 | + ) | ||
| 505 | + .unwrap(); | ||
| 506 | + muxer.write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]])).unwrap(); | ||
| 507 | + muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap(); | ||
| 508 | + muxer.finish().unwrap(); | ||
| 509 | + | ||
| 510 | + let file = File::open(&out).unwrap(); | ||
| 511 | + let size = file.metadata().unwrap().len(); | ||
| 512 | + let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); | ||
| 513 | + assert_eq!(reader.tracks()[&VIDEO_TRACK].timescale(), 24_000); | ||
| 514 | + let first = reader.read_sample(VIDEO_TRACK, 1).unwrap().unwrap(); | ||
| 515 | + assert_eq!(first.duration, 1_001, "one frame is a whole 1001 ticks"); | ||
| 516 | + | ||
| 517 | + let (meta, _) = crate::demux::Demuxer::open(&out).unwrap(); | ||
| 518 | + assert!( | ||
| 519 | + (meta.frame_rate - NTSC).abs() < 1e-9, | ||
| 520 | + "read back as {} fps, not {NTSC}", | ||
| 521 | + meta.frame_rate | ||
| 522 | + ); | ||
| 523 | + std::fs::remove_file(&out).unwrap(); | ||
| 524 | + } | ||
| 440 | } | 525 | } |
crates/engine/src/playback.rsmodified+37 -7
| @@ -101,6 +101,11 @@ pub struct PlaybackSession { | |||
| 101 | retired: Vec<Worker>, | 101 | retired: Vec<Worker>, |
| 102 | clock: PlaybackClock, | 102 | clock: PlaybackClock, |
| 103 | audio: Option<Audio>, | 103 | audio: Option<Audio>, |
| 104 | + /// Why this timeline is silent, when the file itself is not: an audio track | ||
| 105 | + /// we cannot decode is a session that plays perfectly and says nothing about | ||
| 106 | + /// it otherwise. `None` for a file that has usable audio *and* for one that | ||
| 107 | + /// has none at all, which is not a surprise worth a notice. | ||
| 108 | + audio_disabled: Option<String>, | ||
| 104 | /// The edit list. Everything a caller says in seconds is a *timeline* | 109 | /// The edit list. Everything a caller says in seconds is a *timeline* |
| 105 | /// position; only this maps it onto the file. | 110 | /// position; only this maps it onto the file. |
| 106 | project: Project, | 111 | project: Project, |
| @@ -123,7 +128,7 @@ impl PlaybackSession { | |||
| 123 | // `open_worker` rather than `open` purely for the worker handle: the | 128 | // `open_worker` rather than `open` purely for the worker handle: the |
| 124 | // field has to exist from the start for the first seek to use it. | 129 | // field has to exist from the start for the first seek to use it. |
| 125 | let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; | 130 | let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; |
| 126 | - let audio = open_audio(&path); | 131 | + let (audio, audio_disabled) = open_audio(&path); |
| 127 | let source = match audio { | 132 | let source = match audio { |
| 128 | Some(_) => ClockSource::Audio, | 133 | Some(_) => ClockSource::Audio, |
| 129 | None => ClockSource::Wall, | 134 | None => ClockSource::Wall, |
| @@ -139,6 +144,7 @@ impl PlaybackSession { | |||
| 139 | retired: Vec::new(), | 144 | retired: Vec::new(), |
| 140 | clock: PlaybackClock::new(source), | 145 | clock: PlaybackClock::new(source), |
| 141 | audio, | 146 | audio, |
| 147 | + audio_disabled, | ||
| 142 | project, | 148 | project, |
| 143 | span, | 149 | span, |
| 144 | eos: false, | 150 | eos: false, |
| @@ -207,7 +213,7 @@ impl PlaybackSession { | |||
| 207 | // only a session's `drop` retires it, so a refusal above this line would | 213 | // only a session's `drop` retires it, so a refusal above this line would |
| 208 | // leave a PipeWire stream and a thread behind for a project that never | 214 | // leave a PipeWire stream and a thread behind for a project that never |
| 209 | // opened. Nothing before it needs the device. | 215 | // opened. Nothing before it needs the device. |
| 210 | - let audio = open_audio(&first); | 216 | + let (audio, audio_disabled) = open_audio(&first); |
| 211 | let mut session = Self { | 217 | let mut session = Self { |
| 212 | meta, | 218 | meta, |
| 213 | frames: stream.frames, | 219 | frames: stream.frames, |
| @@ -218,6 +224,7 @@ impl PlaybackSession { | |||
| 218 | None => ClockSource::Wall, | 224 | None => ClockSource::Wall, |
| 219 | }), | 225 | }), |
| 220 | audio, | 226 | audio, |
| 227 | + audio_disabled, | ||
| 221 | project, | 228 | project, |
| 222 | span, | 229 | span, |
| 223 | eos: false, | 230 | eos: false, |
| @@ -235,6 +242,14 @@ impl PlaybackSession { | |||
| 235 | &self.meta | 242 | &self.meta |
| 236 | } | 243 | } |
| 237 | 244 | ||
| 245 | + /// Why this session plays silent although the file has sound -- an audio | ||
| 246 | + /// track in a codec we cannot decode, or one the decoder refused. `None` | ||
| 247 | + /// when there is audio, and for a file that never had any. A front-end | ||
| 248 | + /// shows it once, at open: without it the whole thing is a stderr line. | ||
| 249 | + pub fn audio_disabled_reason(&self) -> Option<&str> { | ||
| 250 | + self.audio_disabled.as_deref() | ||
| 251 | + } | ||
| 252 | + | ||
| 238 | /// The files this timeline plays from, index 0 first -- a caller needs it | 253 | /// The files this timeline plays from, index 0 first -- a caller needs it |
| 239 | /// to name an export or a window after the media rather than the project. | 254 | /// to name an export or a window after the media rather than the project. |
| 240 | pub fn sources(&self) -> &[PathBuf] { | 255 | pub fn sources(&self) -> &[PathBuf] { |
| @@ -751,16 +766,31 @@ fn matches_timeline( | |||
| 751 | /// `None` for a silent session -- no audio track, no plugin, no daemon, or a | 766 | /// `None` for a silent session -- no audio track, no plugin, no daemon, or a |
| 752 | /// track the decoder refuses. Dropping the receiver on the way out stops the | 767 | /// track the decoder refuses. Dropping the receiver on the way out stops the |
| 753 | /// audio decode worker, so a failure here leaves nothing running. | 768 | /// audio decode worker, so a failure here leaves nothing running. |
| 754 | -fn open_audio(path: &Path) -> Option<Audio> { | 769 | +/// |
| 770 | +/// The second half is why, for the cases the *file* is to blame for: those are | ||
| 771 | +/// a surprise worth showing (see | ||
| 772 | +/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a | ||
| 773 | +/// file with no audio at all and a machine with no output device are not. | ||
| 774 | +fn open_audio(path: &Path) -> (Option<Audio>, Option<String>) { | ||
| 755 | let (meta, rx) = match AudioSession::open(path) { | 775 | let (meta, rx) = match AudioSession::open(path) { |
| 756 | Ok(Some(opened)) => opened, | 776 | Ok(Some(opened)) => opened, |
| 757 | - Ok(None) => return None, | 777 | + // No AAC track: silent by nature, or sound in a codec we do not have -- |
| 778 | + // and only the second of those is worth a word. | ||
| 779 | + Ok(None) => { | ||
| 780 | + let reason = AudioSession::unsupported(path).ok().flatten(); | ||
| 781 | + if let Some(reason) = &reason { | ||
| 782 | + eprintln!("audio disabled: {reason}"); | ||
| 783 | + } | ||
| 784 | + return (None, reason); | ||
| 785 | + } | ||
| 758 | Err(e) => { | 786 | Err(e) => { |
| 759 | eprintln!("audio disabled: {e}"); | 787 | eprintln!("audio disabled: {e}"); |
| 760 | - return None; | 788 | + return (None, Some(e.to_string())); |
| 761 | } | 789 | } |
| 762 | }; | 790 | }; |
| 763 | - let ao = AoSession::open(meta.sample_rate, u32::from(meta.channels))?; | 791 | + let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else { |
| 792 | + return (None, None); // no device: the machine's business, not the file's | ||
| 793 | + }; | ||
| 764 | // The stream comes up streaming; a session starts paused, so silence the | 794 | // The stream comes up streaming; a session starts paused, so silence the |
| 765 | // device until `play`. The feeder still fills the ring in the meantime. | 795 | // device until `play`. The feeder still fills the ring in the meantime. |
| 766 | ao.set_active(false); | 796 | ao.set_active(false); |
| @@ -774,7 +804,7 @@ fn open_audio(path: &Path) -> Option<Audio> { | |||
| 774 | died: Arc::new(AtomicBool::new(false)), | 804 | died: Arc::new(AtomicBool::new(false)), |
| 775 | epoch: Arc::new(AtomicU64::new(0)), | 805 | epoch: Arc::new(AtomicU64::new(0)), |
| 776 | }; | 806 | }; |
| 777 | - audio.spawn_feeder(rx).then_some(audio) | 807 | + (audio.spawn_feeder(rx).then_some(audio), None) |
| 778 | } | 808 | } |
| 779 | 809 | ||
| 780 | /// Pours decoded chunks into the device, keeping whatever the ring would not | 810 | /// Pours decoded chunks into the device, keeping whatever the ring would not |
crates/engine/tests/audio_decode.rsmodified+28 -0
| @@ -109,4 +109,32 @@ fn video_only_file_has_no_audio() { | |||
| 109 | .expect("open") | 109 | .expect("open") |
| 110 | .is_none() | 110 | .is_none() |
| 111 | ); | 111 | ); |
| 112 | + assert!( | ||
| 113 | + AudioSession::unsupported(asset("test_baseline.mp4")) | ||
| 114 | + .expect("probe") | ||
| 115 | + .is_none(), | ||
| 116 | + "a file with no audio track is not a complaint" | ||
| 117 | + ); | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// Sound we cannot decode must not be silence we say nothing about: the AC-3 | ||
| 121 | +/// fixture opens as picture-only and the session carries the reason a | ||
| 122 | +/// front-end shows (`Player::open_media`). | ||
| 123 | +#[test] | ||
| 124 | +fn an_undecodable_audio_track_is_named() { | ||
| 125 | + let path = asset("test_ac3.mp4"); | ||
| 126 | + assert!( | ||
| 127 | + AudioSession::open(&path).expect("open").is_none(), | ||
| 128 | + "AC-3 is not decodable here" | ||
| 129 | + ); | ||
| 130 | + let reason = AudioSession::unsupported(&path) | ||
| 131 | + .expect("probe") | ||
| 132 | + .expect("the file has an audio track, so it owes a reason"); | ||
| 133 | + assert!(reason.contains("decode"), "unhelpful reason: {reason}"); | ||
| 134 | + let session = engine::PlaybackSession::open(&path).expect("open for playback"); | ||
| 135 | + assert_eq!( | ||
| 136 | + session.audio_disabled_reason(), | ||
| 137 | + Some(reason.as_str()), | ||
| 138 | + "the session must carry it to the front-end" | ||
| 139 | + ); | ||
| 112 | } | 140 | } |
scripts/gen_fixtures.shmodified+6 -0
| @@ -25,6 +25,12 @@ ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30:duration=4 \ | |||
| 25 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 25 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 26 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 26 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 27 | -c:a aac -b:a 128k assets/test_av2.mp4 | 27 | -c:a aac -b:a 128k assets/test_av2.mp4 |
| 28 | +# Unsupported-audio fixture: an AC-3 track, which we cannot decode at all. The | ||
| 29 | +# file plays as picture with silence, and the point is that it says so. | ||
| 30 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | ||
| 31 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 32 | + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 33 | + -c:a ac3 -b:a 192k assets/test_ac3.mp4 | ||
| 28 | # Mismatch fixture: different resolution and no audio track at all, so import | 34 | # Mismatch fixture: different resolution and no audio track at all, so import |
| 29 | # has something concrete to refuse. | 35 | # has something concrete to refuse. |
| 30 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ | 36 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |