forge
Explore
Log in

Don't you dare go Hollow

A film's envelope is read by several hands

Browse files at this commit

50e398828335cba74e684f83446b11ff66f7e86fAhmet Kaan GümüşParent: 7652ada
  • perf
    • a film's envelope is read by several hands
Show full message
⚡ perf(waveform): a film's envelope is read by several hands

Importing a source decodes its whole audio track for the lane's waveform, and
on a film that is the longest thing an import waits for: 22.7 s of one core for
a 2 h 39 m 5.1 E-AC-3 mkv, 3.8 s for a 2 h stereo AAC mp4. It is linear in
length and nothing about it was parallel, though `open_multi_streams` has
always taken a window per call and seeked to it.

So a source long enough to pay for the extra opens is cut into windows -- one
per minute, capped at the machine's cores and at eight -- decoded side by side
and stitched. The first window is the session that was opened to learn the
length, so a split costs `jobs - 1` opens and not `jobs`. Joining is safe
because the fold is min/max into absolutely-numbered buckets: the chunk that
straddles a joint is folded into both windows and cannot be double-counted.

The 2 h 39 m mkv's 22.7 s becomes 4.6 s and the 2 h mp4's 3.8 s becomes 1.2 s,
bucket count identical either way. A clip under two minutes is read exactly as
it was, on the calling thread. `bench waveform <file>` is the metric.
crates/engine/examples/bench.rsmodified+35 -1
@@ -49,6 +49,7 @@ fn main() {
49 "open" => open_bench(&path),49 "open" => open_bench(&path),
50 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),50 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),
51 "scrub" => scrub_bench(&path),51 "scrub" => scrub_bench(&path),
52+ "waveform" => waveform_bench(&path),
52 "export" => {53 "export" => {
53 let seat = args.next().unwrap_or_else(|| usage());54 let seat = args.next().unwrap_or_else(|| usage());
54 let out_dir = PathBuf::from(args.next().unwrap_or_else(|| usage()));55 let out_dir = PathBuf::from(args.next().unwrap_or_else(|| usage()));
@@ -61,7 +62,8 @@ fn main() {
61 fn usage() -> ! {62 fn usage() -> ! {
62 eprintln!(63 eprintln!(
63 "usage: bench open <file>\n bench seek <file> <secs>\n \64 "usage: bench open <file>\n bench seek <file> <secs>\n \
64- bench scrub <file>\n bench export <file> <h264sw|h264hw|av1|hevc> <out_dir>"65+ bench scrub <file>\n bench waveform <file>\n \
66+ bench export <file> <h264sw|h264hw|av1|hevc> <out_dir>"
65 );67 );
66 std::process::exit(2)68 std::process::exit(2)
67 }69 }
@@ -247,6 +249,38 @@ fn seek_bench(path: &Path, secs: f64) {
247 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);249 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);
248 }250 }
249 251
252+// ---------------------------------------------------------------- waveform
253+
254+/// What a lane waits for before it has an envelope: one whole
255+/// [`engine::waveform::peaks`] of the file's first audio stream, at the app's
256+/// own ten buckets a second. Cold once, then warm -- the mkv sidecar index is
257+/// written on the first open, so the two are different questions.
258+fn waveform_bench(path: &Path) {
259+ const BPS: u32 = 10;
260+ evict(path);
261+ let mut cold = Vec::new();
262+ let mut warm = Vec::new();
263+ let mut note = String::new();
264+ for i in 0..3 {
265+ let t = Instant::now();
266+ match engine::waveform::peaks(path, 0, BPS) {
267+ Ok(peaks) => {
268+ let ms = t.elapsed().as_secs_f64() * 1000.0;
269+ if i == 0 { cold.push(ms) } else { warm.push(ms) }
270+ if note.is_empty() {
271+ note = format!("{} buckets", peaks.map_or(0, |p| p.len()));
272+ }
273+ }
274+ Err(e) => {
275+ row(path, "waveform_cold", "ms", &[], &format!("FAIL({e})"));
276+ return;
277+ }
278+ }
279+ }
280+ row(path, "waveform_cold", "ms", &cold, &note);
281+ row(path, "waveform_warm", "ms", &warm, &note);
282+}
283+
250 // ------------------------------------------------------------------- scrub284 // ------------------------------------------------------------------- scrub
251 285
252 /// Twenty scrub steps: the playhead dragged across a quarter of the film, one286 /// Twenty scrub steps: the playhead dragged across a quarter of the film, one
crates/engine/src/waveform.rsmodified+157 -12
@@ -2,9 +2,12 @@
2 //! off the same read-only decode path playback uses. Path in, peaks out — no2 //! off the same read-only decode path playback uses. Path in, peaks out — no
3 //! project model, so a lane rework cannot reach it.3 //! project model, so a lane rework cannot reach it.
4 4
5-use std::path::Path;5+use std::path::{Path, PathBuf};
6+use std::sync::mpsc::Receiver;
7+use std::thread;
6 8
7 use crate::AudioSession;9 use crate::AudioSession;
10+use crate::audio::AudioChunk;
8 11
9 /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of12 /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of
10 /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by13 /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
@@ -23,28 +26,141 @@ use crate::AudioSession;
23 /// flat in it, though: chunks are consumed as they arrive and only the buckets26 /// flat in it, though: chunks are consumed as they arrive and only the buckets
24 /// are kept (2 hours at 10/s is 70k pairs).27 /// are kept (2 hours at 10/s is 70k pairs).
25 ///28 ///
26-/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film29+/// A source long enough for it is decoded in **windows on several threads** and
27-/// before its lane has a waveform. The upgrade path is decoding the source in30+/// the buckets stitched, which is what that linear cost is divided by:
28-/// segments on several threads — `open_multi_streams` already takes a window per31+/// `open_multi_streams` takes a window per call and seeks to it, and the fold to
29-/// call — and stitching the buckets, which the fold to one envelope makes safe.32+/// one envelope is what makes the join safe — a bucket two windows straddle is
33+/// folded from both, and min/max cannot double-count. A film that cost 23 s of
34+/// one core costs about a quarter of that; a clip short enough that the extra
35+/// opens would outweigh the decode they save ([`jobs_for`]) is read exactly as
36+/// it always was, on this thread.
30 pub fn peaks(37 pub fn peaks(
31 path: impl AsRef<Path>,38 path: impl AsRef<Path>,
32 stream: usize,39 stream: usize,
33 buckets_per_sec: u32,40 buckets_per_sec: u32,
34 ) -> crate::Result<Option<Vec<(f32, f32)>>> {41 ) -> crate::Result<Option<Vec<(f32, f32)>>> {
35- let sources = [(path.as_ref().to_path_buf(), stream)];42+ peaks_over(path.as_ref(), stream, buckets_per_sec, None)
36- let Some((meta, rx)) =43+}
37- AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?44+
38- else {45+/// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
46+/// for the same envelope by both routes.
47+fn peaks_over(
48+ path: &Path,
49+ stream: usize,
50+ buckets_per_sec: u32,
51+ jobs: Option<usize>,
52+) -> crate::Result<Option<Vec<(f32, f32)>>> {
53+ let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else {
39 return Ok(None);54 return Ok(None);
40 };55 };
41 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a56 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
42 // bucket every few seconds over a long source.57 // bucket every few seconds over a long source.
43 let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));58 let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));
44 let channels = (meta.channels as usize).max(1);59 let channels = (meta.channels as usize).max(1);
45- let mut peaks: Vec<(f32, f32)> = Vec::new();60+ let rate = f64::from(meta.sample_rate.max(1));
61+ // A track whose length the container does not state cannot be cut into
62+ // windows at all: `secs` is 0 and the whole of it is read on this thread,
63+ // exactly as it was before there was a split.
64+ let secs = meta.total_samples.unwrap_or(0) as f64 / rate;
65+ let jobs = jobs.unwrap_or_else(|| jobs_for(secs)).max(1);
66+ if jobs == 1 {
67+ return Ok(Some(fold(rx, per_bucket, channels, u64::MAX)));
68+ }
69+ let window = secs / jobs as f64;
70+ // Every other window is spawned before this thread folds its own, so they
71+ // all decode side by side; each carries its own error home rather than
72+ // taking a worker down.
73+ let rest: Vec<_> = (1..jobs)
74+ .map(|k| {
75+ let path = path.to_path_buf();
76+ let start = window * k as f64;
77+ // The last window runs to the end of the file: `total_samples` is
78+ // the container's word for a length, and a tail past it must still
79+ // be drawn.
80+ let end = match k + 1 == jobs {
81+ true => f64::INFINITY,
82+ false => window * (k + 1) as f64,
83+ };
84+ thread::Builder::new()
85+ .name("waveform".into())
86+ .spawn(move || -> crate::Result<Vec<(f32, f32)>> {
87+ match open_window(&path, stream, start, end)? {
88+ Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)),
89+ None => Ok(Vec::new()),
90+ }
91+ })
92+ })
93+ .collect::<Result<_, _>>()?;
94+ // This window ends where the next one's decoder was told to start, by the
95+ // same arithmetic, so the two meet with no gap; the chunk that straddles the
96+ // joint is folded into both and min/max does not double-count.
97+ let mut peaks = fold(rx, per_bucket, channels, (window * rate) as u64);
98+ for handle in rest {
99+ let part = handle.join().map_err(|_| "waveform worker panicked")??;
100+ merge(&mut peaks, &part);
101+ }
102+ Ok(Some(peaks))
103+}
104+
105+/// How many threads a source of `secs` is worth splitting across: one below two
106+/// minutes of sound, where the extra opens (a Matroska's is a cluster walk) cost
107+/// more than the decode they would save, and never more than the machine has —
108+/// nor more than a handful, since an import asks this of every source at once.
109+///
110+/// ponytail: that last clause is a ceiling and not a bound — a library import of
111+/// twenty films runs as many of these as the background executor has threads,
112+/// each with eight of its own. The upgrade path is one pool the waveforms share,
113+/// which is also where a "visible range first" order would live.
114+fn jobs_for(secs: f64) -> usize {
115+ const PER_JOB_SECS: f64 = 60.0;
116+ const CEILING: usize = 8;
117+ if !secs.is_finite() || secs < 2.0 * PER_JOB_SECS {
118+ return 1;
119+ }
120+ let cores = thread::available_parallelism().map_or(1, |n| n.get());
121+ ((secs / PER_JOB_SECS) as usize).min(cores).min(CEILING).max(1)
122+}
123+
124+/// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,
125+/// so this is a straight min/max: an empty bucket is `(0.0, 0.0)` and every
126+/// value is clamped to `[-1.0, 1.0]`, which makes the empty pair the identity.
127+fn merge(peaks: &mut Vec<(f32, f32)>, part: &[(f32, f32)]) {
128+ if part.len() > peaks.len() {
129+ peaks.resize(part.len(), (0.0, 0.0));
130+ }
131+ for (slot, &(lo, hi)) in peaks.iter_mut().zip(part) {
132+ slot.0 = slot.0.min(lo);
133+ slot.1 = slot.1.max(hi);
134+ }
135+}
46 136
137+/// One window of one stream, opened the way playback opens it.
138+fn open_window(
139+ path: &Path,
140+ stream: usize,
141+ start_secs: f64,
142+ end_secs: f64,
143+) -> crate::Result<Option<(crate::AudioMeta, Receiver<AudioChunk>)>> {
144+ let sources = [(PathBuf::from(path), stream)];
145+ AudioSession::open_multi_streams(&sources, &[(Some(0), start_secs, end_secs)])
146+}
147+
148+/// Min/max per bucket of everything `rx` carries, at absolute bucket positions:
149+/// `start_sample` counts from the source's own first audible sample whatever
150+/// window the session was opened at. Stops at the first chunk beginning at or
151+/// past `stop_sample`, and dropping the receiver there is what stops that
152+/// window's decoder.
153+fn fold(
154+ rx: Receiver<AudioChunk>,
155+ per_bucket: f64,
156+ channels: usize,
157+ stop_sample: u64,
158+) -> Vec<(f32, f32)> {
159+ let mut peaks: Vec<(f32, f32)> = Vec::new();
47 for chunk in rx {160 for chunk in rx {
161+ if chunk.start_sample >= stop_sample {
162+ break;
163+ }
48 for (frame, values) in chunk.samples.chunks(channels).enumerate() {164 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
49 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;165 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
50 if bucket >= peaks.len() {166 if bucket >= peaks.len() {
@@ -58,14 +174,14 @@ pub fn peaks(
58 }174 }
59 }175 }
60 }176 }
61- Ok(Some(peaks))177+ peaks
62 }178 }
63 179
64 #[cfg(test)]180 #[cfg(test)]
65 mod tests {181 mod tests {
66 use std::path::PathBuf;182 use std::path::PathBuf;
67 183
68- use super::peaks;184+ use super::{peaks, peaks_over};
69 185
70 const BPS: u32 = 10;186 const BPS: u32 = 10;
71 187
@@ -176,6 +292,35 @@ mod tests {
176 }292 }
177 }293 }
178 294
295+ /// The split is an optimisation and nothing else: four windows decoded side
296+ /// by side draw the very envelope the single-threaded walk draws, bucket for
297+ /// bucket. The joints are where a window that started a sample late or
298+ /// stopped a chunk early would show, so this is the check that a film's
299+ /// waveform is still the film's.
300+ #[test]
301+ fn a_split_decode_draws_the_same_envelope() {
302+ let file = asset("test_av.mp4");
303+ let whole = peaks_over(&file, 0, BPS, Some(1))
304+ .expect("open")
305+ .expect("test_av.mp4 has an audio track");
306+ let split = peaks_over(&file, 0, BPS, Some(4))
307+ .expect("open")
308+ .expect("test_av.mp4 has an audio track");
309+ assert_eq!(whole.len(), split.len(), "the split lost or grew buckets");
310+ // Not bit-equality: a window seeks into the middle of an AAC stream and
311+ // its filterbank is primed from a preceding packet rather than carried
312+ // over, so a bucket can land a ten-thousandth away. A lane is drawn a
313+ // hundred pixels tall, where that is a thousandth of a pixel; a window
314+ // that started late or stopped early is off by whole tenths and is what
315+ // this catches.
316+ for (i, (w, s)) in whole.iter().zip(&split).enumerate() {
317+ assert!(
318+ (w.0 - s.0).abs() < 1e-3 && (w.1 - s.1).abs() < 1e-3,
319+ "bucket {i}: whole {w:?}, split {s:?}"
320+ );
321+ }
322+ }
323+
179 #[test]324 #[test]
180 fn video_only_source_has_no_peaks() {325 fn video_only_source_has_no_peaks() {
181 assert!(326 assert!(