Welcome to mirror list, hosted at ThFree Co, Russian Federation.

imp.rs « ebur128level « src « audiofx « audio - github.com/sdroege/gst-plugin-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c8b1f115e074e70511b3b7d0e323168352fa605b (plain)
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// Copyright (C) 2021 Sebastian Dröge <sebastian@centricular.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// <https://mozilla.org/MPL/2.0/>.
//
// SPDX-License-Identifier: MPL-2.0

use gst::glib;
use gst::prelude::*;
use gst::subclass::prelude::*;
use gst_base::prelude::*;
use gst_base::subclass::prelude::*;

use std::i32;
use std::sync::atomic;
use std::sync::Mutex;

use once_cell::sync::Lazy;

use byte_slice_cast::*;

use smallvec::SmallVec;

use atomic_refcell::AtomicRefCell;

static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
    gst::DebugCategory::new(
        "ebur128level",
        gst::DebugColorFlags::empty(),
        Some("EBU R128 Level"),
    )
});

#[glib::flags(name = "GstEbuR128LevelMode")]
pub(crate) enum Mode {
    #[flags_value(name = "Calculate momentary loudness (400ms)", nick = "momentary")]
    MOMENTARY = 0b00000001,
    #[flags_value(name = "Calculate short-term loudness (3s)", nick = "short-term")]
    SHORT_TERM = 0b00000010,
    #[flags_value(
        name = "Calculate relative threshold and global loudness",
        nick = "global"
    )]
    GLOBAL = 0b00000100,
    #[flags_value(name = "Calculate loudness range", nick = "loudness-range")]
    LOUDNESS_RANGE = 0b00001000,
    #[flags_value(name = "Calculate sample peak", nick = "sample-peak")]
    SAMPLE_PEAK = 0b00010000,
    #[flags_value(name = "Calculate true peak", nick = "true-peak")]
    TRUE_PEAK = 0b00100000,
}

impl From<Mode> for ebur128::Mode {
    fn from(mode: Mode) -> Self {
        // Should use histogram mode as otherwise the history will grow forever
        let mut ebur128_mode = ebur128::Mode::HISTOGRAM;
        if mode.contains(Mode::MOMENTARY) {
            ebur128_mode.set(ebur128::Mode::M, true);
        }
        if mode.contains(Mode::SHORT_TERM) {
            ebur128_mode.set(ebur128::Mode::S, true);
        }
        if mode.contains(Mode::GLOBAL) {
            ebur128_mode.set(ebur128::Mode::I, true);
        }
        if mode.contains(Mode::LOUDNESS_RANGE) {
            ebur128_mode.set(ebur128::Mode::LRA, true);
        }
        if mode.contains(Mode::SAMPLE_PEAK) {
            ebur128_mode.set(ebur128::Mode::SAMPLE_PEAK, true);
        }
        if mode.contains(Mode::TRUE_PEAK) {
            ebur128_mode.set(ebur128::Mode::TRUE_PEAK, true);
        }

        ebur128_mode
    }
}

const DEFAULT_MODE: Mode = Mode::all();
const DEFAULT_POST_MESSAGES: bool = true;
const DEFAULT_INTERVAL: gst::ClockTime = gst::ClockTime::SECOND;

#[derive(Debug, Clone, Copy)]
struct Settings {
    mode: Mode,
    post_messages: bool,
    interval: gst::ClockTime,
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            mode: DEFAULT_MODE,
            post_messages: DEFAULT_POST_MESSAGES,
            interval: DEFAULT_INTERVAL,
        }
    }
}

struct State {
    info: gst_audio::AudioInfo,
    ebur128: ebur128::EbuR128,
    num_frames: u64,
    interval_frames: gst::ClockTime,
    interval_frames_remaining: gst::ClockTime,
}

#[derive(Default)]
pub struct EbuR128Level {
    settings: Mutex<Settings>,
    state: AtomicRefCell<Option<State>>,
    reset: atomic::AtomicBool,
}

#[glib::object_subclass]
impl ObjectSubclass for EbuR128Level {
    const NAME: &'static str = "GstEbuR128Level";
    type Type = super::EbuR128Level;
    type ParentType = gst_base::BaseTransform;
}

impl ObjectImpl for EbuR128Level {
    fn signals() -> &'static [glib::subclass::Signal] {
        static SIGNALS: Lazy<Vec<glib::subclass::Signal>> = Lazy::new(|| {
            vec![glib::subclass::Signal::builder("reset")
                .action()
                .class_handler(|_token, args| {
                    let this = args[0].get::<super::EbuR128Level>().unwrap();
                    let imp = this.imp();

                    gst::info!(CAT, obj: this, "Resetting measurements",);
                    imp.reset.store(true, atomic::Ordering::SeqCst);

                    None
                })
                .build()]
        });

        &*SIGNALS
    }

    fn properties() -> &'static [glib::ParamSpec] {
        static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
            vec![
                glib::ParamSpecFlags::builder::<Mode>("mode")
                    .nick("Mode")
                    .blurb("Selection of metrics to calculate")
                    .default_value(DEFAULT_MODE)
                    .mutable_ready()
                    .build(),
                glib::ParamSpecBoolean::builder("post-messages")
                    .nick("Post Messages")
                    .blurb("Whether to post messages on the bus for each interval")
                    .default_value(DEFAULT_POST_MESSAGES)
                    .mutable_playing()
                    .build(),
                glib::ParamSpecUInt64::builder("interval")
                    .nick("Interval")
                    .blurb("Interval in nanoseconds for posting messages")
                    .maximum(u64::MAX - 1)
                    .default_value(DEFAULT_INTERVAL.nseconds())
                    .mutable_ready()
                    .build(),
            ]
        });

        PROPERTIES.as_ref()
    }

    fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
        let mut settings = self.settings.lock().unwrap();
        match pspec.name() {
            "mode" => {
                let mode = value.get().expect("type checked upstream");
                gst::info!(
                    CAT,
                    imp: self,
                    "Changing mode from {:?} to {:?}",
                    settings.mode,
                    mode
                );
                settings.mode = mode;
            }
            "post-messages" => {
                let post_messages = value.get().expect("type checked upstream");
                gst::info!(
                    CAT,
                    imp: self,
                    "Changing post-messages from {} to {}",
                    settings.post_messages,
                    post_messages
                );
                settings.post_messages = post_messages;
            }
            "interval" => {
                let interval = value.get::<u64>().unwrap().nseconds();
                gst::info!(
                    CAT,
                    imp: self,
                    "Changing interval from {} to {}",
                    settings.interval,
                    interval,
                );
                settings.interval = interval;
            }
            _ => unimplemented!(),
        }
    }

    fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
        let settings = self.settings.lock().unwrap();
        match pspec.name() {
            "mode" => settings.mode.to_value(),
            "post-messages" => settings.post_messages.to_value(),
            "interval" => settings.interval.to_value(),
            _ => unimplemented!(),
        }
    }
}

impl GstObjectImpl for EbuR128Level {}

impl ElementImpl for EbuR128Level {
    fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
        static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
            gst::subclass::ElementMetadata::new(
                "EBU R128 Loudness Level Measurement",
                "Filter/Analyzer/Audio",
                "Measures different loudness metrics according to EBU R128",
                "Sebastian Dröge <sebastian@centricular.com>",
            )
        });

        Some(&*ELEMENT_METADATA)
    }

    fn pad_templates() -> &'static [gst::PadTemplate] {
        static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
            let caps = gst_audio::AudioCapsBuilder::new()
                .format_list([
                    gst_audio::AUDIO_FORMAT_S16,
                    gst_audio::AUDIO_FORMAT_S32,
                    gst_audio::AUDIO_FORMAT_F32,
                    gst_audio::AUDIO_FORMAT_F64,
                ])
                // Limit from ebur128
                .rate_range(1..2_822_400)
                // Limit from ebur128
                .channels_range(1..64)
                .layout_list([
                    gst_audio::AudioLayout::Interleaved,
                    gst_audio::AudioLayout::NonInterleaved,
                ])
                .build();
            let src_pad_template = gst::PadTemplate::new(
                "src",
                gst::PadDirection::Src,
                gst::PadPresence::Always,
                &caps,
            )
            .unwrap();

            let sink_pad_template = gst::PadTemplate::new(
                "sink",
                gst::PadDirection::Sink,
                gst::PadPresence::Always,
                &caps,
            )
            .unwrap();

            vec![src_pad_template, sink_pad_template]
        });

        PAD_TEMPLATES.as_ref()
    }
}

impl BaseTransformImpl for EbuR128Level {
    const MODE: gst_base::subclass::BaseTransformMode =
        gst_base::subclass::BaseTransformMode::AlwaysInPlace;
    const PASSTHROUGH_ON_SAME_CAPS: bool = true;
    const TRANSFORM_IP_ON_PASSTHROUGH: bool = true;

    fn set_caps(&self, incaps: &gst::Caps, _outcaps: &gst::Caps) -> Result<(), gst::LoggableError> {
        let info = match gst_audio::AudioInfo::from_caps(incaps) {
            Err(_) => return Err(gst::loggable_error!(CAT, "Failed to parse input caps")),
            Ok(info) => info,
        };

        gst::debug!(CAT, imp: self, "Configured for caps {}", incaps,);

        let settings = *self.settings.lock().unwrap();

        let mut ebur128 = ebur128::EbuR128::new(info.channels(), info.rate(), settings.mode.into())
            .map_err(|err| gst::loggable_error!(CAT, "Failed to create EBU R128: {}", err))?;

        // Map channel positions if we can to give correct weighting
        if let Some(positions) = info.positions() {
            let channel_map = positions
                .iter()
                .map(|p| {
                    match p {
                        gst_audio::AudioChannelPosition::Mono => ebur128::Channel::DualMono,
                        gst_audio::AudioChannelPosition::FrontLeft => ebur128::Channel::Left,
                        gst_audio::AudioChannelPosition::FrontRight => ebur128::Channel::Right,
                        gst_audio::AudioChannelPosition::FrontCenter => ebur128::Channel::Center,
                        gst_audio::AudioChannelPosition::Lfe1
                        | gst_audio::AudioChannelPosition::Lfe2 => ebur128::Channel::Unused,
                        gst_audio::AudioChannelPosition::RearLeft => ebur128::Channel::Mp135,
                        gst_audio::AudioChannelPosition::RearRight => ebur128::Channel::Mm135,
                        gst_audio::AudioChannelPosition::FrontLeftOfCenter => {
                            ebur128::Channel::MpSC
                        }
                        gst_audio::AudioChannelPosition::FrontRightOfCenter => {
                            ebur128::Channel::MmSC
                        }
                        gst_audio::AudioChannelPosition::RearCenter => ebur128::Channel::Mp180,
                        gst_audio::AudioChannelPosition::SideLeft => ebur128::Channel::Mp090,
                        gst_audio::AudioChannelPosition::SideRight => ebur128::Channel::Mm090,
                        gst_audio::AudioChannelPosition::TopFrontLeft => ebur128::Channel::Up030,
                        gst_audio::AudioChannelPosition::TopFrontRight => ebur128::Channel::Um030,
                        gst_audio::AudioChannelPosition::TopFrontCenter => ebur128::Channel::Up000,
                        gst_audio::AudioChannelPosition::TopCenter => ebur128::Channel::Tp000,
                        gst_audio::AudioChannelPosition::TopRearLeft => ebur128::Channel::Up135,
                        gst_audio::AudioChannelPosition::TopRearRight => ebur128::Channel::Um135,
                        gst_audio::AudioChannelPosition::TopSideLeft => ebur128::Channel::Up090,
                        gst_audio::AudioChannelPosition::TopSideRight => ebur128::Channel::Um090,
                        gst_audio::AudioChannelPosition::TopRearCenter => ebur128::Channel::Up180,
                        gst_audio::AudioChannelPosition::BottomFrontCenter => {
                            ebur128::Channel::Bp000
                        }
                        gst_audio::AudioChannelPosition::BottomFrontLeft => ebur128::Channel::Bp045,
                        gst_audio::AudioChannelPosition::BottomFrontRight => {
                            ebur128::Channel::Bm045
                        }
                        gst_audio::AudioChannelPosition::WideLeft => {
                            ebur128::Channel::Mp135 // Mp110?
                        }
                        gst_audio::AudioChannelPosition::WideRight => {
                            ebur128::Channel::Mm135 // Mm110?
                        }
                        gst_audio::AudioChannelPosition::SurroundLeft => {
                            ebur128::Channel::Mp135 // Mp110?
                        }
                        gst_audio::AudioChannelPosition::SurroundRight => {
                            ebur128::Channel::Mm135 // Mm110?
                        }
                        gst_audio::AudioChannelPosition::Invalid
                        | gst_audio::AudioChannelPosition::None => ebur128::Channel::Unused,
                        val => {
                            gst::debug!(
                                CAT,
                                imp: self,
                                "Unknown channel position {:?}, ignoring channel",
                                val
                            );
                            ebur128::Channel::Unused
                        }
                    }
                })
                .collect::<Vec<_>>();
            ebur128
                .set_channel_map(&channel_map)
                .map_err(|err| gst::loggable_error!(CAT, "Failed to set channel map: {}", err))?;
        } else {
            // Weight all channels equally if we have no channel map
            let channel_map = std::iter::repeat(ebur128::Channel::Center)
                .take(info.channels() as usize)
                .collect::<Vec<_>>();
            ebur128
                .set_channel_map(&channel_map)
                .map_err(|err| gst::loggable_error!(CAT, "Failed to set channel map: {}", err))?;
        }

        let interval_frames = settings
            .interval
            .mul_div_floor(info.rate() as u64, *gst::ClockTime::SECOND)
            .unwrap();

        *self.state.borrow_mut() = Some(State {
            info,
            ebur128,
            num_frames: 0,
            interval_frames,
            interval_frames_remaining: interval_frames,
        });

        Ok(())
    }

    fn stop(&self) -> Result<(), gst::ErrorMessage> {
        // Drop state
        let _ = self.state.borrow_mut().take();

        gst::info!(CAT, imp: self, "Stopped");

        Ok(())
    }

    fn transform_ip_passthrough(
        &self,
        buf: &gst::Buffer,
    ) -> Result<gst::FlowSuccess, gst::FlowError> {
        let settings = *self.settings.lock().unwrap();

        let mut state_guard = self.state.borrow_mut();
        let mut state = state_guard.as_mut().ok_or_else(|| {
            gst::element_imp_error!(self, gst::CoreError::Negotiation, ["Have no state yet"]);
            gst::FlowError::NotNegotiated
        })?;

        let mut timestamp = buf.pts();
        let segment = self.instance().segment().downcast::<gst::ClockTime>().ok();

        let buf = gst_audio::AudioBufferRef::from_buffer_ref_readable(buf, &state.info).map_err(
            |_| {
                gst::element_imp_error!(self, gst::ResourceError::Read, ["Failed to map buffer"]);
                gst::FlowError::Error
            },
        )?;

        let mut frames = Frames::from_audio_buffer(self, &buf)?;
        while frames.num_frames() > 0 {
            if self
                .reset
                .compare_exchange(
                    true,
                    false,
                    atomic::Ordering::SeqCst,
                    atomic::Ordering::SeqCst,
                )
                .is_ok()
            {
                state.ebur128.reset();
                state.interval_frames_remaining = state.interval_frames;
                state.num_frames = 0;
            }

            let to_process = u64::min(
                state.interval_frames_remaining.nseconds(),
                frames.num_frames() as u64,
            );

            frames
                .process(to_process, &mut state.ebur128)
                .map_err(|err| {
                    gst::element_imp_error!(
                        self,
                        gst::ResourceError::Read,
                        ["Failed to process buffer: {}", err]
                    );
                    gst::FlowError::Error
                })?;

            state.interval_frames_remaining -= to_process.nseconds();
            state.num_frames += to_process;

            // The timestamp we report in messages is always the timestamp until which measurements
            // are included, not the starting timestamp.
            timestamp = timestamp.opt_add(
                to_process
                    .mul_div_floor(*gst::ClockTime::SECOND, state.info.rate() as u64)
                    .map(gst::ClockTime::from_nseconds)
                    .unwrap(),
            );

            // Post a message whenever an interval is full
            if state.interval_frames_remaining.is_zero() {
                state.interval_frames_remaining = state.interval_frames;

                if settings.post_messages {
                    let running_time = segment.as_ref().and_then(|s| s.to_running_time(timestamp));
                    let stream_time = segment.as_ref().and_then(|s| s.to_stream_time(timestamp));

                    let mut s = gst::Structure::builder("ebur128-level")
                        .field("timestamp", timestamp)
                        .field("running-time", running_time)
                        .field("stream-time", stream_time)
                        .build();

                    if state.ebur128.mode().contains(ebur128::Mode::M) {
                        match state.ebur128.loudness_momentary() {
                            Ok(loudness) => s.set("momentary-loudness", &loudness),
                            Err(err) => gst::error!(
                                CAT,
                                imp: self,
                                "Failed to get momentary loudness: {}",
                                err
                            ),
                        }
                    }

                    if state.ebur128.mode().contains(ebur128::Mode::S) {
                        match state.ebur128.loudness_shortterm() {
                            Ok(loudness) => s.set("shortterm-loudness", &loudness),
                            Err(err) => gst::error!(
                                CAT,
                                imp: self,
                                "Failed to get shortterm loudness: {}",
                                err
                            ),
                        }
                    }

                    if state.ebur128.mode().contains(ebur128::Mode::I) {
                        match state.ebur128.loudness_global() {
                            Ok(loudness) => s.set("global-loudness", &loudness),
                            Err(err) => gst::error!(
                                CAT,
                                imp: self,
                                "Failed to get global loudness: {}",
                                err
                            ),
                        }

                        match state.ebur128.relative_threshold() {
                            Ok(threshold) => s.set("relative-threshold", &threshold),
                            Err(err) => gst::error!(
                                CAT,
                                imp: self,
                                "Failed to get relative threshold: {}",
                                err
                            ),
                        }
                    }

                    if state.ebur128.mode().contains(ebur128::Mode::LRA) {
                        match state.ebur128.loudness_range() {
                            Ok(range) => s.set("loudness-range", &range),
                            Err(err) => {
                                gst::error!(CAT, imp: self, "Failed to get loudness range: {}", err)
                            }
                        }
                    }

                    if state.ebur128.mode().contains(ebur128::Mode::SAMPLE_PEAK) {
                        let peaks = (0..state.info.channels())
                            .map(|c| state.ebur128.sample_peak(c).map(|p| p.to_send_value()))
                            .collect::<Result<Vec<_>, _>>();

                        match peaks {
                            Ok(peaks) => s.set("sample-peak", gst::Array::from(peaks)),
                            Err(err) => {
                                gst::error!(CAT, imp: self, "Failed to get sample peaks: {}", err)
                            }
                        }
                    }

                    if state.ebur128.mode().contains(ebur128::Mode::TRUE_PEAK) {
                        let peaks = (0..state.info.channels())
                            .map(|c| state.ebur128.true_peak(c).map(|p| p.to_send_value()))
                            .collect::<Result<Vec<_>, _>>();

                        match peaks {
                            Ok(peaks) => s.set("true-peak", gst::Array::from(peaks)),
                            Err(err) => {
                                gst::error!(CAT, imp: self, "Failed to get true peaks: {}", err)
                            }
                        }
                    }

                    gst::debug!(CAT, imp: self, "Posting message {}", s);

                    let msg = gst::message::Element::builder(s)
                        .src(&*self.instance())
                        .build();

                    // Release lock while posting the message to avoid deadlocks
                    drop(state_guard);

                    let _ = self.instance().post_message(msg);

                    state_guard = self.state.borrow_mut();
                    state = state_guard.as_mut().ok_or_else(|| {
                        gst::element_imp_error!(
                            self,
                            gst::CoreError::Negotiation,
                            ["Have no state yet"]
                        );
                        gst::FlowError::NotNegotiated
                    })?;
                }
            }
        }

        Ok(gst::FlowSuccess::Ok)
    }
}

/// Helper struct to handle the different sample formats and layouts generically.
enum Frames<'a> {
    S16(&'a [i16], usize),
    S32(&'a [i32], usize),
    F32(&'a [f32], usize),
    F64(&'a [f64], usize),
    S16P(SmallVec<[&'a [i16]; 64]>),
    S32P(SmallVec<[&'a [i32]; 64]>),
    F32P(SmallVec<[&'a [f32]; 64]>),
    F64P(SmallVec<[&'a [f64]; 64]>),
}

impl<'a> Frames<'a> {
    /// Create a new frames wrapper that allows chunked processing.
    fn from_audio_buffer(
        imp: &EbuR128Level,
        buf: &'a gst_audio::AudioBufferRef<&'a gst::BufferRef>,
    ) -> Result<Self, gst::FlowError> {
        match (buf.format(), buf.layout()) {
            (gst_audio::AUDIO_FORMAT_S16, gst_audio::AudioLayout::Interleaved) => Ok(Frames::S16(
                interleaved_channel_data_into_slice(imp, buf)?,
                buf.channels() as usize,
            )),
            (gst_audio::AUDIO_FORMAT_S32, gst_audio::AudioLayout::Interleaved) => Ok(Frames::S32(
                interleaved_channel_data_into_slice(imp, buf)?,
                buf.channels() as usize,
            )),
            (gst_audio::AUDIO_FORMAT_F32, gst_audio::AudioLayout::Interleaved) => Ok(Frames::F32(
                interleaved_channel_data_into_slice(imp, buf)?,
                buf.channels() as usize,
            )),
            (gst_audio::AUDIO_FORMAT_F64, gst_audio::AudioLayout::Interleaved) => Ok(Frames::F64(
                interleaved_channel_data_into_slice(imp, buf)?,
                buf.channels() as usize,
            )),
            (gst_audio::AUDIO_FORMAT_S16, gst_audio::AudioLayout::NonInterleaved) => Ok(
                Frames::S16P(non_interleaved_channel_data_into_slices(imp, buf)?),
            ),
            (gst_audio::AUDIO_FORMAT_S32, gst_audio::AudioLayout::NonInterleaved) => Ok(
                Frames::S32P(non_interleaved_channel_data_into_slices(imp, buf)?),
            ),
            (gst_audio::AUDIO_FORMAT_F32, gst_audio::AudioLayout::NonInterleaved) => Ok(
                Frames::F32P(non_interleaved_channel_data_into_slices(imp, buf)?),
            ),
            (gst_audio::AUDIO_FORMAT_F64, gst_audio::AudioLayout::NonInterleaved) => Ok(
                Frames::F64P(non_interleaved_channel_data_into_slices(imp, buf)?),
            ),
            _ => Err(gst::FlowError::NotNegotiated),
        }
    }

    /// Get the number of remaining frames.
    fn num_frames(&self) -> usize {
        match self {
            Frames::S16(frames, channels) => frames.len() / channels,
            Frames::S32(frames, channels) => frames.len() / channels,
            Frames::F32(frames, channels) => frames.len() / channels,
            Frames::F64(frames, channels) => frames.len() / channels,
            Frames::S16P(frames) => frames[0].len(),
            Frames::S32P(frames) => frames[0].len(),
            Frames::F32P(frames) => frames[0].len(),
            Frames::F64P(frames) => frames[0].len(),
        }
    }

    /// Process `num_frames` with `ebur128` and advance to the next frames.
    fn process(
        &mut self,
        num_frames: u64,
        ebur128: &mut ebur128::EbuR128,
    ) -> Result<(), ebur128::Error> {
        match self {
            Frames::S16(frames, channels) => {
                let (first, second) = frames.split_at(num_frames as usize * *channels);
                ebur128.add_frames_i16(first)?;
                *frames = second;

                Ok(())
            }
            Frames::S32(frames, channels) => {
                let (first, second) = frames.split_at(num_frames as usize * *channels);
                ebur128.add_frames_i32(first)?;
                *frames = second;

                Ok(())
            }
            Frames::F32(frames, channels) => {
                let (first, second) = frames.split_at(num_frames as usize * *channels);
                ebur128.add_frames_f32(first)?;
                *frames = second;

                Ok(())
            }
            Frames::F64(frames, channels) => {
                let (first, second) = frames.split_at(num_frames as usize * *channels);
                ebur128.add_frames_f64(first)?;
                *frames = second;

                Ok(())
            }
            Frames::S16P(channels) => {
                let (first, second) = split_vec(channels, num_frames as usize);
                ebur128.add_frames_planar_i16(&first)?;
                *channels = second;

                Ok(())
            }
            Frames::S32P(channels) => {
                let (first, second) = split_vec(channels, num_frames as usize);
                ebur128.add_frames_planar_i32(&first)?;
                *channels = second;

                Ok(())
            }
            Frames::F32P(channels) => {
                let (first, second) = split_vec(channels, num_frames as usize);
                ebur128.add_frames_planar_f32(&first)?;
                *channels = second;

                Ok(())
            }
            Frames::F64P(channels) => {
                let (first, second) = split_vec(channels, num_frames as usize);
                ebur128.add_frames_planar_f64(&first)?;
                *channels = second;

                Ok(())
            }
        }
    }
}

/// Converts an interleaved audio buffer into a typed slice.
fn interleaved_channel_data_into_slice<'a, T: FromByteSlice>(
    imp: &EbuR128Level,
    buf: &'a gst_audio::AudioBufferRef<&gst::BufferRef>,
) -> Result<&'a [T], gst::FlowError> {
    buf.plane_data(0)
        .map_err(|err| {
            gst::error!(CAT, imp: imp, "Failed to get audio data: {}", err);
            gst::FlowError::Error
        })?
        .as_slice_of::<T>()
        .map_err(|err| {
            gst::error!(CAT, imp: imp, "Failed to handle audio data: {}", err);
            gst::FlowError::Error
        })
}

/// Converts a non-interleaved audio buffer into a vector of typed slices.
fn non_interleaved_channel_data_into_slices<'a, T: FromByteSlice>(
    imp: &EbuR128Level,
    buf: &'a gst_audio::AudioBufferRef<&gst::BufferRef>,
) -> Result<SmallVec<[&'a [T]; 64]>, gst::FlowError> {
    (0..buf.channels())
        .map(|c| {
            buf.plane_data(c)
                .map_err(|err| {
                    gst::error!(CAT, imp: imp, "Failed to get audio data: {}", err);
                    gst::FlowError::Error
                })?
                .as_slice_of::<T>()
                .map_err(|err| {
                    gst::error!(CAT, imp: imp, "Failed to handle audio data: {}", err);
                    gst::FlowError::Error
                })
        })
        .collect::<Result<_, _>>()
}

/// Split a vector of slices into a tuple of slices with each slice split at `split_at`.
#[allow(clippy::type_complexity)]
fn split_vec<'a, 'b, T: Copy>(
    vec: &'b SmallVec<[&'a [T]; 64]>,
    split_at: usize,
) -> (SmallVec<[&'a [T]; 64]>, SmallVec<[&'a [T]; 64]>) {
    let VecPair(first, second) = vec
        .iter()
        .map(|vec| vec.split_at(split_at))
        .collect::<VecPair<_>>();
    (first, second)
}

/// Helper struct to collect from an iterator on pairs into two vectors.
struct VecPair<T>(SmallVec<[T; 64]>, SmallVec<[T; 64]>);

impl<T> std::iter::FromIterator<(T, T)> for VecPair<T> {
    fn from_iter<I: IntoIterator<Item = (T, T)>>(iter: I) -> Self {
        let mut first_vec = SmallVec::new();
        let mut second_vec = SmallVec::new();
        for (first, second) in iter {
            first_vec.push(first);
            second_vec.push(second);
        }

        VecPair(first_vec, second_vec)
    }
}