forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

probe_fps.rs129 lines, 4.8 KiBHistoryRawDownload
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
11use std::path::PathBuf;
12use std::time::{Duration, Instant};
13
14fn 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.
97fn 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}