forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a877f57b2f76ddd2a'

Browse files at this commit

f52d7f5f295b2be520c369aabf8368068a0f3e3cAhmet Kaan GümüşParent: 95cdef23f81ef8
crates/app/src/main.rsmodified+22 -2
@@ -679,6 +679,9 @@ impl Player {
679679 match PlaybackSession::open(path) {
680680 Ok(session) => {
681681 self.fps = session.meta().frame_rate;
682+ // Read before the session moves: a file that plays silent says
683+ // so here or nowhere.
684+ let silent = audio_notice(&session);
682685 self.session = Some(session);
683686 // A fresh session comes up at full volume; the player's own
684687 // setting outlives the file, so it is pushed at every new one.
@@ -687,7 +690,7 @@ impl Player {
687690 self.project_path = project_path(path);
688691 self.name = file_name(path).into();
689692 self.reset_after_reseek();
690- format!("OPENED {}", file_name(path))
693+ format!("OPENED {}{}", file_name(path), silent.unwrap_or_default())
691694 }
692695 Err(e) => format!("OPEN FAILED: {e}"),
693696 }
@@ -733,6 +736,7 @@ impl Player {
733736 let text = match PlaybackSession::open_project(path) {
734737 Ok(session) => {
735738 self.fps = session.meta().frame_rate;
739+ let silent = audio_notice(&session);
736740 // A project is named after itself but still exports beside its
737741 // media: that is the only place an export has ever landed.
738742 self.export_path = export_path(&session.sources()[0]);
@@ -760,7 +764,7 @@ impl Player {
760764 // reaches the screen the way a seek's does. The old picture is
761765 // released by the swap in `pump`, as after any other seek.
762766 self.reset_after_reseek();
763- format!("LOADED {}", file_name(path))
767+ format!("LOADED {}{}", file_name(path), silent.unwrap_or_default())
764768 }
765769 Err(e) => format!("OPEN FAILED: {e}"),
766770 };
@@ -2465,6 +2469,15 @@ fn file_name(path: &std::path::Path) -> String {
24652469 )
24662470 }
24672471
2472+/// The tail an open/load notice grows when the file has sound the engine cannot
2473+/// decode: it plays perfectly, in silence, and that is the one thing the window
2474+/// would otherwise never say (the engine's own word for it, verbatim).
2475+fn audio_notice(session: &PlaybackSession) -> Option<String> {
2476+ session
2477+ .audio_disabled_reason()
2478+ .map(|reason| format!(" — NO AUDIO: {reason}"))
2479+}
2480+
24682481 /// The sources a repaint has not asked about yet. A key that is already there
24692482 /// means "asked", whatever state it is in, which is what stops a decode already
24702483 /// running from being started again by the next of sixty repaints a second.
@@ -3792,6 +3805,13 @@ fn main() {
37923805 notice.get_or_insert(text);
37933806 }
37943807 }
3808+ // A file that plays silent is as much news at launch as it is on a drop, and
3809+ // behind the keymap notice for the same reason an import refusal is.
3810+ if let Some(reason) = session.as_ref().and_then(PlaybackSession::audio_disabled_reason) {
3811+ let text = format!("NO AUDIO: {reason}");
3812+ eprintln!("{text}");
3813+ notice.get_or_insert(text);
3814+ }
37953815 let meta = session.as_ref().map(|session| *session.meta());
37963816 // Beside the media even for a project: an export has never landed anywhere
37973817 // but next to the picture it came from.
crates/engine-hw/src/lib.rsmodified+6 -2
@@ -179,8 +179,12 @@ impl Session {
179179 /// or before it and the pictures in between are dropped unread.
180180 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
181181 let mut session = Self::open(path)?;
182- let sync = session.demuxer.seek_to_sync_at_or_before(target_sample);
183- session.skip = target_sample.saturating_sub(sync);
182+ // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
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;
184188 Some(session)
185189 }
186190
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+35 -5
@@ -259,6 +259,25 @@ impl AudioSession {
259259 Ok(Some((meta, rx)))
260260 }
261261
262+ /// Why [`open`](Self::open) came back silent for a file that *has* sound:
263+ /// `Some(reason)` when there is an audio track and it is not the AAC-LC
264+ /// this decodes (an AC-3 remux, say). `None` when the file is simply silent
265+ /// -- nothing to tell the user there. Header only, and only worth calling
266+ /// once the open has already returned no audio.
267+ pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
268+ let file = File::open(path.as_ref())?;
269+ let size = file.metadata()?.len();
270+ let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
271+ Ok(reader
272+ .tracks()
273+ .values()
274+ .find(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
275+ .map(|t| match t.media_type() {
276+ Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"),
277+ Err(_) => "the audio track is in a codec we cannot decode (AAC-LC only)".to_string(),
278+ }))
279+ }
280+
262281 /// The audio parameters of `path`, for checking an import against the
263282 /// timeline's first source: header only, no decoder and no worker.
264283 /// `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<Box<[u8]>> {
689708 }
690709
691710 /// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`]
692-/// walks; the box's own entry type is `pub(crate)` in mp4 0.14.
693-fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
711+/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. Shared with
712+/// `demux`, which walks a video trak's table with the same two helpers.
713+pub(crate) fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
694714 track
695715 .trak
696716 .mdia
@@ -709,6 +729,18 @@ fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
709729 /// Muxers that write a zero edit list despite a primed stream would leak the
710730 /// priming; upgrade path is preferring the codec delay when it disagrees.
711731 fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 {
732+ edit_media_time(track)
733+ .and_then(|t| scale(t, sample_rate, track.timescale()))
734+ .unwrap_or(DEFAULT_PRIMING)
735+}
736+
737+/// `media_time` of the edit list's first real entry, in the track's own
738+/// timescale: where the presentation starts inside the media. `None` when there
739+/// is no edit list, or only empty entries -- those shift the timeline rather
740+/// than trim the media, and neither track honours that shift (see
741+/// [`priming_samples`]'s ponytail). Shared with `demux`, which owes the video
742+/// track the same trim.
743+pub(crate) fn edit_media_time(track: &Mp4Track) -> Option<u64> {
712744 track
713745 .trak
714746 .edts
@@ -720,8 +752,6 @@ fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 {
720752 .map(|e| e.media_time)
721753 .find(|&t| t != EMPTY_EDIT && t != u64::MAX)
722754 })
723- .and_then(|t| scale(t, sample_rate, track.timescale()))
724- .unwrap_or(DEFAULT_PRIMING)
725755 }
726756
727757 /// `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 {
749779 /// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
750780 /// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
751781 /// carrying the previous entry's delta through the walk.
752-fn packet_at(
782+pub(crate) fn packet_at(
753783 entries: impl IntoIterator<Item = (u32, u32)>,
754784 target_ts: u64,
755785 pre_roll: u32,
crates/engine/src/decode.rsmodified+8 -8
@@ -348,11 +348,11 @@ fn run(
348348 cancel: &AtomicBool,
349349 ) {
350350 let mut decoder = Decoder::new();
351- // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at
352- // a sync sample, so pictures between it and `start_frame` are decoded (the
353- // target frame references them) but never converted or sent.
354- let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1));
355- let mut index = sync - 1;
351+ // Decoding has to restart at a sync sample, so pictures between it and
352+ // `start_frame` are decoded (the target frame references them) but never
353+ // converted or sent. Signed, because the landing sync sample can sit inside
354+ // what the file's edit list trims, i.e. *before* frame 0.
355+ let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
356356
357357 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
358358 // reordering streams need POC-sorted output before display.
@@ -376,12 +376,12 @@ fn run(
376376 break;
377377 }
378378 };
379- if index < start_frame {
379+ if index < i64::from(start_frame) {
380380 index += 1;
381381 continue;
382382 }
383383 let frame = Frame {
384- index,
384+ index: index as u32,
385385 width: yuv.width as u32,
386386 height: yuv.height as u32,
387387 bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
@@ -390,7 +390,7 @@ fn run(
390390 if tx.send(frame).is_err() {
391391 break; // consumer went away
392392 }
393- if index >= end_frame {
393+ if index >= i64::from(end_frame) {
394394 break; // end of the requested range
395395 }
396396 }
crates/engine/src/demux.rsmodified+122 -9
@@ -4,7 +4,9 @@ use std::fs::File;
44 use std::io::BufReader;
55 use std::path::Path;
66
7-use mp4::{MediaType, Mp4Reader};
7+use mp4::{MediaType, Mp4Reader, Mp4Track};
8+
9+use crate::audio::{edit_media_time, packet_at, stts_pairs};
810
911 const START_CODE: [u8; 4] = [0, 0, 0, 1];
1012
@@ -20,6 +22,10 @@ pub struct Demuxer {
2022 reader: Mp4Reader<BufReader<File>>,
2123 track_id: u32,
2224 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,
2329 /// Annex-B SPS+PPS, re-injected ahead of every sync sample.
2430 parameter_sets: Vec<u8>,
2531 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
@@ -44,9 +50,10 @@ impl Demuxer {
4450 let meta = VideoMeta {
4551 width: track.width() as u32,
4652 height: track.height() as u32,
47- frame_rate: track.frame_rate(),
53+ frame_rate: frame_rate(track),
4854 frame_count: 0,
4955 };
56+ let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
5057 let mut parameter_sets = Vec::new();
5158 parameter_sets.extend_from_slice(&START_CODE);
5259 parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
@@ -63,18 +70,24 @@ impl Demuxer {
6370 .unwrap_or_default();
6471
6572 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);
6676 Ok((
6777 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),
6981 ..meta
7082 },
7183 Self {
7284 reader,
7385 track_id,
7486 sample_count,
87+ first_sample,
7588 parameter_sets,
7689 sync_samples,
77- next_sample: 1, // sample ids are 1-based
90+ next_sample,
7891 },
7992 ))
8093 }
@@ -99,16 +112,84 @@ impl Demuxer {
99112 }
100113
101114 /// 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
103- /// from and still reach `sample_id`. Returns the sample it landed on.
104- pub fn seek_to_sync_at_or_before(&mut self, sample_id: u32) -> u32 {
105- let target = sample_id.clamp(1, self.sample_count.max(1));
115+ /// display frame `frame` (0-based), which is the earliest point a decoder can
116+ /// start from and still reach it. Returns the display index of the first
117+ /// picture the caller will now be handed -- *negative* when the landing sync
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));
106124 let chosen = sync_at_or_before(&self.sync_samples, target);
107125 self.next_sample = chosen;
108- chosen
126+ i64::from(chosen) - i64::from(self.first_sample)
109127 }
110128 }
111129
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+
112193 /// Largest entry of the ascending sync table that is `<= sample_id`. An empty
113194 /// table means every sample is a sync sample. When `sample_id` sits before the
114195 /// first sync sample there is nothing decodable earlier, so that one wins.
@@ -168,6 +249,38 @@ mod tests {
168249 assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
169250 }
170251
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+
171284 #[test]
172285 fn rejects_misparse() {
173286 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 {
328328 let bitrate = settings
329329 .bitrate
330330 .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
332- // is finer than any container fps we can read back.
333- let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32;
331+ // The plugin wants an exact rational, and the muxer already picks one
332+ // that is exact at every rate we can read -- `fps * 1000 / 1000` would
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)?;
334336 if !settings.force_sw
335337 && !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)
337339 {
338340 eprintln!("export encoder: hardware (VA-API plugin)");
339341 return Ok(Self::Hw(hw));
@@ -458,8 +460,9 @@ impl ClipDecoder {
458460 struct SwDecoder {
459461 demuxer: Demuxer,
460462 decoder: Decoder,
461- /// Display index of the next picture the decoder will produce.
462- index: u32,
463+ /// Display index of the next picture the decoder will produce. Signed: a
464+ /// sync sample inside what the edit list trims is before frame 0.
465+ index: i64,
463466 start: u32,
464467 frame: Option<YuvFrame>,
465468 }
@@ -469,12 +472,11 @@ impl SwDecoder {
469472 let (_, mut demuxer) = Demuxer::open(path)?;
470473 // Decoding restarts at a sync sample, so pictures between it and the in
471474 // point are decoded (the target references them) and then dropped.
472- // Sample ids are 1-based, frame indices 0-based.
473- let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1));
475+ let index = demuxer.seek_to_sync_at_or_before(start_frame);
474476 Ok(Self {
475477 demuxer,
476478 decoder: Decoder::new(),
477- index: sync - 1,
479+ index,
478480 start: start_frame,
479481 frame: None,
480482 })
@@ -492,7 +494,7 @@ impl SwDecoder {
492494 .decode(&au)
493495 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
494496 let Some(yuv) = decoded else { continue };
495- let wanted = self.index >= self.start;
497+ let wanted = self.index >= i64::from(self.start);
496498 self.index += 1;
497499 if wanted {
498500 self.frame = Some(yuv);
crates/engine/src/mux.rsmodified+96 -11
@@ -10,15 +10,14 @@ use mp4::{
1010 Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType,
1111 };
1212
13-/// 90 kHz is the H.264 convention; frame durations round to well under a
14-/// microsecond of error at every fps we care about.
13+/// 90 kHz is the H.264 convention, and it divides exactly at every *integer*
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`].
1517 const VIDEO_TIMESCALE: u32 = 90_000;
16-/// The same as the video's, deliberately: `mp4` converts every sample duration
17-/// into the movie timescale with an integer division of its own (track.rs:752),
18-/// so a coarser movie clock loses a fraction of a millisecond *per frame* --
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;
18+/// Ticks per frame for a rate the 90 kHz clock cannot express: every NTSC rate
19+/// is `n/1001`, so 1001 ticks a frame makes the timescale a whole `n`.
20+const NTSC_TICKS: u32 = 1001;
2221 /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the
2322 /// per-packet duration is this constant.
2423 const AAC_PACKET_SAMPLES: u32 = 1024;
@@ -78,6 +77,7 @@ impl Mp4Muxer {
7877 return Err("no usable SPS/PPS for the video track".into());
7978 }
8079
80+ let (timescale, frame_duration) = frame_timing(video.frame_rate)?;
8181 let mut writer = Mp4Writer::write_start(
8282 BufWriter::new(File::create(path)?),
8383 &Mp4Config {
@@ -89,12 +89,18 @@ impl Mp4Muxer {
8989 FourCC::from(*b"avc1"),
9090 FourCC::from(*b"mp41"),
9191 ],
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,
9399 },
94100 )?;
95101 writer.add_track(&TrackConfig {
96102 track_type: TrackType::Video,
97- timescale: VIDEO_TIMESCALE,
103+ timescale,
98104 language: "und".to_string(),
99105 media_conf: MediaConfig::AvcConfig(AvcConfig {
100106 width: video.width as u16,
@@ -121,7 +127,7 @@ impl Mp4Muxer {
121127
122128 Ok(Self {
123129 writer,
124- frame_duration: (VIDEO_TIMESCALE as f64 / video.frame_rate).round() as u32,
130+ frame_duration,
125131 has_audio: audio.is_some(),
126132 })
127133 }
@@ -171,6 +177,25 @@ impl Mp4Muxer {
171177 }
172178 }
173179
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(&timescale) {
194+ return Err(format!("frame rate {fps} has no usable timescale").into());
195+ }
196+ Ok((timescale as u32, NTSC_TICKS))
197+}
198+
174199 /// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the
175200 /// unit does not carry both, which the first exported unit always must.
176201 pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> {
@@ -318,6 +343,26 @@ mod tests {
318343 );
319344 }
320345
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+
321366 #[test]
322367 fn create_rejects_unusable_config() {
323368 let out = std::env::temp_dir().join("ve_mux_never_written.mp4");
@@ -437,4 +482,44 @@ mod tests {
437482
438483 std::fs::remove_file(&out).unwrap();
439484 }
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+ }
440525 }
crates/engine/src/playback.rsmodified+37 -7
@@ -101,6 +101,11 @@ pub struct PlaybackSession {
101101 retired: Vec<Worker>,
102102 clock: PlaybackClock,
103103 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>,
104109 /// The edit list. Everything a caller says in seconds is a *timeline*
105110 /// position; only this maps it onto the file.
106111 project: Project,
@@ -123,7 +128,7 @@ impl PlaybackSession {
123128 // `open_worker` rather than `open` purely for the worker handle: the
124129 // field has to exist from the start for the first seek to use it.
125130 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
126- let audio = open_audio(&path);
131+ let (audio, audio_disabled) = open_audio(&path);
127132 let source = match audio {
128133 Some(_) => ClockSource::Audio,
129134 None => ClockSource::Wall,
@@ -139,6 +144,7 @@ impl PlaybackSession {
139144 retired: Vec::new(),
140145 clock: PlaybackClock::new(source),
141146 audio,
147+ audio_disabled,
142148 project,
143149 span,
144150 eos: false,
@@ -207,7 +213,7 @@ impl PlaybackSession {
207213 // only a session's `drop` retires it, so a refusal above this line would
208214 // leave a PipeWire stream and a thread behind for a project that never
209215 // opened. Nothing before it needs the device.
210- let audio = open_audio(&first);
216+ let (audio, audio_disabled) = open_audio(&first);
211217 let mut session = Self {
212218 meta,
213219 frames: stream.frames,
@@ -218,6 +224,7 @@ impl PlaybackSession {
218224 None => ClockSource::Wall,
219225 }),
220226 audio,
227+ audio_disabled,
221228 project,
222229 span,
223230 eos: false,
@@ -235,6 +242,14 @@ impl PlaybackSession {
235242 &self.meta
236243 }
237244
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+
238253 /// The files this timeline plays from, index 0 first -- a caller needs it
239254 /// to name an export or a window after the media rather than the project.
240255 pub fn sources(&self) -> &[PathBuf] {
@@ -751,16 +766,31 @@ fn matches_timeline(
751766 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a
752767 /// track the decoder refuses. Dropping the receiver on the way out stops the
753768 /// 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>) {
755775 let (meta, rx) = match AudioSession::open(path) {
756776 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+ }
758786 Err(e) => {
759787 eprintln!("audio disabled: {e}");
760- return None;
788+ return (None, Some(e.to_string()));
761789 }
762790 };
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+ };
764794 // The stream comes up streaming; a session starts paused, so silence the
765795 // device until `play`. The feeder still fills the ring in the meantime.
766796 ao.set_active(false);
@@ -774,7 +804,7 @@ fn open_audio(path: &Path) -> Option<Audio> {
774804 died: Arc::new(AtomicBool::new(false)),
775805 epoch: Arc::new(AtomicU64::new(0)),
776806 };
777- audio.spawn_feeder(rx).then_some(audio)
807+ (audio.spawn_feeder(rx).then_some(audio), None)
778808 }
779809
780810 /// 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() {
109109 .expect("open")
110110 .is_none()
111111 );
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+ );
112140 }
scripts/gen_fixtures.shmodified+6 -0
@@ -42,6 +42,12 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \
4242 -c:a:1 aac -ar:a:1 22050 -ac:a:1 1 \
4343 -c:a:2 ac3 -ar:a:2 44100 -ac:a:2 2 \
4444 -metadata:s:a:1 language=fra assets/test_multiaudio.mp4
45+# Unsupported-audio fixture: an AC-3 track, which we cannot decode at all. The
46+# file plays as picture with silence, and the point is that it says so.
47+ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
48+ -f lavfi -i "sine=frequency=440:duration=2" \
49+ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
50+ -c:a ac3 -b:a 192k assets/test_ac3.mp4
4551 # Mismatch fixture: different resolution and no audio track at all, so import
4652 # has something concrete to refuse.
4753 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \