phonic 0.16.0

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

use pulp::Simd;

// -------------------------------------------------------------------------------------------------

/// Copy the given planar buffer into an interleaved one.
/// The planar buffer's layout defines layout of the interleaved buffer (channel and frame count).
/// The interleaved buffer must be large enough to fit the planar buffer.
pub fn planar_to_interleaved(planar: &[Vec<f32>], mut interleaved: &mut [f32]) {
    let channel_count = planar.len();
    let frame_count = planar[0].len();
    debug_assert!(
        interleaved.len() >= frame_count * channel_count,
        "Buffer size mismatch"
    );
    match channel_count {
        1 => {
            copy_buffers(&mut interleaved[..frame_count], &planar[0]);
        }
        2 => {
            let left = &planar[0];
            let right = &planar[1];
            let frames = interleaved.as_frames_mut::<2>();
            for (frame, (l, r)) in frames.iter_mut().zip(left.iter().zip(right.iter())) {
                frame[0] = *l;
                frame[1] = *r;
            }
        }
        _ => {
            for (channel_index, channel) in planar.iter().enumerate() {
                for (p, i) in channel
                    .iter()
                    .zip(interleaved.chunks_exact_mut(channel_count))
                {
                    i[channel_index] = *p;
                }
            }
        }
    }
}

// -------------------------------------------------------------------------------------------------

/// Copy the given interleaved buffer into a planar one.
/// The planar buffer's layout defines layout of the interleaved buffer (channel and frame count).
/// The interleaved buffer must be large enough to fill the planar buffer.
pub fn interleaved_to_planar(interleaved: &[f32], planar: &mut [Vec<f32>]) {
    let channel_count = planar.len();
    let frame_count = planar[0].len();
    debug_assert!(
        interleaved.len() >= frame_count * channel_count,
        "Buffer size mismatch"
    );
    match channel_count {
        1 => {
            copy_buffers(&mut planar[0], &interleaved[..frame_count]);
        }
        2 => {
            let frames = interleaved.as_frames::<2>();
            let left = &mut planar[0];
            for (l, frame) in left.iter_mut().zip(frames) {
                *l = frame[0];
            }
            let right = &mut planar[1];
            for (r, frame) in right.iter_mut().zip(frames) {
                *r = frame[1];
            }
        }
        _ => {
            for (channel_index, channel) in planar.iter_mut().enumerate() {
                for (p, i) in channel
                    .iter_mut()
                    .zip(interleaved.chunks_exact(channel_count))
                {
                    *p = i[channel_index];
                }
            }
        }
    }
}

// -------------------------------------------------------------------------------------------------

#[pulp::with_simd(clear_buffer = pulp::Arch::new())]
#[inline(always)]
/// Dest = 0.0
pub fn clear_buffer_with_simd<S: Simd>(simd: S, dest: &mut [f32]) {
    let (head, tail) = S::as_mut_simd_f32s(dest);
    let zero = simd.splat_f32s(0.0);
    for x in head.iter_mut() {
        *x = zero;
    }
    for x in tail.iter_mut() {
        *x = 0.0;
    }
}

#[pulp::with_simd(scale_buffer = pulp::Arch::new())]
#[inline(always)]
/// Dest *= Value
pub fn scale_buffer_with_simd<S: Simd>(simd: S, dest: &mut [f32], value: f32) {
    let (head, tail) = S::as_mut_simd_f32s(dest);
    let valuef32 = simd.splat_f32s(value);
    for x in head.iter_mut() {
        *x = simd.mul_f32s(*x, valuef32);
    }
    for x in tail.iter_mut() {
        *x *= value;
    }
}

#[pulp::with_simd(add_buffers = pulp::Arch::new())]
#[inline(always)]
/// Dest += Source
pub fn add_buffers_with_simd<'a, S: Simd>(simd: S, dest: &'a mut [f32], source: &'a [f32]) {
    assert!(
        dest.len() == source.len(),
        "added buffers should have the same size"
    );
    let (head1, tail1) = S::as_mut_simd_f32s(dest);
    let (head2, tail2) = S::as_simd_f32s(source);
    for (x1, x2) in head1.iter_mut().zip(head2) {
        *x1 = simd.add_f32s(*x1, *x2);
    }
    for (x1, x2) in tail1.iter_mut().zip(tail2) {
        *x1 += *x2;
    }
}

#[pulp::with_simd(copy_buffers = pulp::Arch::new())]
#[inline(always)]
/// Dest = Source
pub fn copy_buffers_with_simd<'a, S: Simd>(_simd: S, dest: &'a mut [f32], source: &'a [f32]) {
    assert!(
        dest.len() == source.len(),
        "copied buffers should have the same size"
    );
    let (head1, tail1) = S::as_mut_simd_f32s(dest);
    let (head2, tail2) = S::as_simd_f32s(source);
    for (x1, x2) in head1.iter_mut().zip(head2) {
        *x1 = *x2;
    }
    for (x1, x2) in tail1.iter_mut().zip(tail2) {
        *x1 = *x2;
    }
}

#[pulp::with_simd(max_abs_sample = pulp::Arch::new())]
#[inline(always)]
/// Find the maximum absolute value in a buffer using SIMD
pub fn max_abs_sample_with_simd<S: Simd>(simd: S, buffer: &[f32]) -> f32 {
    let (head, tail) = S::as_simd_f32s(buffer);

    // Process SIMD lanes
    let mut max_vec = simd.splat_f32s(0.0);
    for &x in head {
        let abs_x = simd.abs_f32s(x);
        max_vec = simd.max_f32s(max_vec, abs_x);
    }

    // Reduce SIMD vector to scalar
    let lanes = simd.reduce_max_f32s(max_vec);

    // Process remaining scalar elements
    let mut max_scalar = lanes;
    for &x in tail {
        max_scalar = max_scalar.max(x.abs());
    }

    max_scalar
}

// -------------------------------------------------------------------------------------------------

/// Remaps interleaved audio between channel layouts.
///
/// Mono sources are expanded to stereo; stereo+ sources are mixed down
/// to mono when needed. Extra output channels are zeroed.
///
/// Note: Frame counts of input and output buffers must be equal!
pub fn remap_buffer_channels(
    input: &[f32],
    input_channels: usize,
    mut output: &mut [f32],
    output_channels: usize,
) {
    assert!(input_channels > 0, "Input channel count must be > 0");
    assert!(output_channels > 0, "Output channel count must be > 0");

    debug_assert!(
        input.len().is_multiple_of(input_channels),
        "Input buffer length ({}) must be divisible by input channels ({input_channels})",
        input.len(),
    );
    debug_assert!(
        output.len().is_multiple_of(output_channels),
        "Output buffer length ({}) must be divisible by output channels ({output_channels})",
        output.len(),
    );
    debug_assert!(
        input.len() / input_channels == output.len() / output_channels,
        "Frame count mismatch: input has {} frames, output has {} frames",
        input.len() / input_channels,
        output.len() / output_channels,
    );

    match (input_channels, output_channels) {
        // mono to stereo: expand
        (1, 2) => {
            let input_frames = input.as_frames::<1>();
            let output_frames = output.as_frames_mut::<2>();
            for (i, o) in input_frames.iter().zip(output_frames) {
                o[0] = i[0];
                o[1] = i[0];
            }
        }
        // stereo to mono: mix down
        (2, 1) => {
            let input_frames = input.as_frames::<2>();
            let output_frames = output.as_frames_mut::<1>();
            for (i, o) in input_frames.iter().zip(output_frames) {
                o[0] = (i[0] + i[1]) / 2.0;
            }
        }
        // no remapping needed: just copy
        (input_channels, output_channels) if input_channels == output_channels => {
            copy_buffers(output, input);
        }
        // everything else
        (input_channels, output_channels) => {
            match input_channels {
                1 => {
                    // expand mono to first two channels, zero remaining channels
                    let input_frames = input.as_frames::<1>();
                    let output_frames = output.chunks_exact_mut(output_channels);
                    for (i, o) in input_frames.iter().zip(output_frames) {
                        o[0] = i[0];
                        o[1] = i[0];
                        o[2..].fill(0.0);
                    }
                }
                _ => {
                    let input_frames = input.chunks_exact(input_channels);
                    match output_channels {
                        1 => {
                            // mix down the first two channels, ignore other input channels
                            let output_frames = output.as_frames_mut::<1>();
                            for (i, o) in input_frames.zip(output_frames) {
                                o[0] = (i[0] + i[1]) / 2.0;
                            }
                        }
                        _ => {
                            // copy first two channels, zero remaining output channels
                            let output_frames = output.chunks_exact_mut(output_channels);
                            for (i, o) in input_frames.zip(output_frames) {
                                o[0] = i[0];
                                o[1] = i[1];
                                o[2..].fill(0.0);
                            }
                        }
                    }
                }
            }
        }
    }
}

// -------------------------------------------------------------------------------------------------

/// Provides safe and efficient methods to access interleaved audio data, such as iterating over
/// frames or individual channels, without needing to perform manual index calculations.
/// It is implemented for common buffer types like `&[f32]` and `Vec<f32>`.
///
/// # Examples
///
/// ```
/// use phonic::utils::buffer::InterleavedBuffer;
///
/// let buffer: &[f32] = &[
///     0.1, 0.2, // Frame 0
///     0.3, 0.4, // Frame 1
/// ];
///
/// // View as frames
/// let frames = buffer.as_frames::<2>();
/// assert_eq!(frames, &[[0.1, 0.2], [0.3, 0.4]]);
///
/// // Iterate over channels
/// let mut channels = buffer.channels(2);
/// let left: Vec<_> = channels.next().unwrap().copied().collect();
/// let right: Vec<_> = channels.next().unwrap().copied().collect();
/// assert_eq!(left, &[0.1, 0.3]);
/// assert_eq!(right, &[0.2, 0.4]);
/// ```
pub trait InterleavedBuffer<'a> {
    /// Raw access to the buffer slice.
    fn buffer(&self) -> &'a [f32];

    /// Iterate by channels. This returns one iterator per channel, each yielding the samples
    /// of that channel across all frames.
    ///
    /// Note: Prefer using `frames` or `as_frames` for hot paths as it's more efficient.
    fn channels(
        &self,
        channel_count: usize,
    ) -> impl Iterator<Item = impl Iterator<Item = &'a f32> + 'a> + 'a {
        let buffer = self.buffer();
        let buffer_len = buffer.len();
        assert!(
            buffer_len.is_multiple_of(channel_count),
            "channels: buffer length ({buffer_len}) must be divisible by channel count ({channel_count})",
        );
        (0..channel_count).map(move |i| buffer.iter().skip(i).step_by(channel_count))
    }

    /// Iterate over frames. Each frame yields `channel_count` samples.
    ///
    /// Note: Prefer using `as_frames` for hot paths. They avoid iterator overhead and yield
    /// fixed-size arrays per frame for better compiler optimization and cache locality.
    fn frames(
        &self,
        channel_count: usize,
    ) -> impl Iterator<Item = impl Iterator<Item = &'a f32> + 'a> + 'a {
        let buffer = self.buffer();
        let buffer_len = buffer.len();
        assert!(
            buffer_len.is_multiple_of(channel_count),
            "frames: buffer length ({buffer_len}) must be divisible by channel count ({channel_count})",
        );
        self.buffer()
            .chunks_exact(channel_count)
            .map(move |channel_chunk| channel_chunk.iter().take(channel_count))
    }

    /// View the interleaved samples as contiguous frames of size `CHANNEL_COUNT`.
    ///
    /// Constraints:
    /// - The buffer length must be divisible by `CHANNEL_COUNT` (i.e. no remainder).
    ///
    /// Typical usage is `CHANNEL_COUNT == self.channel_count()`, in which case each array is one frame.
    fn as_frames<const CHANNEL_COUNT: usize>(&self) -> &'a [[f32; CHANNEL_COUNT]] {
        let buffer = self.buffer();
        let buffer_len = buffer.len();
        assert!(
            buffer_len.is_multiple_of(CHANNEL_COUNT),
            "as_frames: buffer length ({buffer_len}) must be divisible by N ({CHANNEL_COUNT})",
        );
        let frames_count = self.buffer().len() / CHANNEL_COUNT;
        let ptr = buffer.as_ptr() as *const [f32; CHANNEL_COUNT];
        unsafe { std::slice::from_raw_parts(ptr, frames_count) }
    }
}

// -------------------------------------------------------------------------------------------------

/// Extends [`InterleavedBuffer`] with methods for modifying the buffer's contents.
/// It provides safe and efficient ways to get mutable access to frames or individual channels.
///
/// Like [`InterleavedBuffer`], it is implemented for common buffer types that allow mutation,
/// such as `&mut [f32]` and `Vec<f32>`.
///
/// # Examples
///
/// ```
/// use phonic::utils::buffer::{InterleavedBuffer, InterleavedBufferMut};
///
/// let mut buffer: Vec<f32> = vec![
///     0.1, 0.2, // Frame 0
///     0.3, 0.4, // Frame 1
/// ];
///
/// // Get mutable access to sample frames and modify them
/// for frame in buffer.as_frames_mut::<2>() {
///     frame[0] *= 2.0; // Double the left channel
///     frame[1] *= 0.5; // Halve the right channel
/// }
/// assert_eq!(buffer, vec![
///     0.2, 0.1, // Frame 0
///     0.6, 0.2  // Frame 1
/// ]);
/// ```
pub trait InterleavedBufferMut<'a>: InterleavedBuffer<'a> {
    /// Raw mut access to the buffer slice.
    fn buffer_mut(&mut self) -> &'a mut [f32];

    /// Mutable channel-wise iteration.
    ///
    /// Returns an iterator over channels, each yielding mutable samples across all frames.
    /// This uses internal pointer arithmetic to safely create non-overlapping mutable references
    /// into the interleaved buffer.
    ///
    /// Note: Prefer using `frames_mut` or `as_frames_mut` for hot paths as it's more efficient.
    fn channels_mut(
        &mut self,
        channel_count: usize,
    ) -> impl Iterator<Item = impl Iterator<Item = &'a mut f32> + 'a> + 'a {
        let buffer = self.buffer_mut();
        let buffer_len = buffer.len();
        assert!(
            buffer_len.is_multiple_of(channel_count),
            "channels_mut: buffer length ({buffer_len}) must be divisible by channel count ({channel_count})",
        );
        let frame_count = buffer_len / channel_count;
        let ptr = buffer.as_mut_ptr();
        (0..channel_count).map(move |ch_idx| {
            (0..frame_count).map(move |fr_idx| {
                // SAFETY: The outer iterator produces one iterator for each channel.
                // Each inner iterator accesses samples of one channel, which do not overlap with
                // samples of other channels. The borrow checker cannot prove this, so we use
                // unsafe. The lifetime 'a ensures that the returned iterators do not outlive
                // the buffer.
                unsafe { &mut *ptr.add(ch_idx + fr_idx * channel_count) }
            })
        })
    }

    /// Iterate over frames mutably. Each frame yields `channel_count` mutable samples.
    ///
    /// Note: Prefer using `as_frames_mut` for hot paths. They avoid iterator overhead and yield
    /// fixed-size arrays per frame for better compiler optimization and cache locality.
    fn frames_mut(
        &mut self,
        channel_count: usize,
    ) -> impl Iterator<Item = impl Iterator<Item = &'a mut f32> + 'a> + 'a {
        let buffer = self.buffer_mut();
        let buffer_len = buffer.len();
        assert!(
            buffer_len.is_multiple_of(channel_count),
            "frames_mut: buffer length ({buffer_len}) must be divisible by channel count ({channel_count})",
        );
        buffer
            .chunks_exact_mut(channel_count)
            .map(move |channel_chunk| channel_chunk.iter_mut().take(channel_count))
    }

    /// Mutable view of the interleaved samples as contiguous frames of size `CHANNEL_COUNT`.
    ///
    /// Constraints:
    /// - The buffer length must be divisible by `CHANNEL_COUNT` (i.e. no remainder).
    ///
    /// Typical usage is `CHANNEL_COUNT == self.channel_count()`, in which case each array is one frame.
    fn as_frames_mut<const CHANNEL_COUNT: usize>(&mut self) -> &'a mut [[f32; CHANNEL_COUNT]] {
        let buffer = self.buffer_mut();
        let buffer_len = buffer.len();
        assert!(
            buffer_len.is_multiple_of(CHANNEL_COUNT),
            "as_frames_mut: buffer length ({buffer_len}) must be divisible by N ({CHANNEL_COUNT})",
        );
        let frames_count = self.buffer().len() / CHANNEL_COUNT;
        let ptr = buffer.as_mut_ptr() as *mut [f32; CHANNEL_COUNT];
        unsafe { std::slice::from_raw_parts_mut(ptr, frames_count) }
    }
}

// -------------------------------------------------------------------------------------------------

impl<'a> InterleavedBuffer<'a> for &'a [f32] {
    fn buffer(&self) -> &'a [f32] {
        self
    }
}

impl<'a> InterleavedBuffer<'a> for &'a mut [f32] {
    fn buffer(&self) -> &'a [f32] {
        // SAFETY: The lifetime 'a is tied to the underlying slice, which is valid.
        // The compiler incorrectly restricts the lifetime to that of `&self`.
        unsafe { &*(*self as *const [f32]) }
    }
}

impl<'a> InterleavedBufferMut<'a> for &'a mut [f32] {
    fn buffer_mut(&mut self) -> &'a mut [f32] {
        // SAFETY: The lifetime 'a is tied to the underlying slice, which is valid.
        // The compiler incorrectly restricts the lifetime to that of `&mut self`.
        unsafe { &mut *(*self as *mut [f32]) }
    }
}

impl<'a> InterleavedBuffer<'a> for Vec<f32> {
    fn buffer(&self) -> &'a [f32] {
        unsafe { &*(self.as_slice() as *const [f32]) }
    }
}

impl<'a> InterleavedBufferMut<'a> for Vec<f32> {
    fn buffer_mut(&mut self) -> &'a mut [f32] {
        // SAFETY: The lifetime 'a is tied to the underlying slice, which is valid.
        // The compiler incorrectly restricts the lifetime to that of `&mut self`.
        unsafe { &mut *(self.as_mut_slice() as *mut [f32]) }
    }
}

// -------------------------------------------------------------------------------------------------

/// A preallocated buffer slice with persistent start/end positions and helper functions.
#[derive(Clone, Debug)]
pub struct TempBuffer {
    buffer: Box<[f32]>,
    start: usize,
    end: usize,
}

impl TempBuffer {
    /// Create a new empty buffer with the given capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            buffer: vec![0.0; capacity].into_boxed_slice(),
            start: 0,
            end: 0,
        }
    }

    /// Returns `true` if the buffer is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.start >= self.end
    }

    /// Returns the currently used length.
    #[inline]
    pub fn len(&self) -> usize {
        self.end - self.start
    }

    /// Returns the total available capacity.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.buffer.len()
    }

    /// Returns read-only access to the currently filled region.
    #[inline]
    pub fn get(&self) -> &'_ [f32] {
        &self.buffer[self.start..self.end]
    }

    /// Returns mutable access to the currently filled region.
    #[inline]
    pub fn get_mut(&mut self) -> &'_ mut [f32] {
        &mut self.buffer[self.start..self.end]
    }

    /// Sets the valid filled range. Call this before writing via `get_mut()`.
    pub fn set_range(&mut self, start: usize, end: usize) {
        assert!(
            start <= end,
            "Invalid temp buffer range: start {}, end {}",
            start,
            end
        );
        assert!(
            end <= self.capacity(),
            "Invalid temp buffer range: got a capacity of {}, requested {}",
            self.buffer.len(),
            end
        );
        self.start = start;
        self.end = end;
    }
    /// Resets the range to cover the entire available capacity.
    #[inline]
    pub fn reset_range(&mut self) {
        self.start = 0;
        self.end = self.buffer.len();
    }

    /// Clears the range to mark the buffer as empty.
    #[inline]
    pub fn clear_range(&mut self) {
        self.start = 0;
        self.end = 0;
    }

    /// Copies data to `other`, up to `min(self.len(), other.len())` samples.
    /// Returns the number of samples copied.
    pub fn copy_to(&self, other: &mut [f32]) -> usize {
        let copy_len = other.len().min(self.len());

        let other_slice = &mut other[..copy_len];
        let this_slice = &self.get()[..copy_len];
        copy_buffers(other_slice, this_slice);

        copy_len
    }

    /// Copies data from `other`, up to `min(self.len(), other.len())` samples.
    /// Returns the number of samples copied.
    pub fn copy_from(&mut self, other: &[f32]) -> usize {
        let copy_len = other.len().min(self.len());

        let this_slice = &mut self.get_mut()[..copy_len];
        let other_slice = &other[..copy_len];
        copy_buffers(this_slice, other_slice);

        copy_len
    }

    /// Advances the start position by `samples`, consuming that data.
    pub fn consume(&mut self, samples: usize) {
        assert!(
            self.start + samples <= self.end,
            "Invalid temp buffer consume: current length is {}, requested {}",
            self.len(),
            samples
        );
        self.start += samples;
    }
}

// -------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;

    #[test]
    fn planar_interleaved() {
        // mono
        let planar_mono = vec![vec![1.0, 2.0, 3.0, 4.0]];
        let interleaved_mono = vec![1.0, 2.0, 3.0, 4.0];
        let mut planar_mono_copy = planar_mono.clone();
        let mut interleaved_mono_copy = interleaved_mono.clone();

        planar_to_interleaved(&planar_mono, &mut interleaved_mono_copy);
        interleaved_to_planar(&interleaved_mono, &mut planar_mono_copy);
        assert_eq!(planar_mono, planar_mono_copy);
        assert_eq!(interleaved_mono, interleaved_mono_copy);

        // stereo
        let planar_stereo = vec![vec![1.0, 2.0, 3.0, 4.0], vec![4.0, 3.0, 2.0, 1.0]];
        let interleaved_stereo = vec![1.0, 4.0, 2.0, 3.0, 3.0, 2.0, 4.0, 1.0];
        let mut planar_stereo_copy = planar_stereo.clone();
        let mut interleaved_stereo_copy = interleaved_stereo.clone();

        planar_to_interleaved(&planar_stereo, &mut interleaved_stereo_copy);
        interleaved_to_planar(&interleaved_stereo, &mut planar_stereo_copy);
        assert_eq!(planar_stereo, planar_stereo_copy);
        assert_eq!(interleaved_stereo, interleaved_stereo_copy);

        // general
        let planar_general = vec![
            vec![1.0, 2.0, 3.0, 4.0],
            vec![4.0, 3.0, 2.0, 1.0],
            vec![2.0, 1.0, 4.0, 3.0],
        ];
        let interleaved_general = vec![1.0, 4.0, 2.0, 2.0, 3.0, 1.0, 3.0, 2.0, 4.0, 4.0, 1.0, 3.0];
        let mut planar_general_copy = planar_general.clone();
        let mut interleaved_general_copy = interleaved_general.clone();
        planar_to_interleaved(&planar_general, &mut interleaved_general_copy);
        interleaved_to_planar(&interleaved_general, &mut planar_general_copy);
        assert_eq!(planar_general, planar_general_copy);
        assert_eq!(interleaved_general, interleaved_general_copy);
    }

    #[test]
    fn clear_buffer_simd() {
        let mut buffer = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0];
        clear_buffer(&mut buffer);
        assert_eq!(
            buffer,
            vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        );
    }

    #[test]
    fn scale_buffer_simd() {
        let mut buffer = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0];
        scale_buffer(&mut buffer, 2.0);
        assert_eq!(
            buffer,
            vec![2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0]
        );

        scale_buffer(&mut buffer, 0.5);
        assert_eq!(
            buffer,
            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]
        );
    }

    #[test]
    fn add_buffers_simd() {
        let mut dest = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0];
        let source = vec![0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5];
        add_buffers(&mut dest, &source);
        assert_eq!(
            dest,
            vec![1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5, 15.0, 16.5]
        );
    }

    #[test]
    fn copy_buffers_simd() {
        let mut dest = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
        let source = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0];
        copy_buffers(&mut dest, &source);
        assert_eq!(
            dest,
            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]
        );
    }

    #[test]
    fn max_abs_sample_simd() {
        let buffer = vec![
            0.1, -0.5, 0.3, -0.2, 0.15, -0.25, 0.35, -0.45, 0.05, -0.15, 0.25,
        ];
        let max = max_abs_sample(&buffer);
        assert_eq!(max, 0.5);

        let buffer: Vec<f32> = vec![];
        let max = max_abs_sample(&buffer);
        assert_eq!(max, 0.0);
    }

    #[test]
    fn buffer_channels_iter() {
        let mut data = vec![
            0.0_f32, 1.0, // frame 0: L, R
            10.0, 11.0, // frame 1: L, R
            20.0, 21.0, // frame 2: L, R
        ];
        let channels: Vec<Vec<f32>> = data.channels(2).map(|ch| ch.copied().collect()).collect();
        assert_eq!(channels, vec![vec![0.0, 10.0, 20.0], vec![1.0, 11.0, 21.0]]);

        for (i, ch) in data.channels_mut(2).enumerate() {
            if i == 0 {
                // left channel * 2
                for s in ch {
                    *s *= 2.0;
                }
            } else {
                // right channel * 3
                for s in ch {
                    *s *= 3.0;
                }
            }
        }
        assert_eq!(&data, &[0.0_f32, 3.0, 20.0, 33.0, 40.0, 63.0]);
    }

    #[test]
    fn buffer_frames_iter() {
        let mut data = vec![
            0.0_f32, 1.0, // frame 0
            10.0, 11.0, // frame 1
            20.0, 21.0, // frame 2
        ];

        let frames: Vec<Vec<f32>> = data.frames(2).map(|f| f.copied().collect()).collect();
        assert_eq!(
            frames,
            vec![vec![0.0, 1.0], vec![10.0, 11.0], vec![20.0, 21.0]]
        );

        for frame in data.as_mut_slice().frames_mut(2) {
            for s in frame {
                *s += 0.5;
            }
        }
        assert_eq!(&data, &[0.5_f32, 1.5, 10.5, 11.5, 20.5, 21.5]);
    }

    #[test]
    fn buffer_as_frames() {
        let mut data = vec![
            0.0_f32, 1.0, // frame 0: L, R
            10.0, 11.0, // frame 1: L, R
            20.0, 21.0, // frame 2: L, R
        ];
        let frames = data.as_frames::<2>();
        assert_eq!(frames, &[[0.0_f32, 1.0], [10.0, 11.0], [20.0, 21.0]][..]);

        let frames = data.as_frames_mut::<2>();
        for frame in frames.iter_mut() {
            frame[0] += 0.25;
            frame[1] += 0.75;
        }
        assert_eq!(&data, &[0.25_f32, 1.75, 10.25, 11.75, 20.25, 21.75]);
    }

    #[test]
    #[should_panic]
    fn buffer_as_frames_constraints() {
        let data = vec![
            0.0_f32, 1.0, // frame 0: L, R
            10.0, 11.0, // frame 1: L, R
            20.0, 21.0, // frame 2: L, R
        ];
        // 5 channels does not fit into 3*2 samples
        let _frames = data.as_frames::<5>();
    }
}