forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

probe_fps.rs144 lines, 5.4 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> [secs] [play] [play_secs]`
6//!
7//! With `play` it also seeks there, plays `play_secs` (two by default) against the
8//! real audio device and reports the skew between the picture on screen and the
9//! master 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 // mp4 only: a Matroska file has no `moov` and reading one out of it is a
40 // panic, which used to make this tool unusable on exactly the films in a
41 // library that the demuxer most needs checking against.
42 if !engine::demux::is_matroska(&path) {
43 mp4_boxes(&path);
44 }
45 match engine::AudioSession::open(&path) {
46 Ok(Some((audio, _))) => println!(" audio: {} Hz {} ch", audio.sample_rate, audio.channels),
47 Ok(None) => println!(
48 " audio: none usable ({:?})",
49 engine::AudioSession::unsupported(&path)
50 ),
51 Err(e) => println!(" audio: refused ({e})"),
52 }
53
54 // `play [secs]`: how long to play for, two seconds by default.
55 if args.next().is_some_and(|a| a == *"play") {
56 let seconds = args
57 .next()
58 .and_then(|s| s.to_str().and_then(|s| s.parse().ok()))
59 .unwrap_or(2.0);
60 play(&path, secs, meta.frame_rate, seconds);
61 }
62}
63
64/// The edit list and sample counts of an mp4, per track.
65fn mp4_boxes(path: &std::path::Path) {
66 let file = std::fs::File::open(path).expect("open");
67 let size = file.metadata().expect("stat").len();
68 let reader =
69 mp4::Mp4Reader::read_header(std::io::BufReader::new(file), size).expect("read header");
70 for (id, track) in reader.tracks() {
71 let elst: Vec<(u64, u64)> = track
72 .trak
73 .edts
74 .as_ref()
75 .and_then(|e| e.elst.as_ref())
76 .map(|e| {
77 e.entries
78 .iter()
79 .map(|e| (e.segment_duration, e.media_time))
80 .collect()
81 })
82 .unwrap_or_default();
83 let ctts: Vec<(u32, u32)> = track
84 .trak
85 .mdia
86 .minf
87 .stbl
88 .ctts
89 .as_ref()
90 .map(|c| {
91 c.entries
92 .iter()
93 .take(3)
94 .map(|e| (e.sample_count, e.sample_offset as u32))
95 .collect()
96 })
97 .unwrap_or_default();
98 println!(" ctts (first entries): {ctts:?}");
99 println!(
100 " track {id}: {:?}, timescale {}, {} samples, elst (segment_duration, media_time) {elst:?}",
101 track.media_type(),
102 track.timescale(),
103 track.sample_count(),
104 );
105 }
106}
107
108/// Seeks in, plays two seconds against the real device, and reports where the
109/// picture stands against the master clock. The clock counts audio samples, so
110/// `frame / fps - clock` *is* the A/V skew: a truncated frame rate shows up
111/// here as tens of seconds of it, ten minutes in.
112fn play(path: &std::path::Path, secs: f64, fps: f64, seconds: f64) {
113 let mut session = engine::PlaybackSession::open(path).expect("open for playback");
114 session.seek(secs);
115 session.play();
116 let mut last = None;
117 let mut held: Option<u32> = None;
118 let deadline = Instant::now() + Duration::from_secs_f64(seconds);
119 while Instant::now() < deadline {
120 session.tick();
121 // The app's own drop-when-behind rule (`Player::pump`): show every frame
122 // already due and hold the first one that is not, or this would measure
123 // how far the decoder runs ahead instead of what is on screen.
124 let target = session.now() * fps;
125 while let Some(index) = held.take().or_else(|| session.try_frame().map(|f| f.index)) {
126 if f64::from(index) > target {
127 held = Some(index);
128 break;
129 }
130 last = Some(index);
131 }
132 std::thread::sleep(Duration::from_millis(4));
133 }
134 let now = session.now();
135 let Some(index) = last else {
136 println!(" played from {secs}s: no frame arrived, clock at {now:.3}s");
137 return;
138 };
139 let media = f64::from(index) / fps;
140 println!(
141 " played from {secs}s: clock {now:.3}s, frame {index} = media {media:.3}s, skew {:+.3}s",
142 media - now
143 );
144}