forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB65ea910Tahinli3 months ago308 commits

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