forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfffcda0Tahinli3 months ago397 commits

waveform.rs353 lines, 15.2 KiBHistoryRawDownload
1//! Waveform peaks for drawing a clip's audio: min/max per time bucket, taken
2//! off the same read-only decode path playback uses. Path in, peaks out — no
3//! project model, so a lane rework cannot reach it.
4
5use std::path::{Path, PathBuf};
6use std::sync::mpsc::Receiver;
7use std::thread;
8
9use crate::AudioSession;
10use crate::audio::AudioChunk;
11
12/// `(min, max)` of every sample in each `1 / buckets_per_sec` window of
13/// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
14/// the decoder). Channels are folded together: one envelope per clip, not per
15/// channel.
16///
17/// `Ok(None)` for a file with no audio track — a silent source is valid, not a
18/// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
19/// straddles zero, so silence draws as a flat line.
20///
21/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and
22/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but
23/// it is linear in source length either way: callers cache the result per source
24/// *and stream* — two streams of one file are two different envelopes, and a
25/// cache keyed on the path alone would draw the first one under both. Memory is
26/// flat in it, though: chunks are consumed as they arrive and only the buckets
27/// are kept (2 hours at 10/s is 70k pairs).
28///
29/// A source long enough for it is decoded in **windows on several threads** and
30/// the buckets stitched, which is what that linear cost is divided by:
31/// `open_multi_streams` takes a window per call and seeks to it, and the fold to
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.
37pub fn peaks(
38 path: impl AsRef<Path>,
39 stream: usize,
40 buckets_per_sec: u32,
41) -> crate::Result<Option<Vec<(f32, f32)>>> {
42 peaks_over(path.as_ref(), stream, buckets_per_sec, None)
43}
44
45/// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
46/// for the same envelope by both routes.
47fn 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 {
54 return Ok(None);
55 };
56 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
57 // bucket every few seconds over a long source.
58 let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));
59 let channels = (meta.channels as usize).max(1);
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/// corner-cut: 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.
114fn 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.
127fn 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}
136
137/// One window of one stream, opened the way playback opens it.
138fn 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.
153fn 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();
160 for chunk in rx {
161 if chunk.start_sample >= stop_sample {
162 break;
163 }
164 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
165 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
166 if bucket >= peaks.len() {
167 peaks.resize(bucket + 1, (0.0, 0.0));
168 }
169 let slot = &mut peaks[bucket];
170 for &v in values {
171 let v = v.clamp(-1.0, 1.0);
172 slot.0 = slot.0.min(v);
173 slot.1 = slot.1.max(v);
174 }
175 }
176 }
177 peaks
178}
179
180#[cfg(test)]
181mod tests {
182 use std::path::PathBuf;
183
184 use super::{peaks, peaks_over};
185
186 const BPS: u32 = 10;
187
188 fn asset(name: &str) -> PathBuf {
189 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
190 .join("../../assets")
191 .join(name)
192 }
193
194 #[test]
195 fn peaks_follow_the_1hz_volume_pulse() {
196 let peaks = peaks(asset("test_av.mp4"), 0, BPS)
197 .expect("open")
198 .expect("test_av.mp4 has an audio track");
199 // 5 s of source; the container's tail padding may spill one bucket.
200 let want = 5 * BPS as usize;
201 assert!(
202 peaks.len().abs_diff(want) <= 1,
203 "{} buckets, want {want} +/-1",
204 peaks.len()
205 );
206
207 for (i, &(lo, hi)) in peaks.iter().enumerate() {
208 assert!(
209 (-1.0..=0.0).contains(&lo) && (0.0..=1.0).contains(&hi),
210 "bucket {i} is ({lo}, {hi})"
211 );
212 }
213
214 // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): a full silence every
215 // second at t = 0.75, a full-scale peak at t = 0.25. So every second's
216 // quietest bucket must be the 8th (t in [0.7, 0.8)) — a bucketing that
217 // was off by a scale factor or dropped chunk positions would not line
218 // the dips up second after second.
219 for second in 0..5 {
220 let band = &peaks[second * BPS as usize..][..BPS as usize];
221 let level = |&(lo, hi): &(f32, f32)| hi - lo;
222 let quietest = (0..band.len())
223 .min_by(|&a, &b| level(&band[a]).total_cmp(&level(&band[b])))
224 .expect("non-empty band");
225 assert!(
226 (6..=8).contains(&quietest),
227 "second {second}: dip at bucket {quietest}, want 7 +/-1"
228 );
229 // Depth as a ratio, not an absolute: the fixture's sines sit around
230 // an eighth of full scale, and that is the encoder's business.
231 let (dip, loudest) = (
232 level(&band[quietest]),
233 band.iter().map(level).fold(0.0, f32::max),
234 );
235 assert!(loudest > 0.05, "second {second}: peak level only {loudest}");
236 assert!(
237 dip < 0.1 * loudest,
238 "second {second}: dip {dip} against peak {loudest}, want near silence"
239 );
240 }
241 }
242
243 /// A song's clip draws like any other: this goes through the same
244 /// `open_multi_streams` the timeline plays with, which reads a standalone
245 /// audio file on stream 0 as readily as an mp4's AAC track.
246 #[test]
247 fn a_standalone_audio_file_has_peaks_too() {
248 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)
249 .expect("open")
250 .expect("test_tone.mp3 is audio");
251 let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one
252 assert!(
253 peaks.len().abs_diff(want) <= 2,
254 "{} buckets, want {want} +/-2",
255 peaks.len()
256 );
257 // The fixture carries the A/V one's 1 Hz envelope, so the middle second
258 // has a dip and a peak. As a ratio, and a looser one: the tone sits
259 // around an eighth of full scale and mp3 does not preserve a true zero.
260 let level = |&(lo, hi): &(f32, f32)| hi - lo;
261 let band = &peaks[BPS as usize..][..BPS as usize];
262 let dip = band.iter().map(level).fold(f32::MAX, f32::min);
263 let loudest = band.iter().map(level).fold(0.0, f32::max);
264 assert!(loudest > 0.05, "peak level only {loudest}");
265 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
266 }
267
268 /// The shape the ask came from: a film in an mkv with a 5.1 AAC track,
269 /// which no symphonia decoder takes (`aac: aac too complex`) and which
270 /// therefore reaches the lane through `rusty_aac` and the stereo fold. A
271 /// clip of one draws a waveform like any other -- an envelope that is not
272 /// flat -- rather than the empty band a silent file makes.
273 #[test]
274 fn a_five_one_aac_mkv_draws_an_envelope() {
275 let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
276 .expect("the 5.1 AAC track decodes")
277 .expect("test_hevc10.mkv has an audio track");
278 let want = 2 * BPS as usize; // 2 s of tones
279 assert!(
280 peaks.len().abs_diff(want) <= 2,
281 "{} buckets, want {want} +/-2",
282 peaks.len()
283 );
284 // Six tones, one per channel, folded to stereo: every bucket carries
285 // signal, and a decode that came out silent (or clipped to a rail) is
286 // exactly what this refuses.
287 for (i, &(lo, hi)) in peaks.iter().enumerate() {
288 assert!(
289 (0.02..2.0).contains(&(hi - lo)),
290 "bucket {i} is ({lo}, {hi})"
291 );
292 }
293 }
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
324 #[test]
325 fn video_only_source_has_no_peaks() {
326 assert!(
327 peaks(asset("test_baseline.mp4"), 0, BPS)
328 .expect("open")
329 .is_none()
330 );
331 }
332
333 /// Two streams of one file are two envelopes: the lane draws what the clip
334 /// actually plays, so a cache keyed on the path alone would be a lie the
335 /// user can see. Stream 1 of the fixture is 2 s of 220 Hz mono against
336 /// stream 0's 4-second-long pulsed stereo pair.
337 #[test]
338 fn each_stream_of_a_file_has_its_own_envelope() {
339 let multi = asset("test_multiaudio.mp4");
340 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
341 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
342 assert!(!zero.is_empty() && !one.is_empty());
343 // Bucket for bucket, not merely somewhere: a cache keyed on the path
344 // alone would hand the lane the *first* stream's shape for both, and
345 // that is what this refuses.
346 assert_ne!(zero, one, "both streams drew the same envelope");
347 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
348 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
349 // any other stream rather than being refused.
350 let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2");
351 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
352 }
353}