Merge branch 'worktree-agent-a877f57b2f76ddd2a'
Browse files at this commit11 changed files +501 -54
- 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 +35 -5
- 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
| @@ -679,6 +679,9 @@ impl Player { | ||
| 679 | 679 | match PlaybackSession::open(path) { |
| 680 | 680 | Ok(session) => { |
| 681 | 681 | 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); | |
| 682 | 685 | self.session = Some(session); |
| 683 | 686 | // A fresh session comes up at full volume; the player's own |
| 684 | 687 | // setting outlives the file, so it is pushed at every new one. |
| @@ -687,7 +690,7 @@ impl Player { | ||
| 687 | 690 | self.project_path = project_path(path); |
| 688 | 691 | self.name = file_name(path).into(); |
| 689 | 692 | self.reset_after_reseek(); |
| 690 | - format!("OPENED {}", file_name(path)) | |
| 693 | + format!("OPENED {}{}", file_name(path), silent.unwrap_or_default()) | |
| 691 | 694 | } |
| 692 | 695 | Err(e) => format!("OPEN FAILED: {e}"), |
| 693 | 696 | } |
| @@ -733,6 +736,7 @@ impl Player { | ||
| 733 | 736 | let text = match PlaybackSession::open_project(path) { |
| 734 | 737 | Ok(session) => { |
| 735 | 738 | self.fps = session.meta().frame_rate; |
| 739 | + let silent = audio_notice(&session); | |
| 736 | 740 | // A project is named after itself but still exports beside its |
| 737 | 741 | // media: that is the only place an export has ever landed. |
| 738 | 742 | self.export_path = export_path(&session.sources()[0]); |
| @@ -760,7 +764,7 @@ impl Player { | ||
| 760 | 764 | // reaches the screen the way a seek's does. The old picture is |
| 761 | 765 | // released by the swap in `pump`, as after any other seek. |
| 762 | 766 | self.reset_after_reseek(); |
| 763 | - format!("LOADED {}", file_name(path)) | |
| 767 | + format!("LOADED {}{}", file_name(path), silent.unwrap_or_default()) | |
| 764 | 768 | } |
| 765 | 769 | Err(e) => format!("OPEN FAILED: {e}"), |
| 766 | 770 | }; |
| @@ -2465,6 +2469,15 @@ fn file_name(path: &std::path::Path) -> String { | ||
| 2465 | 2469 | ) |
| 2466 | 2470 | } |
| 2467 | 2471 | |
| 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 | + | |
| 2468 | 2481 | /// The sources a repaint has not asked about yet. A key that is already there |
| 2469 | 2482 | /// means "asked", whatever state it is in, which is what stops a decode already |
| 2470 | 2483 | /// running from being started again by the next of sixty repaints a second. |
| @@ -3792,6 +3805,13 @@ fn main() { | ||
| 3792 | 3805 | notice.get_or_insert(text); |
| 3793 | 3806 | } |
| 3794 | 3807 | } |
| 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 | + } | |
| 3795 | 3815 | let meta = session.as_ref().map(|session| *session.meta()); |
| 3796 | 3816 | // Beside the media even for a project: an export has never landed anywhere |
| 3797 | 3817 | // but next to the picture it came from. |
crates/engine-hw/src/lib.rsmodified+6 -2
| @@ -179,8 +179,12 @@ impl Session { | ||
| 179 | 179 | /// or before it and the pictures in between are dropped unread. |
| 180 | 180 | fn open_at(path: &Path, target_sample: u32) -> Option<Self> { |
| 181 | 181 | 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; | |
| 184 | 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+35 -5
| @@ -259,6 +259,25 @@ impl AudioSession { | ||
| 259 | 259 | Ok(Some((meta, rx))) |
| 260 | 260 | } |
| 261 | 261 | |
| 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 | + | |
| 262 | 281 | /// The audio parameters of `path`, for checking an import against the |
| 263 | 282 | /// timeline's first source: header only, no decoder and no worker. |
| 264 | 283 | /// `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]>> { | ||
| 689 | 708 | } |
| 690 | 709 | |
| 691 | 710 | /// 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)> + '_ { | |
| 694 | 714 | track |
| 695 | 715 | .trak |
| 696 | 716 | .mdia |
| @@ -709,6 +729,18 @@ fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ { | ||
| 709 | 729 | /// Muxers that write a zero edit list despite a primed stream would leak the |
| 710 | 730 | /// priming; upgrade path is preferring the codec delay when it disagrees. |
| 711 | 731 | 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> { | |
| 712 | 744 | track |
| 713 | 745 | .trak |
| 714 | 746 | .edts |
| @@ -720,8 +752,6 @@ fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { | ||
| 720 | 752 | .map(|e| e.media_time) |
| 721 | 753 | .find(|&t| t != EMPTY_EDIT && t != u64::MAX) |
| 722 | 754 | }) |
| 723 | - .and_then(|t| scale(t, sample_rate, track.timescale())) | |
| 724 | - .unwrap_or(DEFAULT_PRIMING) | |
| 725 | 755 | } |
| 726 | 756 | |
| 727 | 757 | /// `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 { | ||
| 749 | 779 | /// packets of an entry boundary gets less pre-roll. AAC packets are uniformly |
| 750 | 780 | /// 1024 frames (one entry per track), so this cannot fire here; upgrade path is |
| 751 | 781 | /// carrying the previous entry's delta through the walk. |
| 752 | -fn packet_at( | |
| 782 | +pub(crate) fn packet_at( | |
| 753 | 783 | entries: impl IntoIterator<Item = (u32, u32)>, |
| 754 | 784 | target_ts: u64, |
| 755 | 785 | pre_roll: u32, |
crates/engine/src/decode.rsmodified+8 -8
| @@ -348,11 +348,11 @@ fn run( | ||
| 348 | 348 | cancel: &AtomicBool, |
| 349 | 349 | ) { |
| 350 | 350 | 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); | |
| 356 | 356 | |
| 357 | 357 | // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); |
| 358 | 358 | // reordering streams need POC-sorted output before display. |
| @@ -376,12 +376,12 @@ fn run( | ||
| 376 | 376 | break; |
| 377 | 377 | } |
| 378 | 378 | }; |
| 379 | - if index < start_frame { | |
| 379 | + if index < i64::from(start_frame) { | |
| 380 | 380 | index += 1; |
| 381 | 381 | continue; |
| 382 | 382 | } |
| 383 | 383 | let frame = Frame { |
| 384 | - index, | |
| 384 | + index: index as u32, | |
| 385 | 385 | width: yuv.width as u32, |
| 386 | 386 | height: yuv.height as u32, |
| 387 | 387 | bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), |
| @@ -390,7 +390,7 @@ fn run( | ||
| 390 | 390 | if tx.send(frame).is_err() { |
| 391 | 391 | break; // consumer went away |
| 392 | 392 | } |
| 393 | - if index >= end_frame { | |
| 393 | + if index >= i64::from(end_frame) { | |
| 394 | 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 | 4 | use std::io::BufReader; |
| 5 | 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 | 11 | const START_CODE: [u8; 4] = [0, 0, 0, 1]; |
| 10 | 12 | |
| @@ -20,6 +22,10 @@ pub struct Demuxer { | ||
| 20 | 22 | reader: Mp4Reader<BufReader<File>>, |
| 21 | 23 | track_id: u32, |
| 22 | 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 | 29 | /// Annex-B SPS+PPS, re-injected ahead of every sync sample. |
| 24 | 30 | parameter_sets: Vec<u8>, |
| 25 | 31 | /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box |
| @@ -44,9 +50,10 @@ impl Demuxer { | ||
| 44 | 50 | let meta = VideoMeta { |
| 45 | 51 | width: track.width() as u32, |
| 46 | 52 | height: track.height() as u32, |
| 47 | - frame_rate: track.frame_rate(), | |
| 53 | + frame_rate: frame_rate(track), | |
| 48 | 54 | frame_count: 0, |
| 49 | 55 | }; |
| 56 | + let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); | |
| 50 | 57 | let mut parameter_sets = Vec::new(); |
| 51 | 58 | parameter_sets.extend_from_slice(&START_CODE); |
| 52 | 59 | parameter_sets.extend_from_slice(track.sequence_parameter_set()?); |
| @@ -63,18 +70,24 @@ impl Demuxer { | ||
| 63 | 70 | .unwrap_or_default(); |
| 64 | 71 | |
| 65 | 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 | 76 | Ok(( |
| 67 | 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 | 81 | ..meta |
| 70 | 82 | }, |
| 71 | 83 | Self { |
| 72 | 84 | reader, |
| 73 | 85 | track_id, |
| 74 | 86 | sample_count, |
| 87 | + first_sample, | |
| 75 | 88 | parameter_sets, |
| 76 | 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 | 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 | |
| 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)); | |
| 106 | 124 | let chosen = sync_at_or_before(&self.sync_samples, target); |
| 107 | 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 | 193 | /// Largest entry of the ascending sync table that is `<= sample_id`. An empty |
| 113 | 194 | /// table means every sample is a sync sample. When `sample_id` sits before the |
| 114 | 195 | /// first sync sample there is nothing decodable earlier, so that one wins. |
| @@ -168,6 +249,38 @@ mod tests { | ||
| 168 | 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 | 284 | #[test] |
| 172 | 285 | fn rejects_misparse() { |
| 173 | 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 | 328 | let bitrate = settings |
| 329 | 329 | .bitrate |
| 330 | 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 | |
| 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)?; | |
| 334 | 336 | if !settings.force_sw |
| 335 | 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 | 340 | eprintln!("export encoder: hardware (VA-API plugin)"); |
| 339 | 341 | return Ok(Self::Hw(hw)); |
| @@ -458,8 +460,9 @@ impl ClipDecoder { | ||
| 458 | 460 | struct SwDecoder { |
| 459 | 461 | demuxer: Demuxer, |
| 460 | 462 | 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, | |
| 463 | 466 | start: u32, |
| 464 | 467 | frame: Option<YuvFrame>, |
| 465 | 468 | } |
| @@ -469,12 +472,11 @@ impl SwDecoder { | ||
| 469 | 472 | let (_, mut demuxer) = Demuxer::open(path)?; |
| 470 | 473 | // Decoding restarts at a sync sample, so pictures between it and the in |
| 471 | 474 | // 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); | |
| 474 | 476 | Ok(Self { |
| 475 | 477 | demuxer, |
| 476 | 478 | decoder: Decoder::new(), |
| 477 | - index: sync - 1, | |
| 479 | + index, | |
| 478 | 480 | start: start_frame, |
| 479 | 481 | frame: None, |
| 480 | 482 | }) |
| @@ -492,7 +494,7 @@ impl SwDecoder { | ||
| 492 | 494 | .decode(&au) |
| 493 | 495 | .map_err(|e| format!("decode at picture {}: {e}", self.index))?; |
| 494 | 496 | let Some(yuv) = decoded else { continue }; |
| 495 | - let wanted = self.index >= self.start; | |
| 497 | + let wanted = self.index >= i64::from(self.start); | |
| 496 | 498 | self.index += 1; |
| 497 | 499 | if wanted { |
| 498 | 500 | self.frame = Some(yuv); |
crates/engine/src/mux.rsmodified+96 -11
| @@ -10,15 +10,14 @@ use mp4::{ | ||
| 10 | 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 | |
| 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`]. | |
| 15 | 17 | 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; | |
| 22 | 21 | /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the |
| 23 | 22 | /// per-packet duration is this constant. |
| 24 | 23 | const AAC_PACKET_SAMPLES: u32 = 1024; |
| @@ -78,6 +77,7 @@ impl Mp4Muxer { | ||
| 78 | 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 | 81 | let mut writer = Mp4Writer::write_start( |
| 82 | 82 | BufWriter::new(File::create(path)?), |
| 83 | 83 | &Mp4Config { |
| @@ -89,12 +89,18 @@ impl Mp4Muxer { | ||
| 89 | 89 | FourCC::from(*b"avc1"), |
| 90 | 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 | 101 | writer.add_track(&TrackConfig { |
| 96 | 102 | track_type: TrackType::Video, |
| 97 | - timescale: VIDEO_TIMESCALE, | |
| 103 | + timescale, | |
| 98 | 104 | language: "und".to_string(), |
| 99 | 105 | media_conf: MediaConfig::AvcConfig(AvcConfig { |
| 100 | 106 | width: video.width as u16, |
| @@ -121,7 +127,7 @@ impl Mp4Muxer { | ||
| 121 | 127 | |
| 122 | 128 | Ok(Self { |
| 123 | 129 | writer, |
| 124 | - frame_duration: (VIDEO_TIMESCALE as f64 / video.frame_rate).round() as u32, | |
| 130 | + frame_duration, | |
| 125 | 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 | 199 | /// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the |
| 175 | 200 | /// unit does not carry both, which the first exported unit always must. |
| 176 | 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 | 366 | #[test] |
| 322 | 367 | fn create_rejects_unusable_config() { |
| 323 | 368 | let out = std::env::temp_dir().join("ve_mux_never_written.mp4"); |
| @@ -437,4 +482,44 @@ mod tests { | ||
| 437 | 482 | |
| 438 | 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 | 101 | retired: Vec<Worker>, |
| 102 | 102 | clock: PlaybackClock, |
| 103 | 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 | 109 | /// The edit list. Everything a caller says in seconds is a *timeline* |
| 105 | 110 | /// position; only this maps it onto the file. |
| 106 | 111 | project: Project, |
| @@ -123,7 +128,7 @@ impl PlaybackSession { | ||
| 123 | 128 | // `open_worker` rather than `open` purely for the worker handle: the |
| 124 | 129 | // field has to exist from the start for the first seek to use it. |
| 125 | 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 | 132 | let source = match audio { |
| 128 | 133 | Some(_) => ClockSource::Audio, |
| 129 | 134 | None => ClockSource::Wall, |
| @@ -139,6 +144,7 @@ impl PlaybackSession { | ||
| 139 | 144 | retired: Vec::new(), |
| 140 | 145 | clock: PlaybackClock::new(source), |
| 141 | 146 | audio, |
| 147 | + audio_disabled, | |
| 142 | 148 | project, |
| 143 | 149 | span, |
| 144 | 150 | eos: false, |
| @@ -207,7 +213,7 @@ impl PlaybackSession { | ||
| 207 | 213 | // only a session's `drop` retires it, so a refusal above this line would |
| 208 | 214 | // leave a PipeWire stream and a thread behind for a project that never |
| 209 | 215 | // opened. Nothing before it needs the device. |
| 210 | - let audio = open_audio(&first); | |
| 216 | + let (audio, audio_disabled) = open_audio(&first); | |
| 211 | 217 | let mut session = Self { |
| 212 | 218 | meta, |
| 213 | 219 | frames: stream.frames, |
| @@ -218,6 +224,7 @@ impl PlaybackSession { | ||
| 218 | 224 | None => ClockSource::Wall, |
| 219 | 225 | }), |
| 220 | 226 | audio, |
| 227 | + audio_disabled, | |
| 221 | 228 | project, |
| 222 | 229 | span, |
| 223 | 230 | eos: false, |
| @@ -235,6 +242,14 @@ impl PlaybackSession { | ||
| 235 | 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 | 253 | /// The files this timeline plays from, index 0 first -- a caller needs it |
| 239 | 254 | /// to name an export or a window after the media rather than the project. |
| 240 | 255 | pub fn sources(&self) -> &[PathBuf] { |
| @@ -751,16 +766,31 @@ fn matches_timeline( | ||
| 751 | 766 | /// `None` for a silent session -- no audio track, no plugin, no daemon, or a |
| 752 | 767 | /// track the decoder refuses. Dropping the receiver on the way out stops the |
| 753 | 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 | 775 | let (meta, rx) = match AudioSession::open(path) { |
| 756 | 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 | 786 | Err(e) => { |
| 759 | 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 | 794 | // The stream comes up streaming; a session starts paused, so silence the |
| 765 | 795 | // device until `play`. The feeder still fills the ring in the meantime. |
| 766 | 796 | ao.set_active(false); |
| @@ -774,7 +804,7 @@ fn open_audio(path: &Path) -> Option<Audio> { | ||
| 774 | 804 | died: Arc::new(AtomicBool::new(false)), |
| 775 | 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 | 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 | 109 | .expect("open") |
| 110 | 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
| @@ -42,6 +42,12 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ | ||
| 42 | 42 | -c:a:1 aac -ar:a:1 22050 -ac:a:1 1 \ |
| 43 | 43 | -c:a:2 ac3 -ar:a:2 44100 -ac:a:2 2 \ |
| 44 | 44 | -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 | |
| 45 | 51 | # Mismatch fixture: different resolution and no audio track at all, so import |
| 46 | 52 | # has something concrete to refuse. |
| 47 | 53 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |