forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

waveform.rs173 lines, 7.1 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;
6
7use crate::AudioSession;
8
9/// `(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 by
11/// the decoder). Channels are folded together: one envelope per clip, not per
12/// channel.
13///
14/// `Ok(None)` for a file with no audio track — a silent source is valid, not a
15/// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
16/// straddles zero, so silence draws as a flat line.
17///
18/// Decoding the whole file runs at ~1700x realtime, but it is still linear in
19/// source length: callers cache the result per source *and stream* — two
20/// streams of one file are two different envelopes, and a cache keyed on the
21/// path alone would draw the first one under both.
22pub fn peaks(
23 path: impl AsRef<Path>,
24 stream: usize,
25 buckets_per_sec: u32,
26) -> crate::Result<Option<Vec<(f32, f32)>>> {
27 let sources = [(path.as_ref().to_path_buf(), stream)];
28 let Some((meta, rx)) =
29 AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
30 else {
31 return Ok(None);
32 };
33 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
34 // bucket every few seconds over a long source.
35 let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));
36 let channels = (meta.channels as usize).max(1);
37 let mut peaks: Vec<(f32, f32)> = Vec::new();
38
39 for chunk in rx {
40 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
41 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
42 if bucket >= peaks.len() {
43 peaks.resize(bucket + 1, (0.0, 0.0));
44 }
45 let slot = &mut peaks[bucket];
46 for &v in values {
47 let v = v.clamp(-1.0, 1.0);
48 slot.0 = slot.0.min(v);
49 slot.1 = slot.1.max(v);
50 }
51 }
52 }
53 Ok(Some(peaks))
54}
55
56#[cfg(test)]
57mod tests {
58 use std::path::PathBuf;
59
60 use super::peaks;
61
62 const BPS: u32 = 10;
63
64 fn asset(name: &str) -> PathBuf {
65 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
66 .join("../../assets")
67 .join(name)
68 }
69
70 #[test]
71 fn peaks_follow_the_1hz_volume_pulse() {
72 let peaks = peaks(asset("test_av.mp4"), 0, BPS)
73 .expect("open")
74 .expect("test_av.mp4 has an audio track");
75 // 5 s of source; the container's tail padding may spill one bucket.
76 let want = 5 * BPS as usize;
77 assert!(
78 peaks.len().abs_diff(want) <= 1,
79 "{} buckets, want {want} +/-1",
80 peaks.len()
81 );
82
83 for (i, &(lo, hi)) in peaks.iter().enumerate() {
84 assert!(
85 (-1.0..=0.0).contains(&lo) && (0.0..=1.0).contains(&hi),
86 "bucket {i} is ({lo}, {hi})"
87 );
88 }
89
90 // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): a full silence every
91 // second at t = 0.75, a full-scale peak at t = 0.25. So every second's
92 // quietest bucket must be the 8th (t in [0.7, 0.8)) — a bucketing that
93 // was off by a scale factor or dropped chunk positions would not line
94 // the dips up second after second.
95 for second in 0..5 {
96 let band = &peaks[second * BPS as usize..][..BPS as usize];
97 let level = |&(lo, hi): &(f32, f32)| hi - lo;
98 let quietest = (0..band.len())
99 .min_by(|&a, &b| level(&band[a]).total_cmp(&level(&band[b])))
100 .expect("non-empty band");
101 assert!(
102 (6..=8).contains(&quietest),
103 "second {second}: dip at bucket {quietest}, want 7 +/-1"
104 );
105 // Depth as a ratio, not an absolute: the fixture's sines sit around
106 // an eighth of full scale, and that is the encoder's business.
107 let (dip, loudest) = (
108 level(&band[quietest]),
109 band.iter().map(level).fold(0.0, f32::max),
110 );
111 assert!(loudest > 0.05, "second {second}: peak level only {loudest}");
112 assert!(
113 dip < 0.1 * loudest,
114 "second {second}: dip {dip} against peak {loudest}, want near silence"
115 );
116 }
117 }
118
119 /// A song's clip draws like any other: this goes through the same
120 /// `open_multi_streams` the timeline plays with, which reads a standalone
121 /// audio file on stream 0 as readily as an mp4's AAC track.
122 #[test]
123 fn a_standalone_audio_file_has_peaks_too() {
124 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)
125 .expect("open")
126 .expect("test_tone.mp3 is audio");
127 let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one
128 assert!(
129 peaks.len().abs_diff(want) <= 2,
130 "{} buckets, want {want} +/-2",
131 peaks.len()
132 );
133 // The fixture carries the A/V one's 1 Hz envelope, so the middle second
134 // has a dip and a peak. As a ratio, and a looser one: the tone sits
135 // around an eighth of full scale and mp3 does not preserve a true zero.
136 let level = |&(lo, hi): &(f32, f32)| hi - lo;
137 let band = &peaks[BPS as usize..][..BPS as usize];
138 let dip = band.iter().map(level).fold(f32::MAX, f32::min);
139 let loudest = band.iter().map(level).fold(0.0, f32::max);
140 assert!(loudest > 0.05, "peak level only {loudest}");
141 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
142 }
143
144 #[test]
145 fn video_only_source_has_no_peaks() {
146 assert!(
147 peaks(asset("test_baseline.mp4"), 0, BPS)
148 .expect("open")
149 .is_none()
150 );
151 }
152
153 /// Two streams of one file are two envelopes: the lane draws what the clip
154 /// actually plays, so a cache keyed on the path alone would be a lie the
155 /// user can see. Stream 1 of the fixture is 2 s of 220 Hz mono against
156 /// stream 0's 4-second-long pulsed stereo pair.
157 #[test]
158 fn each_stream_of_a_file_has_its_own_envelope() {
159 let multi = asset("test_multiaudio.mp4");
160 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
161 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
162 assert!(!zero.is_empty() && !one.is_empty());
163 // Bucket for bucket, not merely somewhere: a cache keyed on the path
164 // alone would hand the lane the *first* stream's shape for both, and
165 // that is what this refuses.
166 assert_ne!(zero, one, "both streams drew the same envelope");
167 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
168 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
169 // any other stream rather than being refused.
170 let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2");
171 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
172 }
173}