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
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
// 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 dasp_frame::Frame;

/// Convert linear energy to logarithmic loudness.
pub fn energy_to_loudness(energy: f64) -> f64 {
    // The non-test version is faster and more accurate but gives
    // slightly different results than the C version and fails the
    // tests because of that.
    #[cfg(test)]
    {
        10.0 * (f64::ln(energy) / std::f64::consts::LN_10) - 0.691
    }
    #[cfg(not(test))]
    {
        10.0 * f64::log10(energy) - 0.691
    }
}

/// Trait for abstracting over interleaved and planar samples.
pub trait Samples<'a, S: Sample + 'a>: Sized {
    /// Call the given closure for each sample of the given channel.
    // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable
    // and because of that we wouldn't get nice optimizations
    fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a S));

    /// Call the given closure for each sample of the given channel.
    // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable
    // and because of that we wouldn't get nice optimizations
    fn foreach_sample_zipped<U>(
        &self,
        channel: usize,
        iter: impl Iterator<Item = U>,
        func: impl FnMut(&'a S, U),
    );

    fn foreach_frame<F: Frame<Sample = S>>(&self, func: impl FnMut(F));

    /// Number of frames.
    fn frames(&self) -> usize;

    /// Number of channels.
    fn channels(&self) -> usize;

    /// Split into two at the given sample.
    fn split_at(self, sample: usize) -> (Self, Self);
}

/// Struct representing interleaved samples.
pub struct Interleaved<'a, S> {
    /// Interleaved sample data.
    data: &'a [S],
    /// Number of channels.
    channels: usize,
}

impl<'a, S> Interleaved<'a, S> {
    /// Create a new wrapper around the interleaved channels and do a sanity check.
    pub fn new(data: &'a [S], channels: usize) -> Result<Self, crate::Error> {
        if channels == 0 {
            return Err(crate::Error::NoMem);
        }

        if data.len() % channels != 0 {
            return Err(crate::Error::NoMem);
        }

        Ok(Interleaved { data, channels })
    }
}

impl<'a, S: Sample> Samples<'a, S> for Interleaved<'a, S> {
    #[inline]
    fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a S)) {
        assert!(channel < self.channels);

        for v in self.data.chunks_exact(self.channels) {
            func(&v[channel])
        }
    }

    #[inline]
    fn foreach_sample_zipped<U>(
        &self,
        channel: usize,
        iter: impl Iterator<Item = U>,
        mut func: impl FnMut(&'a S, U),
    ) {
        assert!(channel < self.channels);

        for (v, u) in Iterator::zip(self.data.chunks_exact(self.channels), iter) {
            func(&v[channel], u)
        }
    }

    #[inline]
    fn foreach_frame<F: Frame<Sample = S>>(&self, mut func: impl FnMut(F)) {
        assert_eq!(F::CHANNELS, self.channels);
        for f in self.data.chunks_exact(self.channels) {
            func(F::from_samples(&mut f.iter().copied()).unwrap());
        }
    }

    #[inline]
    fn frames(&self) -> usize {
        self.data.len() / self.channels
    }

    #[inline]
    fn channels(&self) -> usize {
        self.channels
    }

    #[inline]
    fn split_at(self, sample: usize) -> (Self, Self) {
        assert!(sample * self.channels <= self.data.len());

        let (fst, snd) = self.data.split_at(sample * self.channels);
        (
            Interleaved {
                data: fst,
                channels: self.channels,
            },
            Interleaved {
                data: snd,
                channels: self.channels,
            },
        )
    }
}

/// Struct representing interleaved samples.
pub struct Planar<'a, S> {
    data: &'a [&'a [S]],
    start: usize,
    end: usize,
}

impl<'a, S> Planar<'a, S> {
    /// Create a new wrapper around the planar channels and do a sanity check.
    pub fn new(data: &'a [&'a [S]]) -> Result<Self, crate::Error> {
        if data.is_empty() {
            return Err(crate::Error::NoMem);
        }

        if data.iter().any(|d| data[0].len() != d.len()) {
            return Err(crate::Error::NoMem);
        }

        Ok(Planar {
            data,
            start: 0,
            end: data[0].len(),
        })
    }
}

impl<'a, S: Sample> Samples<'a, S> for Planar<'a, S> {
    #[inline]
    fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a S)) {
        assert!(channel < self.data.len());

        for v in &self.data[channel][self.start..self.end] {
            func(v)
        }
    }

    #[inline]
    fn foreach_sample_zipped<U>(
        &self,
        channel: usize,
        iter: impl Iterator<Item = U>,
        mut func: impl FnMut(&'a S, U),
    ) {
        assert!(channel < self.data.len());

        for (v, u) in Iterator::zip(self.data[channel][self.start..self.end].iter(), iter) {
            func(v, u)
        }
    }

    #[inline]
    fn foreach_frame<F: Frame<Sample = S>>(&self, mut func: impl FnMut(F)) {
        let channels = self.data.len();
        assert_eq!(F::CHANNELS, channels);
        for f in self.start..self.end {
            func(F::from_fn(|c| self.data[c][f]));
        }
    }

    #[inline]
    fn frames(&self) -> usize {
        self.end - self.start
    }

    #[inline]
    fn channels(&self) -> usize {
        self.data.len()
    }

    #[inline]
    fn split_at(self, sample: usize) -> (Self, Self) {
        assert!(self.start + sample <= self.end);

        (
            Planar {
                data: self.data,
                start: self.start,
                end: self.start + sample,
            },
            Planar {
                data: self.data,
                start: self.start + sample,
                end: self.end,
            },
        )
    }
}

pub trait Sample:
    dasp_sample::Sample + dasp_sample::Duplex<f32> + dasp_sample::Duplex<f64>
{
    const MAX_AMPLITUDE: f64;

    fn as_f64_raw(self) -> f64;
}

impl Sample for f32 {
    const MAX_AMPLITUDE: f64 = 1.0;

    #[inline(always)]
    fn as_f64_raw(self) -> f64 {
        self as f64
    }
}
impl Sample for f64 {
    const MAX_AMPLITUDE: f64 = 1.0;

    #[inline(always)]
    fn as_f64_raw(self) -> f64 {
        self
    }
}
impl Sample for i16 {
    const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);

    #[inline(always)]
    fn as_f64_raw(self) -> f64 {
        self as f64
    }
}
impl Sample for i32 {
    const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);

    #[inline(always)]
    fn as_f64_raw(self) -> f64 {
        self as f64
    }
}

/// An extension-trait to accumulate samples into a frame
pub trait FrameAccumulator: Frame {
    fn scale_add(&mut self, other: &Self, coeff: f32);
    fn retain_max_samples(&mut self, other: &Self);
}

impl<F: Frame, S> FrameAccumulator for F
where
    S: SampleAccumulator + std::fmt::Debug,
    F: IndexMut<Target = S>,
{
    #[inline(always)]
    fn scale_add(&mut self, other: &Self, coeff: f32) {
        for i in 0..Self::CHANNELS {
            self.index_mut(i).scale_add(*other.index(i), coeff);
        }
    }

    fn retain_max_samples(&mut self, other: &Self) {
        for i in 0..Self::CHANNELS {
            let this = self.index_mut(i);
            let other = other.index(i);
            if *other > *this {
                *this = *other;
            }
        }
    }
}

// Required since std::ops::IndexMut seem to not be implemented for arrays
// making FrameAcc hard to implement for auto-vectorization
// IndexMut seems to be coming to stdlib, when https://github.com/rust-lang/rust/pull/74989
// implemented, this trait can be removed
pub trait IndexMut {
    type Target;
    fn index_mut(&mut self, i: usize) -> &mut Self::Target;
    fn index(&self, i: usize) -> &Self::Target;
}

macro_rules! index_mut_impl {
    ( $channels:expr ) => {
        impl<T: SampleAccumulator> IndexMut for [T; $channels] {
            type Target = T;
            #[inline(always)]
            fn index_mut(&mut self, i: usize) -> &mut Self::Target {
                &mut self[i]
            }
            #[inline(always)]
            fn index(&self, i: usize) -> &Self::Target {
                &self[i]
            }
        }
    };
}

index_mut_impl!(1);
index_mut_impl!(2);
index_mut_impl!(4);
index_mut_impl!(6);
index_mut_impl!(8);

pub trait SampleAccumulator: Sample {
    fn scale_add(&mut self, other: Self, coeff: f32);
}

impl SampleAccumulator for f32 {
    #[inline(always)]
    fn scale_add(&mut self, other: Self, coeff: f32) {
        #[cfg(feature = "precision-true-peak")]
        {
            *self = other.mul_add(coeff, *self);
        }
        #[cfg(not(feature = "precision-true-peak"))]
        {
            *self += other * coeff
        }
    }
}

#[cfg(test)]
pub mod tests {
    use dasp_sample::{FromSample, Sample};

    #[derive(Clone, Debug)]
    pub struct Signal<S: FromSample<f32>> {
        pub data: Vec<S>,
        pub channels: u32,
        pub rate: u32,
    }

    impl<S: Sample + FromSample<f32> + quickcheck::Arbitrary> quickcheck::Arbitrary for Signal<S> {
        fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self {
            use rand::Rng;

            let channels = g.gen_range(1, 16);
            let rate = g.gen_range(16_000, 224_000);
            let num_frames = (rate as f64 * g.gen_range(0.0, 5.0)) as usize;

            let max = g.gen_range(0.0, 1.0);
            let freqs = [
                g.gen_range(20.0, 16_000.0),
                g.gen_range(20.0, 16_000.0),
                g.gen_range(20.0, 16_000.0),
                g.gen_range(20.0, 16_000.0),
            ];
            let volumes = [
                g.gen_range(0.0, 1.0),
                g.gen_range(0.0, 1.0),
                g.gen_range(0.0, 1.0),
                g.gen_range(0.0, 1.0),
            ];
            let volume_scale = 1.0 / volumes.iter().sum::<f32>();
            let mut accumulators = [0.0; 4];
            let steps = [
                2.0 * std::f32::consts::PI * freqs[0] / rate as f32,
                2.0 * std::f32::consts::PI * freqs[1] / rate as f32,
                2.0 * std::f32::consts::PI * freqs[2] / rate as f32,
                2.0 * std::f32::consts::PI * freqs[3] / rate as f32,
            ];

            let mut data = vec![S::from_sample(0.0f32); num_frames * channels as usize];
            for frame in data.chunks_exact_mut(channels as usize) {
                let val = max
                    * (f32::sin(accumulators[0]) * volumes[0]
                        + f32::sin(accumulators[1]) * volumes[1]
                        + f32::sin(accumulators[2]) * volumes[2]
                        + f32::sin(accumulators[3]) * volumes[3])
                    / volume_scale;

                for sample in frame.iter_mut() {
                    *sample = S::from_sample(val);
                }

                for (acc, step) in accumulators.iter_mut().zip(steps.iter()) {
                    *acc += step;
                }
            }

            Signal {
                data,
                channels,
                rate,
            }
        }

        fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
            SignalShrinker::boxed(self.clone())
        }
    }

    struct SignalShrinker<A: FromSample<f32>> {
        seed: Signal<A>,
        /// How many elements to take
        size: usize,
        /// Whether we tried with one channel already
        tried_one_channel: bool,
    }

    impl<A: FromSample<f32> + quickcheck::Arbitrary> SignalShrinker<A> {
        fn boxed(seed: Signal<A>) -> Box<dyn Iterator<Item = Signal<A>>> {
            let channels = seed.channels;
            Box::new(SignalShrinker {
                seed,
                size: 0,
                tried_one_channel: channels == 1,
            })
        }
    }

    impl<A> Iterator for SignalShrinker<A>
    where
        A: FromSample<f32> + quickcheck::Arbitrary,
    {
        type Item = Signal<A>;
        fn next(&mut self) -> Option<Signal<A>> {
            if self.size < self.seed.data.len() {
                // Generate a smaller vector by removing size elements
                let xs1 = if self.tried_one_channel {
                    Vec::from(&self.seed.data[..self.size])
                } else {
                    self.seed
                        .data
                        .iter()
                        .cloned()
                        .step_by(self.seed.channels as usize)
                        .take(self.size)
                        .collect()
                };

                if self.size == 0 {
                    self.size = if self.tried_one_channel {
                        self.seed.channels as usize
                    } else {
                        1
                    };
                } else {
                    self.size *= 2;
                }

                Some(Signal {
                    data: xs1,
                    channels: if self.tried_one_channel {
                        self.seed.channels
                    } else {
                        1
                    },
                    rate: self.seed.rate,
                })
            } else if !self.tried_one_channel {
                self.tried_one_channel = true;
                self.size = 0;
                self.next()
            } else {
                None
            }
        }
    }
}