truepeak 0.1.1

True-peak measurement and lookahead limiting for planar f32 audio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use std::{
    ops::Range,
    sync::atomic::{AtomicBool, Ordering},
};

use crate::{BLOCK, Error, Progress, Upsampler, validate_layout, validate_rate};

#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TruePeak {
    /// Refined absolute peak in dBTP; negative infinity for silence.
    pub dbtp: f64,
    /// Absolute peak amplitude; can exceed one for inter-sample peaks.
    pub linear: f64,
    /// Zero-based input channel index.
    pub channel: usize,
    /// Relative to input sample 0, after removing interpolation delay.
    /// Zero padding can place a boundary peak slightly outside the input duration.
    pub position_seconds: f64,
}

#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChannelSamplePeak {
    /// Absolute sample maximum in dBFS; negative infinity for silence.
    pub dbfs: f64,
    /// Exact absolute input maximum, converted losslessly from `f32` to `f64`.
    pub linear: f64,
    /// Zero-based input channel index.
    pub channel: usize,
    /// Earliest index attaining the maximum; zero for empty or silent input.
    pub position_samples: usize,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SamplePeak {
    /// Largest peak across channels; ties choose the first channel.
    pub overall: ChannelSamplePeak,
    /// Peaks in input channel order.
    pub per_channel: Vec<ChannelSamplePeak>,
}

fn db(linear: f64) -> f64 {
    20.0 * linear.log10()
}

pub(crate) fn refine_peak(left: f64, center: f64, right: f64) -> (f64, f64) {
    if center.abs() >= left.abs() && center.abs() >= right.abs() {
        let curvature = right - 2.0 * center + left;
        let offset = if curvature == 0.0 {
            0.0
        } else {
            (left - right) / (2.0 * curvature)
        };
        if curvature != 0.0 && offset.abs() <= 0.5 {
            return (center - (right - left).powi(2) / (8.0 * curvature), offset);
        }
    }
    (center, 0.0)
}

fn check_cancel(cancel: &AtomicBool) -> Result<(), Error> {
    if cancel.load(Ordering::Relaxed) {
        Err(Error::Cancelled)
    } else {
        Ok(())
    }
}

fn report(
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
    pass: u32,
    done_samples: usize,
    total_samples: usize,
) -> Result<(), Error> {
    progress(Progress {
        pass,
        done_samples,
        total_samples,
    });
    check_cancel(cancel)
}

/// Uses 4x, 8x, or 16x interpolation; 8x is recommended.
/// Phase-sweep fixtures require readings within 0.02 dB of known tone peaks.
/// Ties choose the first channel. Empty channels and silence read negative infinity.
/// For long input, use `true_peak_with_control` to support cancellation and progress.
pub fn true_peak(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
) -> Result<TruePeak, Error> {
    true_peak_with_control(
        channels,
        sample_rate_hz,
        oversampling,
        &AtomicBool::new(false),
        &mut |_| {},
    )
}

/// Measures the overall peak with the validation and padding rules of [`true_peak`].
/// Progress counts base-rate samples across channels with pass 1. Cancellation
/// is checked at block boundaries and returns [`Error::Cancelled`] without partial results.
pub fn true_peak_with_control(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
) -> Result<TruePeak, Error> {
    let peaks = true_peak_per_channel_with_control(
        channels,
        sample_rate_hz,
        oversampling,
        cancel,
        progress,
    )?;
    Ok(overall_peak(peaks))
}

fn overall_peak(peaks: Vec<TruePeak>) -> TruePeak {
    let mut best = peaks[0];
    for peak in peaks.into_iter().skip(1) {
        if peak.linear > best.linear {
            best = peak;
        }
    }
    best
}

/// Same validation and zero-padding semantics as [`true_peak`], in input channel order.
pub fn true_peak_per_channel(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
) -> Result<Vec<TruePeak>, Error> {
    true_peak_per_channel_with_control(
        channels,
        sample_rate_hz,
        oversampling,
        &AtomicBool::new(false),
        &mut |_| {},
    )
}

/// Refines every local maximum in one scan, retaining only two neighboring samples.
/// Progress counts base-rate samples across channels; cancellation returns no partial peaks.
pub fn true_peak_per_channel_with_control(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
) -> Result<Vec<TruePeak>, Error> {
    measure_peaks(
        channels,
        sample_rate_hz,
        oversampling,
        cancel,
        progress,
        PeakScan::default(),
    )
}

/// Measures local peaks whose refined, delay-compensated position is in `range`.
/// The range uses base-rate frames and must satisfy `start <= end <= channel.len()`;
/// otherwise returns [`Error::InvalidInput`]. Empty ranges read silence with position zero.
/// Interpolation uses surrounding input, avoiding the ringing caused by slicing at a cut.
/// Positions remain relative to the whole input; ties choose the first channel.
/// A full-input range is bit-identical to [`true_peak`], including boundary padding peaks.
pub fn true_peak_in_range(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    range: Range<usize>,
) -> Result<TruePeak, Error> {
    true_peak_in_range_with_control(
        channels,
        sample_rate_hz,
        oversampling,
        range,
        &AtomicBool::new(false),
        &mut |_| {},
    )
}

/// Measures the overall peak with the range and context rules of [`true_peak_in_range`].
/// Progress counts processed base-rate samples across channels, including context, with pass 1.
/// Cancellation is checked at block boundaries and returns no partial results.
pub fn true_peak_in_range_with_control(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    range: Range<usize>,
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
) -> Result<TruePeak, Error> {
    let peaks = true_peak_per_channel_in_range_with_control(
        channels,
        sample_rate_hz,
        oversampling,
        range,
        cancel,
        progress,
    )?;
    Ok(overall_peak(peaks))
}

/// Same validation, context, and position semantics as [`true_peak_in_range`], in channel order.
pub fn true_peak_per_channel_in_range(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    range: Range<usize>,
) -> Result<Vec<TruePeak>, Error> {
    true_peak_per_channel_in_range_with_control(
        channels,
        sample_rate_hz,
        oversampling,
        range,
        &AtomicBool::new(false),
        &mut |_| {},
    )
}

/// Measures per-channel peaks with the range rules of [`true_peak_in_range`]
/// and progress/cancellation semantics of [`true_peak_in_range_with_control`].
/// Non-finite samples in the processed range or its interpolation context are rejected.
pub fn true_peak_per_channel_in_range_with_control(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    range: Range<usize>,
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
) -> Result<Vec<TruePeak>, Error> {
    measure_peaks(
        channels,
        sample_rate_hz,
        oversampling,
        cancel,
        progress,
        PeakScan {
            range: Some(range),
            ..PeakScan::default()
        },
    )
}

struct PeakScan {
    block_size: usize,
    bit_depth: Option<u8>,
    range: Option<Range<usize>>,
}

impl Default for PeakScan {
    fn default() -> Self {
        Self {
            block_size: BLOCK,
            bit_depth: None,
            range: None,
        }
    }
}

fn measure_peaks(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
    scan: PeakScan,
) -> Result<Vec<TruePeak>, Error> {
    let PeakScan {
        block_size,
        bit_depth,
        range,
    } = scan;
    let len = validate_layout(channels)?;
    validate_rate(sample_rate_hz)?;
    if !matches!(oversampling, 4 | 8 | 16) {
        return Err(Error::InvalidConfig(
            "oversampling must be 4, 8, or 16".into(),
        ));
    }
    let range = range.unwrap_or(0..len);
    if range.start > range.end || range.end > len {
        return Err(Error::InvalidInput(
            "range must satisfy start <= end <= input length".into(),
        ));
    }
    check_cancel(cancel)?;
    let mut up = Upsampler::new(oversampling, sample_rate_hz)?;
    let delay = up.delay();
    // Preserve whole-file padding peaks, even when refinement places them outside the input.
    let whole_file = range == (0..len);
    // One extra base-rate frame supplies both neighbors for three-point refinement.
    let margin = delay.div_ceil(oversampling as usize) + 1;
    let context = if range.is_empty() {
        range.clone()
    } else {
        range.start.saturating_sub(margin)..range.end.saturating_add(margin).min(len)
    };
    let total = context
        .len()
        .checked_mul(channels.len())
        .ok_or_else(|| Error::InvalidInput("input length overflow".into()))?;
    let mut done = 0;
    report(cancel, progress, 1, done, total)?;
    let mut output = Vec::with_capacity(block_size * oversampling as usize + 2 * delay);
    let mut results = Vec::with_capacity(channels.len());
    let mut quantized = Vec::with_capacity(block_size);
    for (channel, input) in channels.iter().enumerate() {
        up.reset();
        let mut index = 0;
        let mut best = 0.0;
        let mut position = 0.0;
        let mut neighbors = [0.0_f64; 2];
        let mut consume = |samples: &[f32]| {
            for &sample in samples {
                let right = sample as f64;
                if index >= 2 {
                    let [left, center] = neighbors;
                    let (value, offset) = refine_peak(left, center, right);
                    if value.abs() > best {
                        let candidate = index as f64 - 1.0 + offset;
                        let in_range = || {
                            let frame = context.start as f64
                                + (candidate - delay as f64) / oversampling as f64;
                            center.abs() >= left.abs()
                                && center.abs() >= right.abs()
                                && frame >= range.start as f64
                                && frame < range.end as f64
                        };
                        if whole_file || in_range() {
                            best = value.abs();
                            position = candidate;
                        }
                    }
                }
                if whole_file && right.abs() > best {
                    best = right.abs();
                    position = index as f64;
                }
                neighbors = [neighbors[1], right];
                index += 1;
            }
        };
        for block in input[context.clone()].chunks(block_size) {
            check_cancel(cancel)?;
            output.clear();
            if let Some(bits) = bit_depth {
                quantized.clear();
                quantized.extend(block.iter().map(|&v| crate::quantize_sample(v, bits)));
                up.process(&quantized, &mut output)?;
            } else {
                up.process(block, &mut output)?;
            }
            consume(&output);
            done += block.len();
            report(cancel, progress, 1, done, total)?;
        }
        output.clear();
        up.flush(&mut output);
        consume(&output);
        check_cancel(cancel)?;
        results.push(TruePeak {
            dbtp: db(best),
            linear: best,
            channel,
            position_seconds: if best == 0.0 {
                0.0
            } else if whole_file {
                (position - delay as f64) / (sample_rate_hz as f64 * oversampling as f64)
            } else {
                (context.start as f64 + (position - delay as f64) / oversampling as f64)
                    / sample_rate_hz as f64
            },
        });
    }
    report(cancel, progress, 1, done, total)?;
    Ok(results)
}

pub(crate) fn export_peak_with_control(
    channels: &[&[f32]],
    sample_rate_hz: u32,
    oversampling: u32,
    bit_depth: Option<u8>,
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
) -> Result<f64, Error> {
    let peaks = measure_peaks(
        channels,
        sample_rate_hz,
        oversampling,
        cancel,
        progress,
        PeakScan {
            bit_depth,
            ..PeakScan::default()
        },
    )?;
    Ok(peaks
        .iter()
        .map(|p| p.dbtp)
        .fold(f64::NEG_INFINITY, f64::max))
}

/// Exact absolute f32 maxima, converted losslessly to f64. Ties within a channel use the earliest
/// sample; ties across channels use the first channel. Rejects non-finite samples and invalid layouts.
pub fn sample_peak(channels: &[&[f32]]) -> Result<SamplePeak, Error> {
    sample_peak_with_control(channels, &AtomicBool::new(false), &mut |_| {})
}

/// Measures sample maxima with the validation and tie rules of [`sample_peak`].
/// Progress counts base-rate samples across channels with pass 1. Cancellation
/// is checked at block boundaries and returns [`Error::Cancelled`] without partial results.
pub fn sample_peak_with_control(
    channels: &[&[f32]],
    cancel: &AtomicBool,
    progress: &mut dyn FnMut(Progress),
) -> Result<SamplePeak, Error> {
    let len = validate_layout(channels)?;
    check_cancel(cancel)?;
    let total = len
        .checked_mul(channels.len())
        .ok_or_else(|| Error::InvalidInput("input length overflow".into()))?;
    let mut done = 0;
    report(cancel, progress, 1, done, total)?;
    let mut per_channel = Vec::with_capacity(channels.len());
    for (channel, input) in channels.iter().enumerate() {
        let mut peak = ChannelSamplePeak {
            dbfs: f64::NEG_INFINITY,
            linear: 0.0,
            channel,
            position_samples: 0,
        };
        for block in input.chunks(BLOCK) {
            check_cancel(cancel)?;
            for (index, &sample) in block.iter().enumerate() {
                if !sample.is_finite() {
                    return Err(Error::InvalidInput("non-finite sample".into()));
                }
                let value = (sample as f64).abs();
                if value > peak.linear {
                    peak.linear = value;
                    peak.position_samples = done - channel * len + index;
                }
            }
            done += block.len();
            report(cancel, progress, 1, done, total)?;
        }
        peak.dbfs = db(peak.linear);
        per_channel.push(peak);
    }
    let mut overall = per_channel[0];
    for &peak in &per_channel[1..] {
        if peak.linear > overall.linear {
            overall = peak;
        }
    }
    Ok(SamplePeak {
        overall,
        per_channel,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn refined_peaks_cross_block_boundaries_without_changing_results() {
        let mut input = vec![0.0; 5003];
        for (index, value) in [
            (6, 0.3),
            (63, -0.7),
            (1023, 0.9),
            (4095, -1.0),
            (5002, 0.99),
        ] {
            input[index] = value;
            input[index - 1] = value * 0.6;
        }
        for factor in [4, 8, 16] {
            for range in [
                None,
                Some(0..input.len()),
                Some(40..1040),
                Some(4094..4097),
                Some(4999..input.len()),
            ] {
                let analyze = |block_size| {
                    measure_peaks(
                        &[&input],
                        44100,
                        factor,
                        &AtomicBool::new(false),
                        &mut |_| {},
                        PeakScan {
                            block_size,
                            range: range.clone(),
                            ..PeakScan::default()
                        },
                    )
                    .unwrap()
                };
                let expected = analyze(input.len());
                for block in [1, 7, 64, 4096] {
                    assert_eq!(
                        analyze(block),
                        expected,
                        "L={factor}, block={block}, {range:?}"
                    );
                }
            }
        }
    }
}