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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! This library contains an implementation of EBU R-128 loudness measurement.
//!
//! It exposes functions to calculate the loudess of a chunk of audio,
//! plus a higher-level interface that calculates loudness over time
//! according the restrictions defined in EBU R-128.
//!
//! TODO:
//! * Support sample rates other than 48kHz
//! * Become agnostic to audio chunk size

#![warn(missing_docs)]

#[macro_use]
extern crate enum_display_derive;

use biquad::{Biquad, Coefficients, DirectForm1};
use std::error::Error;
use std::fmt::Display;
use std::result::Result;

// Spec defines 400ms block overlapping by 75%
const AUDIO_BLOCK_S: f64 = 0.1;
const MOMENTARY_BLOCK_S: f64 = 0.4;
const SHORT_TERM_BLOCK_S: f64 = 3.;
const GATING_THRESHOLD_ABSOLUTE: f64 = -70.;

/// Enumeration of audio channels in the order they usually appear interleaved.
#[derive(PartialEq, Eq, Hash, Copy, Clone, Ord, PartialOrd, Debug, Display)]
pub enum Channel {
    /// Left channel
    Left = 0,
    /// Right channel
    Right = 1,
    /// Centre chanel
    Centre = 2,
    /// Low-frequecy-effects channel (not used)
    Lfe = 3,
    /// Left surround channel
    LeftSurround = 4,
    /// Right surround channel
    RightSurround = 5,
}

impl Default for Channel {
    fn default() -> Self {
        Channel::Left
    }
}

/// EBU R-128 specifes that audio shall be split into gating blocks and only
/// those above a threshold shall count towards the loudness.
/// `GatingType` will determine that threshold in line with the spcification.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Display)]
pub enum GatingType {
    /// All blocks are considered
    None,
    /// Blocks above -70 LUFS are considered
    Absolute,
    /// Two-pass calculation. Absolute loudness is caluclated first,
    /// then a threshold 10 LUFS bellow the calculated value is applied.
    Relative,
}

impl Default for GatingType {
    fn default() -> Self {
        GatingType::None
    }
}

/// Determines how much history a `State` will store for future loudness calculations
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Display)]
pub enum Mode {
    /// All blocks are stored
    Normal,
    /// Only enough block so calculate short-term loudness are stored
    Streaming,
}

impl Default for Mode {
    fn default() -> Self {
        Mode::Normal
    }
}

fn channel_from_index(index: usize) -> Channel {
    match index {
        0 => Channel::Left,
        1 => Channel::Right,
        2 => Channel::Centre,
        3 => Channel::Lfe,
        4 => Channel::LeftSurround,
        _ => Channel::RightSurround,
    }
}

/// Errors resulting from loudness calculations
#[derive(PartialEq, Eq, Hash, Copy, Clone, Ord, PartialOrd, Debug, Display)]
pub enum Ebur128Error {
    /// Loudness calculation requires more audio to be analyzed before giving a sensible value.
    NotEnoughAudio,
    /// All audio in the applicable time frame was below the loudness threshold.
    TooQuiet,
    /// The requested calculation is not available in this mode.
    NotAvailable,
    /// Audio was fed into `State::process()` with an unsupported block size.
    WrongBlockSize,
}

impl Error for Ebur128Error {}

fn root_mean<I: ExactSizeIterator<Item = f64>>(values: I) -> f64 {
    let divisor = values.len() as f64;
    values.map(|v| v * v).sum::<f64>() / divisor
}

fn channel_gain(channel: Channel) -> f64 {
    match channel {
        Channel::Left => 1.,
        Channel::Right => 1.,
        Channel::Centre => 1.,
        Channel::LeftSurround => 1.41,
        Channel::RightSurround => 1.41,
        _ => 0.,
    }
}

/// These filter co-efficients are taken from ITU-R BS.1770-2 and
/// require a 48kHz sampling rate.
fn get_filters() -> (DirectForm1<f64>, DirectForm1<f64>) {
    let stage1 = Coefficients {
        a1: -1.69065929318241,
        a2: 0.73248077421585,
        b0: 1.53512485958697,
        b1: -2.69169618940638,
        b2: 1.19839281085285,
    };

    let stage2 = Coefficients {
        a1: -1.99004745483398,
        a2: 0.99007225036621,
        b0: 1.,
        b1: -2.,
        b2: 1.,
    };

    (
        DirectForm1::<f64>::new(stage1),
        DirectForm1::<f64>::new(stage2),
    )
}

/// Calculate the loudness of audio in a single channel
/// ```
/// let samples = (0..4800).map(|i| (1000. * (i as f64 / 48000.)).sin());
/// let channel = ebur128rs::Channel::Left;
/// assert!(ebur128rs::calculate_loudness(samples.into_iter(), channel) > -70.);
/// ```
pub fn calculate_loudness<I: ExactSizeIterator<Item = f64>>(samples: I, channel: Channel) -> f64 {
    root_mean(samples) * channel_gain(channel)
}

fn deinterleave<I: ExactSizeIterator<Item = f64>>(
    samples: I,
    num_channels: usize,
) -> Vec<Vec<f64>> {
    let mut deinterleaved: Vec<Vec<f64>> =
        vec![Vec::with_capacity(samples.len() / num_channels); num_channels];
    let index = (0..num_channels).cycle();
    for (sample, idx) in samples.zip(index) {
        deinterleaved[idx].push(sample);
    }
    deinterleaved
}

fn deinterleave_and_filter<I: ExactSizeIterator<Item = f64>>(
    interleaved_samples: I,
    num_channels: usize,
) -> Vec<Vec<f64>> {
    let mut audio = deinterleave(interleaved_samples, num_channels);
    let mut filters = vec![get_filters(); num_channels];
    for (channel, (mut f1, mut f2)) in audio.iter_mut().zip(filters.iter_mut()) {
        for sample in channel.iter_mut() {
            *sample = f2.run(f1.run(*sample));
        }
    }
    audio
}

/// Calculate the loudness of interleaved audio
/// ```
/// let left = (0..4800).map(|i| (1000. * (i as f64 / 48000.)).sin());
/// let right = left.clone().map(|s| s * 0.5);
/// let samples: Vec<f64> = left.zip(right).flat_map(|(l,r)| vec![l, r].into_iter()).collect();
/// assert!(ebur128rs::calculate_loudness_interleaved(samples.into_iter(), 2) > -70.);
/// ```
pub fn calculate_loudness_interleaved<I: ExactSizeIterator<Item = f64>>(
    interleaved_samples: I,
    num_channels: usize,
) -> f64 {
    let audio = deinterleave_and_filter(interleaved_samples, num_channels);
    let mut sum = 0f64;
    for (index, channel_audio) in audio.into_iter().enumerate() {
        let channel = channel_from_index(index);
        if channel == Channel::Lfe {
            continue;
        }
        sum += calculate_loudness(channel_audio.iter().cloned(), channel);
    }
    -0.691 + (10. * sum.log10())
}

/// Struct that calculates consecutive loudness blocks and offers
/// various loudness calculation types.
/// ```
/// use ebur128rs::{State, GatingType};
///
/// let left = (0..4800).map(|i| (1000. * (i as f64 / 48000.)).sin());
/// let right = left.clone().map(|s| s * 0.5);
/// let samples: Vec<f64> = left.zip(right).flat_map(|(l,r)| vec![l, r].into_iter()).collect();
/// let sample_iter = samples.into_iter();
///
/// let mut state = State::default();
/// for _ in (0..10) {
///     assert!(state.process(sample_iter.clone()).is_ok());
///     println!("{:?}", state.integrated_loudness(GatingType::Absolute));
/// }
/// ```
#[derive(Clone, Debug)]
pub struct State {
    sample_rate: f64,
    channels: usize,
    loudness_blocks: Vec<f64>,
    running_loudness: f64,
    blocks_processed: f64,
    mode: Mode,
}

impl Default for State {
    /// Construct a new loudness state with sample rate 48000Hz, 2 channels, in non-streaming mode.
    /// ```
    /// use ebur128rs::{State, GatingType};
    ///
    /// let samples = (0..9600).map(|i| (1000. * (i as f64 / 48000.)).sin());
    ///
    /// let mut state = State::default();
    /// state.process(samples);
    ///
    /// println!("{:?}", state.integrated_loudness(GatingType::Absolute));
    /// ```
    fn default() -> Self {
        State::new(48000., 2, Mode::Normal)
    }
}

impl State {
    /// Construct a new loudness state. Use `new` instead of `default` if you require
    /// any channel count other than 2 or if you need streaming mode.
    ///
    /// If `streaming` is `false`, `State` will keep a record of the loudness of every
    /// block ever processed. If `streaming` is `true`, `State` will limit its records
    /// to the number required to calculate the short-term loudness (3 seconds worth),
    /// and integrated loudness with a relative threshold will not be available. All
    /// other loudness calculations will work as normal.
    ///
    /// Currently only 48000Hz sample rate is supported. Using other sample rates will
    /// not produce any errors but will affect the accuracy of the loudness measurement.
    /// ```
    /// let mut state = ebur128rs::State::new(48000., 1, ebur128rs::Mode::Streaming);
    /// ```
    pub fn new(sample_rate: f64, channels: usize, mode: Mode) -> State {
        State {
            sample_rate: sample_rate,
            channels: channels,
            loudness_blocks: vec![],
            running_loudness: 0.,
            blocks_processed: 0.,
            mode: mode,
        }
    }

    fn short_term_loudness_blocks() -> usize {
        (SHORT_TERM_BLOCK_S / AUDIO_BLOCK_S) as usize
    }

    fn momentary_loudness_blocks() -> usize {
        (MOMENTARY_BLOCK_S / AUDIO_BLOCK_S) as usize
    }

    fn samples_per_audio_block(&self) -> usize {
        (AUDIO_BLOCK_S * self.sample_rate) as usize * self.channels
    }

    fn gating_threshold(&self, gating: GatingType) -> f64 {
        match gating {
            GatingType::None => f64::NEG_INFINITY,
            GatingType::Absolute => GATING_THRESHOLD_ABSOLUTE,
            GatingType::Relative => self.integrated_loudness(GatingType::Absolute).unwrap() - 10., // Blind unwrap should be fine - function is not public
        }
    }

    fn update_running_loudness(&mut self, val: f64) {
        self.blocks_processed += 1.;
        self.running_loudness += (val - self.running_loudness) / self.blocks_processed;
    }

    fn store_loudness_block(&mut self, loudness: f64) {
        self.loudness_blocks.push(loudness);
        if self.mode == Mode::Streaming {
            while self.loudness_blocks.len() > Self::short_term_loudness_blocks() {
                self.loudness_blocks.remove(0);
            }
        }
    }

    /// Process a block of interleaved samples. The block must be exactly 100ms long.
    /// ```
    /// let mut state = ebur128rs::State::default(); // 2 channels, 48000 Hz
    /// assert!(state.process(vec![0.; 9600].into_iter()).is_ok());
    /// assert!(state.process(vec![0.; 9601].into_iter()).is_err());
    /// assert!(state.process(vec![0.; 9599].into_iter()).is_err());
    /// ```
    pub fn process<I: ExactSizeIterator<Item = f64>>(
        &mut self,
        interleaved_samples: I,
    ) -> Result<(), Ebur128Error> {
        if interleaved_samples.len() != self.samples_per_audio_block() {
            return Err(Ebur128Error::WrongBlockSize);
        }
        let loudness = calculate_loudness_interleaved(interleaved_samples, self.channels);
        self.store_loudness_block(loudness);
        if self.mode == Mode::Streaming {
            self.update_running_loudness(loudness);
        }
        Ok(())
    }

    fn loudness(
        &self,
        gating: GatingType,
        starting_block_index: usize,
    ) -> Result<f64, Ebur128Error> {
        let threshold = self.gating_threshold(gating);

        let blocks_above_threshold = self.loudness_blocks[starting_block_index..]
            .iter()
            .filter(|loudness| **loudness >= threshold)
            .count();

        if blocks_above_threshold == 0 {
            return Err(Ebur128Error::TooQuiet);
        }

        Ok(self.loudness_blocks[starting_block_index..]
            .iter()
            .filter(|loudness| **loudness >= threshold)
            .sum::<f64>()
            / blocks_above_threshold as f64)
    }

    /// Calculate the loudness of the entire history.
    /// ```
    /// use ebur128rs::{State, GatingType};
    ///
    /// let samples = (0..9600).map(|i| (1000. * (i as f64 / 48000.)).sin());
    ///
    /// let mut state = State::default(); // 2 channels, 48000 Hz
    /// for _ in (0..10) {
    ///     assert!(state.process(samples.clone()).is_ok());
    /// }
    ///
    /// println!("Integrated loudness is {:?}", state.integrated_loudness(GatingType::Relative));
    /// ```
    pub fn integrated_loudness(&self, gating: GatingType) -> Result<f64, Ebur128Error> {
        if self.mode == Mode::Streaming {
            if gating == GatingType::Relative {
                return Err(Ebur128Error::NotAvailable);
            }
            if self.blocks_processed == 0. {
                return Err(Ebur128Error::NotEnoughAudio);
            }
            return Ok(self.running_loudness);
        }
        self.loudness(gating, 0)
    }

    /// Calculate the loudness of the last 3 seconds.
    /// ```
    /// use ebur128rs::{State, GatingType};
    ///
    /// let samples = (0..9600).map(|i| (1000. * (i as f64 / 48000.)).sin());
    ///
    /// let mut state = State::default(); // 2 channels, 48000 Hz
    /// for _ in (0..10) {
    ///     assert!(state.process(samples.clone()).is_ok());
    /// }
    ///
    /// println!("Integrated loudness is {:?}", state.short_term_loudness(GatingType::Relative));
    /// ```
    pub fn short_term_loudness(&self, gating: GatingType) -> Result<f64, Ebur128Error> {
        let starting_block_idx = self
            .loudness_blocks
            .len()
            .checked_sub(Self::short_term_loudness_blocks())
            .unwrap_or(0);
        self.loudness(gating, starting_block_idx)
    }

    /// Calculate the loudness of the last 400 milliseconds.
    /// ```
    /// use ebur128rs::{State, GatingType};
    ///
    /// let samples = (0..9600).map(|i| (1000. * (i as f64 / 48000.)).sin());
    ///
    /// let mut state = State::default(); // 2 channels, 48000 Hz
    /// for _ in (0..10) {
    ///     assert!(state.process(samples.clone()).is_ok());
    /// }
    ///
    /// println!("Integrated loudness is {:?}", state.momentary_loudness(GatingType::Relative));
    /// ```
    pub fn momentary_loudness(&self, gating: GatingType) -> Result<f64, Ebur128Error> {
        let starting_block_idx = self
            .loudness_blocks
            .len()
            .checked_sub(Self::momentary_loudness_blocks())
            .unwrap_or(0);
        self.loudness(gating, starting_block_idx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dasp_signal::{self as signal, Signal};
    use more_asserts::*;
    use rand::{thread_rng, Rng};

    macro_rules! assert_close_enough {
        ($left:expr, $right:expr, $tollerance:expr) => {
            let (left, right, tollerance) = (&($left), &($right), &($tollerance));
            assert_ge!(*left, *right - *tollerance);
            assert_le!(*left, *right + *tollerance);
        };
    }

    fn create_noise(length: usize, scale: f64) -> Vec<f64> {
        let mut rng = thread_rng();
        (0..length).map(|_| rng.gen::<f64>() * scale).collect()
    }

    fn tone_1k() -> Vec<f64> {
        signal::rate(48000.)
            .const_hz(1000.)
            .sine()
            .take(48000)
            .collect::<Vec<f64>>()
    }

    #[test]
    fn new_state() {
        let state = State::default();
        assert!(state.integrated_loudness(GatingType::None).is_err());
    }

    #[test]
    fn input_too_short() {
        let mut state = State::default();
        assert!(state.process(vec![0f64; 9599].into_iter()).is_err());
    }

    #[test]
    fn input_too_long() {
        let mut state = State::default();
        assert!(state.process(vec![0f64; 9601].into_iter()).is_err());
    }

    #[test]
    fn input_correct_length() {
        let mut state = State::default();
        assert!(state.process(vec![0f64; 9600].into_iter()).is_ok());
    }

    #[test]
    fn integrated_loudness_multiple_frames() {
        let mut state = State::default();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness1 = state.integrated_loudness(GatingType::None).unwrap();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness2 = state.integrated_loudness(GatingType::None).unwrap();
        assert_close_enough!(loudness1, loudness2, 0.1);
    }

    #[test]
    fn integrated_loudness_ungated() {
        let mut state = State::default();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness1 = state.integrated_loudness(GatingType::None).unwrap();
        assert!(state.process(create_noise(9600, 0.1).into_iter()).is_ok());
        let loudness2 = state.integrated_loudness(GatingType::None).unwrap();
        assert!(state.process(create_noise(9600, 0.9).into_iter()).is_ok());
        let loudness3 = state.integrated_loudness(GatingType::None).unwrap();
        assert_gt!(loudness1, loudness2);
        assert_lt!(loudness2, loudness3);
    }

    #[test]
    fn integrated_loudness_gated_absolute() {
        let mut state = State::default();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness1 = state.integrated_loudness(GatingType::Absolute).unwrap();
        assert!(state
            .process(create_noise(9600, 0.0001).into_iter())
            .is_ok());
        let loudness2 = state.integrated_loudness(GatingType::Absolute).unwrap();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness3 = state.integrated_loudness(GatingType::Absolute).unwrap();
        assert_eq!(loudness1, loudness2);
        assert_close_enough!(loudness1, loudness3, 0.1);
    }

    #[test]
    fn integrated_loudness_gated_relative() {
        let mut state = State::default();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness1 = state.integrated_loudness(GatingType::Relative).unwrap();
        assert!(state.process(create_noise(9600, 0.01).into_iter()).is_ok());
        let loudness2 = state.integrated_loudness(GatingType::Relative).unwrap();
        assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        let loudness3 = state.integrated_loudness(GatingType::Relative).unwrap();
        assert_eq!(loudness1, loudness2);
        assert_close_enough!(loudness1, loudness3, 0.1);
    }

    #[test]
    fn short_term_loudness_ungated() {
        let mut state = State::default();
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.1).into_iter()).is_ok());
        }
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.9).into_iter()).is_ok());
        }
        let il = state.integrated_loudness(GatingType::None).unwrap();
        let stl = state.short_term_loudness(GatingType::None).unwrap();
        assert_gt!(stl, il);
    }

    #[test]
    fn momentary_loudness_ungated() {
        let mut state = State::default();
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.1).into_iter()).is_ok());
        }
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        }
        for _ in 0..4 {
            assert!(state.process(create_noise(9600, 0.9).into_iter()).is_ok());
        }
        let il = state.integrated_loudness(GatingType::None).unwrap();
        let stl = state.short_term_loudness(GatingType::None).unwrap();
        let ml = state.momentary_loudness(GatingType::None).unwrap();
        assert_lt!(il, stl);
        assert_lt!(stl, ml);
    }

    #[test]
    fn everything_below_threshold() {
        let mut state = State::default();
        for _ in 0..30 {
            assert_eq!(
                state
                    .process(create_noise(9600, 0.0001).into_iter())
                    .is_ok(),
                true
            );
        }
        assert_eq!(
            state.integrated_loudness(GatingType::Absolute).is_err(),
            true
        );
    }

    #[test]
    fn streaming_mode_integrated_loudness() {
        let mut state = State::new(48000., 1, Mode::Streaming);
        for _ in 0..30 {
            assert_eq!(
                state.process(create_noise(4800, 0.5).into_iter()).is_ok(),
                true
            );
        }
        let il = state.integrated_loudness(GatingType::Absolute).unwrap();
        assert_close_enough!(il, -13.6, 0.1);
    }

    #[test]
    fn streaming_mode_no_relative_threshold() {
        let mut state = State::new(48000., 1, Mode::Streaming);
        for _ in 0..30 {
            assert_eq!(
                state.process(create_noise(4800, 0.5).into_iter()).is_ok(),
                true
            );
        }
        assert_eq!(
            state.integrated_loudness(GatingType::Relative).is_err(),
            true
        );
    }

    #[test]
    fn streaming_mode_short_term_loudness_ungated() {
        let mut state = State::new(48000., 2, Mode::Streaming);
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.1).into_iter()).is_ok());
        }
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.9).into_iter()).is_ok());
        }
        let il = state.integrated_loudness(GatingType::None).unwrap();
        let stl = state.short_term_loudness(GatingType::None).unwrap();
        assert_gt!(stl, il);
    }

    #[test]
    fn streaming_mode_momentary_loudness_ungated() {
        let mut state = State::new(48000., 2, Mode::Streaming);
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.1).into_iter()).is_ok());
        }
        for _ in 0..30 {
            assert!(state.process(create_noise(9600, 0.5).into_iter()).is_ok());
        }
        for _ in 0..4 {
            assert!(state.process(create_noise(9600, 0.9).into_iter()).is_ok());
        }
        let il = state.integrated_loudness(GatingType::None).unwrap();
        let stl = state.short_term_loudness(GatingType::None).unwrap();
        let ml = state.momentary_loudness(GatingType::None).unwrap();
        assert_lt!(il, stl);
        assert_lt!(stl, ml);
    }

    #[test]
    fn sine() {
        // Specification states:
        // "If a 0 dB FS 1 kHz sine wave is applied to the left, centre,
        // or right channel input, the indicated loudness will equal -3.01 LKFS."
        let mut state = State::new(48000., 1, Mode::Normal);
        assert!(state.process(tone_1k().into_iter().take(4800)).is_ok());
        let loudness = state.integrated_loudness(GatingType::Absolute).unwrap();
        assert_close_enough!(loudness, -3.01, 0.01);
    }

    #[test]
    fn channel_loudness() {
        assert_eq!(
            calculate_loudness(vec![1., 1., 1.].into_iter(), Channel::Left),
            1.
        );
        assert_eq!(
            calculate_loudness(vec![1., 1., 1.].into_iter(), Channel::Right),
            1.
        );
        assert_eq!(
            calculate_loudness(vec![1., 1., 1.].into_iter(), Channel::Centre),
            1.
        );
        assert_eq!(
            calculate_loudness(vec![1., 1., 1.].into_iter(), Channel::LeftSurround),
            1.41
        );
        assert_eq!(
            calculate_loudness(vec![1., 1., 1.].into_iter(), Channel::RightSurround),
            1.41
        );
    }

    #[test]
    fn deinterleave_works() {
        assert_eq!(
            deinterleave(vec![0., 1., 0., 1.].into_iter(), 2),
            vec![[0., 0.,], [1., 1.,]]
        );
    }

    #[test]
    fn deinterleave_and_filter_works() {
        let (mut f1l, mut f2l) = get_filters();
        let (mut f1r, mut f2r) = get_filters();

        let left_result: Vec<f64> = vec![0., 1., 1., 1., 1., 1.]
            .into_iter()
            .map(|s| f2l.run(f1l.run(s)))
            .collect();

        let right_result: Vec<f64> = vec![0., 2., 2., 2., 2., 2.]
            .into_iter()
            .map(|s| f2r.run(f1r.run(s)))
            .collect();

        let samples: Vec<f64> = vec![0., 0., 1., 2., 1., 2., 1., 2., 1., 2., 1., 2.];
        let result = deinterleave_and_filter(samples.into_iter(), 2);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], left_result);
        assert_eq!(result[1], right_result);
    }

    #[test]
    fn filters_work() {
        let mut samples = vec![0f64];
        samples.append(&mut vec![1f64; 19]);
        let (mut f1, mut f2) = get_filters();
        let result: Vec<f64> = samples.into_iter().map(|s| f2.run(f1.run(s))).collect();
        assert_eq!(result[0], 0.);
        assert_gt!(result[1], result[0]);
        for i in 2..20 {
            assert_lt!(result[i], result[i - 1]);
        }
    }

    #[test]
    fn loudness_interleaved_mono() {
        let result = calculate_loudness_interleaved(create_noise(48000, 0.5).into_iter(), 1);
        assert_ne!(result, 0.);
    }

    #[test]
    fn loudness_interleaved_stereo() {
        let result = calculate_loudness_interleaved(create_noise(48000 * 2, 0.5).into_iter(), 2);
        assert_ne!(result, 0.);
    }

    #[test]
    fn loudness_interleaved_5_1() {
        let result = calculate_loudness_interleaved(create_noise(48000 * 6, 0.5).into_iter(), 6);
        assert_ne!(result, 0.);
    }
}