ebur128 0.1.10

Implementation of the EBU R128 loudness standard
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
// Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use crate::interp::InterpF;
use crate::utils::{FrameAccumulator, Sample};
use dasp_frame::Frame;
use smallvec::{smallvec, SmallVec};

use UpsamplingScanner::*;

#[derive(Debug)]
enum UpsamplingScanner {
    Mono2F(InterpF<24, 2, [f32; 1]>),
    Stereo2F(InterpF<24, 2, [f32; 2]>),
    Quad2F(InterpF<24, 2, [f32; 4]>),
    Surround2F(InterpF<24, 2, [f32; 6]>),
    OctoSurround2F(InterpF<24, 2, [f32; 8]>),
    Mono4F(InterpF<12, 4, [f32; 1]>),
    Stereo4F(InterpF<12, 4, [f32; 2]>),
    Quad4F(InterpF<12, 4, [f32; 4]>),
    Surround4F(InterpF<12, 4, [f32; 6]>),
    OctoSurround4F(InterpF<12, 4, [f32; 8]>),
    Generic2F(Box<[InterpF<24, 2, [f32; 1]>]>),
    Generic4F(Box<[InterpF<12, 4, [f32; 1]>]>),
}

impl UpsamplingScanner {
    fn new(rate: u32, channels: u32) -> Option<Self> {
        enum Factor {
            Four,
            Two,
        }
        let interp_factor = if rate < 96_000 {
            Factor::Four
        } else if rate < 192_000 {
            Factor::Two
        } else {
            return None;
        };

        Some(match (channels as usize, interp_factor) {
            (1, Factor::Two) => Mono2F(InterpF::new()),
            (2, Factor::Two) => Stereo2F(InterpF::new()),
            (4, Factor::Two) => Quad2F(InterpF::new()),
            (6, Factor::Two) => Surround2F(InterpF::new()),
            (8, Factor::Two) => OctoSurround2F(InterpF::new()),
            (1, Factor::Four) => Mono4F(InterpF::new()),
            (2, Factor::Four) => Stereo4F(InterpF::new()),
            (4, Factor::Four) => Quad4F(InterpF::new()),
            (6, Factor::Four) => Surround4F(InterpF::new()),
            (8, Factor::Four) => OctoSurround4F(InterpF::new()),
            (c, Factor::Two) => Generic2F(vec![InterpF::new(); c].into()),
            (c, Factor::Four) => Generic4F(vec![InterpF::new(); c].into()),
        })
    }

    pub fn check_true_peak<'a, T: Sample + 'a, S: crate::Samples<'a, T>>(
        &mut self,
        src: S,
        peaks: &mut [f64],
    ) {
        macro_rules! tp_specialized_impl {
            ( $channels:expr, $interpolator:expr ) => {{
                const CHANNELS: usize = $channels;
                assert!(src.channels() == CHANNELS && peaks.len() == CHANNELS);
                let mut tmp_peaks = <[f32; CHANNELS]>::from_fn(|i| peaks[i] as f32);

                src.foreach_frame(|frame: [T; CHANNELS]| {
                    let frame_f32: [f32; CHANNELS] = Frame::map(frame, |s| s.to_sample::<f32>());
                    for new_frame in &$interpolator.interpolate(frame_f32) {
                        tmp_peaks.retain_max_samples(&Frame::map(*new_frame, |s| s.abs()));
                    }
                });
                for (dst, src) in Iterator::zip(peaks.into_iter(), &tmp_peaks) {
                    *dst = *src as f64;
                }
            }};
        }

        macro_rules! tp_generic_impl {
            ( $interpolators:expr ) => {{
                assert!(src.channels() == $interpolators.len() && src.channels() == peaks.len());
                for (c, (interpolator, channel_peak)) in
                    Iterator::zip($interpolators.iter_mut(), peaks.iter_mut()).enumerate()
                {
                    src.foreach_sample(c, move |s| {
                        for [new_sample] in &interpolator.interpolate([s.to_sample::<f32>()]) {
                            let new_sample = new_sample.abs() as f64;
                            if new_sample > *channel_peak {
                                *channel_peak = new_sample;
                            }
                        }
                    });
                }
            }};
        }

        match self {
            Mono2F(interpolator) => tp_specialized_impl!(1, interpolator),
            Stereo2F(interpolator) => tp_specialized_impl!(2, interpolator),
            Quad2F(interpolator) => tp_specialized_impl!(4, interpolator),
            Surround2F(interpolator) => tp_specialized_impl!(6, interpolator),
            OctoSurround2F(interpolator) => tp_specialized_impl!(8, interpolator),
            Mono4F(interpolator) => tp_specialized_impl!(1, interpolator),
            Stereo4F(interpolator) => tp_specialized_impl!(2, interpolator),
            Quad4F(interpolator) => tp_specialized_impl!(4, interpolator),
            Surround4F(interpolator) => tp_specialized_impl!(6, interpolator),
            OctoSurround4F(interpolator) => tp_specialized_impl!(8, interpolator),
            Generic2F(interpolators) => tp_generic_impl!(interpolators),
            Generic4F(interpolators) => tp_generic_impl!(interpolators),
        }
    }

    fn reset(&mut self) {
        match self {
            Mono2F(interpolator) => interpolator.reset(),
            Stereo2F(interpolator) => interpolator.reset(),
            Quad2F(interpolator) => interpolator.reset(),
            Surround2F(interpolator) => interpolator.reset(),
            OctoSurround2F(interpolator) => interpolator.reset(),
            Mono4F(interpolator) => interpolator.reset(),
            Stereo4F(interpolator) => interpolator.reset(),
            Quad4F(interpolator) => interpolator.reset(),
            Surround4F(interpolator) => interpolator.reset(),
            OctoSurround4F(interpolator) => interpolator.reset(),
            Generic2F(interpolators) => interpolators.iter_mut().for_each(InterpF::reset),
            Generic4F(interpolators) => interpolators.iter_mut().for_each(InterpF::reset),
        }
    }
}

/// True peak measurement.
#[derive(Debug)]
pub struct TruePeak {
    /// Interpolator/resampler.
    interp: UpsamplingScanner,
}

impl TruePeak {
    pub fn new(rate: u32, channels: u32) -> Option<Self> {
        UpsamplingScanner::new(rate, channels).map(|interp| Self { interp })
    }

    pub fn reset(&mut self) {
        self.interp.reset();
    }

    pub fn check_true_peak<'a, T: Sample + 'a, S: crate::Samples<'a, T>>(
        &mut self,
        src: S,
        peaks: &mut [f64],
    ) {
        self.interp.check_true_peak(src, peaks)
    }

    pub fn seed<'a, T: Sample + 'a, S: crate::Samples<'a, T>>(&mut self, src: S) {
        let mut true_peaks: SmallVec<[f64; 16]> = smallvec![0.0; src.channels()];
        self.interp.check_true_peak(src, &mut true_peaks)
    }
}

#[cfg(feature = "c-tests")]
use std::os::raw::c_void;

#[cfg(feature = "c-tests")]
extern "C" {
    pub fn true_peak_create_c(rate: u32, channels: u32) -> *mut c_void;
    pub fn true_peak_check_short_c(
        tp: *mut c_void,
        frames: usize,
        src: *const i16,
        peaks: *mut f64,
    );
    pub fn true_peak_check_int_c(tp: *mut c_void, frames: usize, src: *const i32, peaks: *mut f64);
    pub fn true_peak_check_float_c(
        tp: *mut c_void,
        frames: usize,
        src: *const f32,
        peaks: *mut f64,
    );
    pub fn true_peak_check_double_c(
        tp: *mut c_void,
        frames: usize,
        src: *const f64,
        peaks: *mut f64,
    );
    pub fn true_peak_destroy_c(tp: *mut c_void);
}

#[cfg(feature = "c-tests")]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::Signal;
    use float_eq::assert_float_eq;
    use quickcheck_macros::quickcheck;

    #[quickcheck]
    fn compare_c_impl_i16(signal: Signal<i16>) -> quickcheck::TestResult {
        if signal.rate >= 192_000 {
            return quickcheck::TestResult::discard();
        }

        // Maximum of 400ms but our input is up to 5000ms, so distribute it evenly
        // by shrinking accordingly.
        let len = signal.data.len() / signal.channels as usize;
        let len = std::cmp::min(2 * len / 25, 4 * ((signal.rate as usize + 5) / 10));

        let mut peaks = vec![0.0f64; signal.channels as usize];
        let mut peaks_c = vec![0.0f64; signal.channels as usize];

        {
            let mut tp = TruePeak::new(signal.rate, signal.channels).unwrap();
            tp.check_true_peak(
                crate::Interleaved::new(
                    &signal.data[0..(len * signal.channels as usize)],
                    signal.channels as usize,
                )
                .unwrap(),
                &mut peaks,
            );
        }

        unsafe {
            let tp = true_peak_create_c(signal.rate, signal.channels);
            assert!(!tp.is_null());
            true_peak_check_short_c(tp, len, signal.data.as_ptr(), peaks_c.as_mut_ptr());
            true_peak_destroy_c(tp);
        }

        for (i, (r, c)) in peaks.iter().zip(peaks_c.iter()).enumerate() {
            assert_float_eq!(
                *r,
                *c,
                // For a performance-boost, interpolation-filter is defined as f32, causing lower precision
                abs <= 0.000004,
                "Rust and C implementation differ at channel {}",
                i,
            );
        }

        quickcheck::TestResult::passed()
    }

    #[quickcheck]
    fn compare_c_impl_i32(signal: Signal<i32>) -> quickcheck::TestResult {
        if signal.rate >= 192_000 {
            return quickcheck::TestResult::discard();
        }

        // Maximum of 400ms but our input is up to 5000ms, so distribute it evenly
        // by shrinking accordingly.
        let len = signal.data.len() / signal.channels as usize;
        let len = std::cmp::min(2 * len / 25, 4 * ((signal.rate as usize + 5) / 10));

        let mut peaks = vec![0.0f64; signal.channels as usize];
        let mut peaks_c = vec![0.0f64; signal.channels as usize];

        {
            let mut tp = TruePeak::new(signal.rate, signal.channels).unwrap();
            tp.check_true_peak(
                crate::Interleaved::new(
                    &signal.data[0..(len * signal.channels as usize)],
                    signal.channels as usize,
                )
                .unwrap(),
                &mut peaks,
            );
        }

        unsafe {
            let tp = true_peak_create_c(signal.rate, signal.channels);
            assert!(!tp.is_null());
            true_peak_check_int_c(tp, len, signal.data.as_ptr(), peaks_c.as_mut_ptr());
            true_peak_destroy_c(tp);
        }

        for (i, (r, c)) in peaks.iter().zip(peaks_c.iter()).enumerate() {
            assert_float_eq!(
                *r,
                *c,
                // For a performance-boost, interpolation-filter is defined as f32, causing lower precision
                abs <= 0.000004,
                "Rust and C implementation differ at channel {}",
                i
            );
        }

        quickcheck::TestResult::passed()
    }

    #[quickcheck]
    fn compare_c_impl_f32(signal: Signal<f32>) -> quickcheck::TestResult {
        if signal.rate >= 192_000 {
            return quickcheck::TestResult::discard();
        }

        // Maximum of 400ms but our input is up to 5000ms, so distribute it evenly
        // by shrinking accordingly.
        let len = signal.data.len() / signal.channels as usize;
        let len = std::cmp::min(2 * len / 25, 4 * ((signal.rate as usize + 5) / 10));

        let mut peaks = vec![0.0f64; signal.channels as usize];
        let mut peaks_c = vec![0.0f64; signal.channels as usize];

        {
            let mut tp = TruePeak::new(signal.rate, signal.channels).unwrap();
            tp.check_true_peak(
                crate::Interleaved::new(
                    &signal.data[0..(len * signal.channels as usize)],
                    signal.channels as usize,
                )
                .unwrap(),
                &mut peaks,
            );
        }

        unsafe {
            let tp = true_peak_create_c(signal.rate, signal.channels);
            assert!(!tp.is_null());
            true_peak_check_float_c(tp, len, signal.data.as_ptr(), peaks_c.as_mut_ptr());
            true_peak_destroy_c(tp);
        }

        for (i, (r, c)) in peaks.iter().zip(peaks_c.iter()).enumerate() {
            assert_float_eq!(
                *r,
                *c,
                // For a performance-boost, interpolation-filter is defined as f32, causing lower precision
                abs <= 0.000004,
                "Rust and C implementation differ at channel {}",
                i
            );
        }

        quickcheck::TestResult::passed()
    }

    #[quickcheck]
    fn compare_c_impl_f64(signal: Signal<f64>) -> quickcheck::TestResult {
        if signal.rate >= 192_000 {
            return quickcheck::TestResult::discard();
        }

        // Maximum of 400ms but our input is up to 5000ms, so distribute it evenly
        // by shrinking accordingly.
        let len = signal.data.len() / signal.channels as usize;
        let len = std::cmp::min(2 * len / 25, 4 * ((signal.rate as usize + 5) / 10));

        let mut peaks = vec![0.0f64; signal.channels as usize];
        let mut peaks_c = vec![0.0f64; signal.channels as usize];

        {
            let mut tp = TruePeak::new(signal.rate, signal.channels).unwrap();
            tp.check_true_peak(
                crate::Interleaved::new(
                    &signal.data[0..(len * signal.channels as usize)],
                    signal.channels as usize,
                )
                .unwrap(),
                &mut peaks,
            );
        }

        unsafe {
            let tp = true_peak_create_c(signal.rate, signal.channels);
            assert!(!tp.is_null());
            true_peak_check_double_c(tp, len, signal.data.as_ptr(), peaks_c.as_mut_ptr());
            true_peak_destroy_c(tp);
        }

        for (i, (r, c)) in peaks.iter().zip(peaks_c.iter()).enumerate() {
            assert_float_eq!(
                *r,
                *c,
                // For a performance-boost, interpolation-filter is defined as f32, causing lower precision
                abs <= 0.000004,
                "Rust and C implementation differ at channel {}",
                i
            );
        }

        quickcheck::TestResult::passed()
    }
}