Skip to content

Commit 0fe1ca0

Browse files
refactor(dsp): keep downmixed frames finite
Signed-off-by: Maika Namuo <httpworldview@gmail.com>
1 parent 7d17327 commit 0fe1ca0

3 files changed

Lines changed: 72 additions & 129 deletions

File tree

‎src/dsp.rs‎

Lines changed: 14 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -287,32 +287,24 @@ impl<'a> AudioBlock<'a> {
287287
self.frame_count() as f32 / self.sample_rate.hz()
288288
}
289289

290+
// Samples arrive finite, and the frames mixed from them stay so.
290291
pub fn stereo_frames(
291292
&self,
292293
) -> impl ExactSizeIterator<Item = [f32; 2]> + DoubleEndedIterator + '_ {
293294
let matrix = self.stereo_matrix();
294-
self.samples
295-
.chunks_exact(self.channels)
296-
.map(move |frame| match matrix {
297-
[weights] => {
298-
let sample = frame[0];
299-
[0.0 + sample * weights[0], 0.0 + sample * weights[1]]
300-
}
301-
[first, second] => {
302-
let sample = frame[0];
303-
let [left, right] = [0.0 + sample * first[0], 0.0 + sample * first[1]];
304-
let sample = frame[1];
305-
[left + sample * second[0], right + sample * second[1]]
306-
}
307-
_ => {
308-
frame
309-
.iter()
310-
.zip(matrix)
311-
.fold([0.0; 2], |[left, right], (&sample, weights)| {
312-
[left + sample * weights[0], right + sample * weights[1]]
313-
})
314-
}
315-
})
295+
let plain = *matrix == [[1.0, 0.0], [0.0, 1.0]];
296+
self.samples.chunks_exact(self.channels).map(move |frame| {
297+
if plain {
298+
return [frame[0], frame[1]];
299+
}
300+
// A fold here measured 1.6x the instructions.
301+
let mut sides = [0.0_f32; 2];
302+
for (&sample, weights) in frame.iter().zip(matrix) {
303+
sides[0] += sample * weights[0];
304+
sides[1] += sample * weights[1];
305+
}
306+
sides.map(|side| side.clamp(f32::MIN, f32::MAX))
307+
})
316308
}
317309

318310
pub fn projected_frames(
@@ -656,35 +648,6 @@ mod tests {
656648
);
657649
}
658650

659-
#[test]
660-
fn common_stereo_paths_match_general_fold() {
661-
let nan = f32::from_bits(0x7fc0_1234);
662-
for (samples, channels) in [
663-
(&[0.0, -0.0, nan, f32::INFINITY][..], 1),
664-
(&[0.0, -0.0, 0.25, -0.5, nan, f32::INFINITY][..], 2),
665-
] {
666-
let block = AudioBlock::fallback(samples, channels, RATE);
667-
let matrix = block.stereo_matrix();
668-
let expected = samples.chunks_exact(channels).map(|frame| {
669-
frame
670-
.iter()
671-
.zip(matrix)
672-
.fold([0.0; 2], |[left, right], (&sample, weights)| {
673-
[left + sample * weights[0], right + sample * weights[1]]
674-
})
675-
});
676-
for (actual, expected) in block.stereo_frames().zip(expected) {
677-
for (actual, expected) in actual.into_iter().zip(expected) {
678-
if expected.is_nan() {
679-
assert!(actual.is_nan());
680-
} else {
681-
assert_eq!(actual.to_bits(), expected.to_bits());
682-
}
683-
}
684-
}
685-
}
686-
}
687-
688651
#[test]
689652
fn nonnegative_running_means_preserve_small_values_after_a_large_value_expires() {
690653
let mut means = RunningMeans::<3, 1>::new([2]);

‎src/visuals/stereometer/processor.rs‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ impl StereometerProcessor {
123123
for [left, right] in block.stereo_frames() {
124124
self.histories[FULL_BAND].push_back((left, right));
125125
self.correlators[FULL_BAND].update(left, right, alpha);
126+
self.silent_frames = if [left, right] == [0.0; 2] {
127+
self.silent_frames + 1
128+
} else {
129+
0
130+
};
126131

127132
if mode.analyzed() {
128133
let bands = self.band_splitter.process([left, right]);
@@ -142,16 +147,6 @@ impl StereometerProcessor {
142147
.iter_mut()
143148
.for_each(Correlator::flush_denormals);
144149
self.band_splitter.flush_denormals();
145-
let trailing = block
146-
.stereo_frames()
147-
.rev()
148-
.take_while(|frame| *frame == [0.0; 2])
149-
.count();
150-
self.silent_frames = if trailing == block.frame_count() {
151-
self.silent_frames + trailing
152-
} else {
153-
trailing
154-
};
155150
// A window of only digital silence holds no signal: its correlation is undefined.
156151
let silent = self.silent_frames as f32 >= window * sample_rate.hz();
157152

@@ -388,4 +383,18 @@ mod tests {
388383
assert_close(correlation(&[(1., 0.), (0., 1.), (-1., 0.), (0., -1.)]), 0.);
389384
assert_close(correlation(&[(0.0, 0.0)]), 0.0);
390385
}
386+
387+
#[test]
388+
fn overflowing_downmix_leaves_correlation_finite() {
389+
let mut processor = StereometerProcessor::new(StereometerConfig {
390+
segment_duration: Finite::must(1.0),
391+
..Default::default()
392+
});
393+
// Front left and center both feed the left side, so their sum overflows.
394+
let samples = [[f32::MAX, 0.0, f32::MAX], [0.5; 3], [0.5; 3], [0.5; 3]];
395+
let snapshot = processor
396+
.process_block(&AudioBlock::fallback(samples.as_flattened(), 3, RATE))
397+
.unwrap();
398+
assert!(snapshot.correlations[FULL_BAND].is_finite());
399+
}
391400
}

‎src/visuals/waveform/processor.rs‎

Lines changed: 39 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -123,13 +123,19 @@ impl BandTracker {
123123
}
124124
}
125125

126+
#[derive(Clone, Copy, Default)]
127+
struct ChannelColumn {
128+
extrema: Option<(f32, f32)>,
129+
// Where the column before it ended, which joins the two.
130+
carried: Option<f32>,
131+
}
132+
126133
crate::macros::default_struct! {
127134
pub struct WaveformProcessor {
128135
config: WaveformConfig = WaveformConfig::default(),
129136
band_analysis: Option<(BandFilter, BandTracker)> = None,
130137
column_phase: f64 = 0.0,
131-
current: [Option<(f32, f32, Option<f32>)>; DERIVED_CHANNELS] = [None; DERIVED_CHANNELS],
132-
last_sample: [Option<f32>; DERIVED_CHANNELS] = [None; DERIVED_CHANNELS],
138+
channels: [ChannelColumn; DERIVED_CHANNELS] = [ChannelColumn::default(); DERIVED_CHANNELS],
133139
pending_columns: Vec<WaveFrame> = Vec::new(),
134140
reset_pending: bool = true,
135141
}
@@ -155,9 +161,8 @@ impl WaveformProcessor {
155161

156162
pub fn reset_audio(&mut self) {
157163
self.column_phase = 0.0;
158-
self.last_sample = [None; DERIVED_CHANNELS];
164+
self.channels = [ChannelColumn::default(); DERIVED_CHANNELS];
159165
self.pending_columns.clear();
160-
self.current = [None; DERIVED_CHANNELS];
161166
if self.band_analysis.is_some() {
162167
self.band_analysis = Self::band_analysis(self.config);
163168
}
@@ -174,9 +179,9 @@ impl WaveformProcessor {
174179
}
175180

176181
fn columns(&self) -> WaveFrame {
177-
let mut columns = std::array::from_fn(|channel| {
178-
let (min, max) = self.current[channel].map_or((0.0, 0.0), |(min, max, _)| {
179-
self.last_sample[channel].map_or((min, max), |last| (min.min(last), max.max(last)))
182+
let mut columns = self.channels.map(|channel| {
183+
let (min, max) = channel.extrema.map_or((0.0, 0.0), |(min, max)| {
184+
(channel.carried).map_or((min, max), |last| (min.min(last), max.max(last)))
180185
});
181186
WaveColumn {
182187
min,
@@ -203,67 +208,46 @@ impl WaveformProcessor {
203208
columns
204209
}
205210

206-
fn emit_column(&mut self) {
211+
fn emit_column(&mut self, newest: [f32; DERIVED_CHANNELS]) {
207212
let columns = self.columns();
208-
for channel in 0..DERIVED_CHANNELS {
209-
if let Some((_, _, Some(last))) = self.current[channel] {
210-
self.last_sample[channel] = Some(last);
211-
}
212-
}
213+
self.channels = newest.map(|sample| ChannelColumn {
214+
extrema: None,
215+
carried: Some(sample),
216+
});
213217
self.pending_columns.push(columns);
214218
if self.pending_columns.len() >= self.config.max_columns * 2 {
215219
self.cap_pending_columns();
216220
}
217-
self.current = [None; DERIVED_CHANNELS];
218221
}
219222

220223
fn ingest_samples(&mut self, block: &AudioBlock<'_>) {
221224
let step = (f64::from(self.config.scroll_speed.get())
222225
/ f64::from(self.config.sample_rate.get()))
223226
.min(1.0);
224227
for stereo in block.stereo_frames() {
225-
let derived = WAVEFORM_CHANNELS.map(|channel| channel.project(stereo));
226-
let finite = derived.map(f32::is_finite);
227228
if let Some((filter, tracker)) = &mut self.band_analysis {
228-
let bands = filter.process([
229-
if finite[0] { derived[0] } else { 0.0 },
230-
if finite[1] { derived[1] } else { 0.0 },
231-
]);
232-
tracker.process(std::array::from_fn(|channel| {
233-
if finite[channel] {
234-
bands.map(|band| WAVEFORM_CHANNELS[channel].project(band))
235-
} else {
236-
[0.0; BAND_COUNT]
237-
}
238-
}));
229+
let bands = filter.process(stereo);
230+
tracker.process(
231+
WAVEFORM_CHANNELS.map(|channel| bands.map(|band| channel.project(band))),
232+
);
239233
}
240-
self.ingest_derived(derived, finite, step);
234+
self.ingest_derived(
235+
WAVEFORM_CHANNELS.map(|channel| channel.project(stereo)),
236+
step,
237+
);
241238
}
242239
}
243240

244-
fn ingest_derived(
245-
&mut self,
246-
derived: [f32; DERIVED_CHANNELS],
247-
finite: [bool; DERIVED_CHANNELS],
248-
step: f64,
249-
) {
250-
for channel in 0..DERIVED_CHANNELS {
251-
if finite[channel] {
252-
let sample = derived[channel];
253-
self.current[channel] = Some(match self.current[channel] {
254-
Some((min, max, _)) => (min.min(sample), max.max(sample), Some(sample)),
255-
None => (sample, sample, Some(sample)),
256-
});
257-
} else {
258-
if let Some((_, _, last)) = &mut self.current[channel] {
259-
*last = None;
260-
}
261-
self.last_sample[channel] = None;
262-
}
241+
fn ingest_derived(&mut self, derived: [f32; DERIVED_CHANNELS], step: f64) {
242+
for (channel, sample) in self.channels.iter_mut().zip(derived) {
243+
channel.extrema = Some(match channel.extrema {
244+
Some((min, max)) => (min.min(sample), max.max(sample)),
245+
None => (sample, sample),
246+
});
263247
}
264248
self.column_phase += step;
265249
if self.column_phase >= 1.0 {
266-
self.emit_column();
250+
self.emit_column(derived);
267251
self.column_phase -= 1.0;
268252
}
269253
}
@@ -429,27 +413,14 @@ mod tests {
429413
}
430414

431415
#[test]
432-
fn non_finite_samples_are_sanitized_and_break_column_continuity() {
416+
fn extreme_samples_stay_finite() {
417+
// Front left and center both feed the left side, so their sum overflows.
433418
let mut processor = WaveformProcessor::new(config(RATE, 8));
434-
let update = process(&mut processor, &[0.0, f32::NAN, f32::INFINITY, 1.0], 1);
435-
436-
assert_eq!(update.columns.len(), 4);
437-
assert_eq!(extrema(&update, 0, 3), (1.0, 1.0));
438-
assert!(
439-
update
440-
.columns
441-
.iter()
442-
.flatten()
443-
.all(|c| c.min.is_finite() && c.max.is_finite())
444-
);
445-
assert!(
446-
update
447-
.columns
448-
.iter()
449-
.flatten()
450-
.flat_map(|c| c.color_bands)
451-
.all(f32::is_finite)
452-
);
419+
let update = process(&mut processor, &[f32::MAX, 0.0, f32::MAX, 1.0, 0.0, 0.0], 3);
420+
assert_eq!(extrema(&update, 0, 0), (f32::MAX, f32::MAX));
421+
assert_eq!(extrema(&update, 0, 1), (1.0, f32::MAX));
422+
let mut bands = update.columns.iter().flatten().flat_map(|c| c.color_bands);
423+
assert!(bands.all(f32::is_finite));
453424

454425
for (right, channel) in [(f32::MAX, 2), (-f32::MAX, 3)] {
455426
let mut processor = WaveformProcessor::new(config(RATE, 8));

0 commit comments

Comments
 (0)