maudio 0.1.5

Rust bindings to the miniaudio 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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Audio file encoding.
use std::{marker::PhantomData, mem::MaybeUninit, path::Path, sync::Arc};

use maudio_sys::ffi as sys;

use crate::{
    audio::{formats::Format, sample_rate::SampleRate},
    data_source::sources::decoder::{Cb, Fs},
    device::device_builder::Unknown,
    engine::AllocationCallbacks,
    pcm_frames::{PcmFormat, S24Packed},
    AsRawRef, Binding, ErrorKinds, MaResult, MaudioError,
};

/// Writes PCM audio frames into an encoded output destination.
///
/// An `Encoder` accepts interleaved PCM frames in the format specified by `F`,
/// encodes them as `E`, and writes the resulting bytes to the destination type `D`.
///
/// # Format support
///
/// Currently, miniaudio's streaming encoder only supports **WAV** output.
///
/// # What an encoder does
///
/// An encoder sits between raw PCM audio and some encoded output destination:
///
/// - you provide PCM frames with [`Encoder::write_pcm_frames`]
/// - the encoder converts them into the selected encoded format
/// - the encoded bytes are written to the file or writer chosen during construction
///
/// # Input and output
///
/// The encoder's **destination** is chosen once at build time:
///
/// - [`EncoderBuilder::build_file`] creates an encoder that writes to a file path
/// - [`EncoderBuilder::build_writer`] creates an encoder that writes through custom callbacks
///
/// After construction, audio data can be supplied manually through
/// [`Encoder::write_pcm_frames`].
///
/// # PCM requirements
///
/// The written PCM data must already match the encoder's configured:
///
/// - sample format
/// - channel count
/// - sample rate
///
/// No automatic conversion is performed by the encoder.
/// If these are not supported by the output file type an error will be returned.
///
/// # Examples
///
/// Writing to a file:
///
/// ```no_run
/// # use std::path::PathBuf;
/// # use maudio::encoder::EncoderBuilder;
/// # use maudio::{MaResult, audio::sample_rate::SampleRate};
/// # fn main() -> MaResult<()> {
/// let path = PathBuf::from("out.flac");
///
/// let mut encoder = EncoderBuilder::new_f32(2, SampleRate::Sr44100)
///     .wav()
///     .build_file(&path)?;
///
/// let pcm = vec![0.0f32; 512 * 2];
/// encoder.write_pcm_frames(&pcm)?;
/// # Ok(())
/// # }
/// ```
///
/// Writing to a custom writer:
///
/// ```no_run
/// # use std::fs::File;
/// # use maudio::encoder::EncoderBuilder;
/// # use maudio::{MaResult, audio::sample_rate::SampleRate};
/// # fn main() -> MaResult<()> {
/// let file = File::create("out.wav").unwrap();
///
/// let mut encoder = EncoderBuilder::new_i16(2, SampleRate::Sr44100)
///     .wav()
///     .build_writer(file)?;
///
/// let pcm = vec![0i16; 256 * 2];
/// encoder.write_pcm_frames(&pcm)?;
/// # Ok(())
/// # }
/// ```
pub struct Encoder<F: PcmFormat, E: CodecFormat, D> {
    inner: *mut sys::ma_encoder,
    channels: u32,
    sample_rate: SampleRate,
    format: Format,
    #[allow(clippy::type_complexity)]
    user_data: Option<EncoderUserDataDestructor>,
    _format: PhantomData<F>,
    _encoding: PhantomData<E>,
    _destination: PhantomData<D>,
}

type EncoderUserDataDestructor = (*mut core::ffi::c_void, fn(*mut core::ffi::c_void));

impl<F: PcmFormat, E: CodecFormat, D> Binding for Encoder<F, E, D> {
    type Raw = *mut sys::ma_encoder;

    /// !!! unimplemented !!!
    fn from_ptr(_raw: Self::Raw) -> Self {
        unimplemented!()
    }

    fn to_raw(&self) -> Self::Raw {
        self.inner
    }
}

impl<F: PcmFormat, E: CodecFormat, D> Encoder<F, E, D> {
    // TODO: Test if this works with F::PcmUnit (i32)
    pub fn write_pcm_frames(&mut self, source: &[F::StorageUnit]) -> MaResult<u64> {
        encoder_ffi::ma_encoder_write_pcm_frames(self, source)
    }
}

// Private methods
impl<F: PcmFormat, E: CodecFormat, D> Encoder<F, E, D> {
    fn new(
        inner: *mut sys::ma_encoder,
        channels: u32,
        sample_rate: SampleRate,
        format: Format,
    ) -> Self {
        Self {
            inner,
            channels,
            sample_rate,
            format,
            user_data: None,
            _format: PhantomData,
            _encoding: PhantomData,
            _destination: PhantomData,
        }
    }

    fn init_from_file(config: &EncoderBuilder<F, E>, path: &Path) -> MaResult<Encoder<F, E, Fs>> {
        let mut mem: Box<std::mem::MaybeUninit<sys::ma_encoder>> = Box::new(MaybeUninit::uninit());

        Encoder::<F, E, D>::init_from_file_internal(path, config, mem.as_mut_ptr())?;

        let inner: *mut sys::ma_encoder = Box::into_raw(mem) as *mut sys::ma_encoder;
        Ok(Encoder::new(
            inner,
            config.channels,
            config.sample_rate,
            config.format,
        ))
    }

    fn init_from_writer<W: WriteSeek>(
        config: &EncoderBuilder<F, E>,
        writer: W,
    ) -> MaResult<Encoder<F, E, Cb>> {
        let mut mem: Box<std::mem::MaybeUninit<sys::ma_encoder>> = Box::new(MaybeUninit::uninit());

        let user_data = Box::new(EncoderUserData { writer });
        let user_data_ptr = Box::into_raw(user_data) as *mut core::ffi::c_void;
        encoder_ffi::ma_encoder_init(
            Some(encoder_write_proc::<W>),
            Some(encoder_seek_proc::<W>),
            user_data_ptr,
            config,
            mem.as_mut_ptr(),
        )?;

        let inner: *mut sys::ma_encoder = Box::into_raw(mem) as *mut sys::ma_encoder;
        let mut encoder = Encoder::new(inner, config.channels, config.sample_rate, config.format);
        encoder.user_data = Some((user_data_ptr, encoder_user_data_drop::<W>));
        Ok(encoder)
    }

    fn init_from_file_internal(
        path: &Path,
        config: &EncoderBuilder<F, E>,
        encoder: *mut sys::ma_encoder,
    ) -> MaResult<()> {
        #[cfg(unix)]
        {
            use crate::engine::cstring_from_path;

            let path = cstring_from_path(path)?;
            encoder_ffi::ma_encoder_init_file(path, config, encoder)?;
            Ok(())
        }

        #[cfg(windows)]
        {
            use crate::engine::wide_null_terminated;

            let path = wide_null_terminated(path);

            encoder_ffi::ma_encoder_init_file_w(&path, config, encoder)?;
            Ok(())
        }

        #[cfg(not(any(unix, windows)))]
        compile_error!("init decoder from file is only supported on unix and windows");
    }
}

/// Trait alias for types that implement both [`std::io::Write`] and [`std::io::Seek`].
///
/// This is used by [`EncoderBuilder::build_writer`] to accept custom output
/// destinations for encoded audio data.
pub trait WriteSeek: std::io::Write + std::io::Seek {}
impl<T: std::io::Write + std::io::Seek> WriteSeek for T {}

struct EncoderUserData<W> {
    writer: W,
}

unsafe extern "C" fn encoder_write_proc<W: WriteSeek>(
    encoder: *mut sys::ma_encoder,
    buffer_in: *const core::ffi::c_void,
    bytes_to_write: usize,
    bytes_written: *mut usize,
) -> sys::ma_result {
    if encoder.is_null() || buffer_in.is_null() || bytes_written.is_null() {
        return sys::ma_result_MA_INVALID_ARGS;
    }

    // Make sure we don't leave this uninitialized
    *bytes_written = 0;

    let user_data = &mut *((&*encoder).pUserData as *mut EncoderUserData<W>);

    let slice = core::slice::from_raw_parts(buffer_in as _, bytes_to_write);

    match user_data.writer.write_all(slice) {
        Ok(()) => {
            *bytes_written = bytes_to_write;
            sys::ma_result_MA_SUCCESS
        }
        Err(_) => sys::ma_result_MA_ERROR,
    }
}

unsafe extern "C" fn encoder_seek_proc<W: WriteSeek>(
    encoder: *mut sys::ma_encoder,
    byte_offset: i64,
    origin: sys::ma_seek_origin,
) -> sys::ma_result {
    if encoder.is_null() {
        return sys::ma_result_MA_INVALID_ARGS;
    }

    let user_data = &mut *((&*encoder).pUserData as *mut EncoderUserData<W>);

    let pos = match origin {
        sys::ma_seek_origin_ma_seek_origin_start => {
            if byte_offset < 0 {
                return sys::ma_result_MA_INVALID_ARGS;
            }
            std::io::SeekFrom::Start(byte_offset as _)
        }
        sys::ma_seek_origin_ma_seek_origin_current => std::io::SeekFrom::Current(byte_offset as _),
        sys::ma_seek_origin_ma_seek_origin_end => std::io::SeekFrom::End(byte_offset as _),
        _ => return sys::ma_result_MA_INVALID_ARGS,
    };

    match user_data.writer.seek(pos) {
        Ok(_) => sys::ma_result_MA_SUCCESS,
        Err(_) => sys::ma_result_MA_ERROR,
    }
}

unsafe extern "C" fn encoder_seek_proc_no_op(
    encoder: *mut sys::ma_encoder,
    _byte_offset: i64,
    _origin: sys::ma_seek_origin,
) -> sys::ma_result {
    if encoder.is_null() {
        return sys::ma_result_MA_INVALID_ARGS;
    }

    sys::ma_result_MA_SUCCESS
}

mod encoder_ffi {
    use maudio_sys::ffi as sys;

    use crate::{
        encoder::{CodecFormat, Encoder, EncoderBuilder},
        pcm_frames::PcmFormat,
        AsRawRef, Binding, MaResult, MaudioError,
    };

    #[inline]
    pub fn ma_encoder_init<F: PcmFormat, E: CodecFormat>(
        on_write: sys::ma_encoder_write_proc,
        on_seek: sys::ma_encoder_seek_proc,
        user_data: *mut core::ffi::c_void,
        config: &EncoderBuilder<F, E>,
        encoder: *mut sys::ma_encoder,
    ) -> MaResult<()> {
        let res = unsafe {
            sys::ma_encoder_init(on_write, on_seek, user_data, config.as_raw_ptr(), encoder)
        };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_encoder_init_file<F: PcmFormat, E: CodecFormat>(
        path: std::ffi::CString,
        config: &EncoderBuilder<F, E>,
        encoder: *mut sys::ma_encoder,
    ) -> MaResult<()> {
        let res = unsafe { sys::ma_encoder_init_file(path.as_ptr(), config.as_raw_ptr(), encoder) };
        MaudioError::check(res)
    }

    #[inline]
    #[cfg(windows)]
    pub fn ma_encoder_init_file_w<F: PcmFormat, E: CodecFormat>(
        path: &[u16],
        config: &EncoderBuilder<F, E>,
        encoder: *mut sys::ma_encoder,
    ) -> MaResult<()> {
        let res =
            unsafe { sys::ma_encoder_init_file_w(path.as_ptr(), config.as_raw_ptr(), encoder) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_encoder_uninit<F: PcmFormat, E: CodecFormat, D>(encoder: &mut Encoder<F, E, D>) {
        unsafe {
            sys::ma_encoder_uninit(encoder.to_raw());
        };
    }

    pub fn ma_encoder_write_pcm_frames<F: PcmFormat, E: CodecFormat, D>(
        encoder: &mut Encoder<F, E, D>,
        source: &[F::StorageUnit],
    ) -> MaResult<u64> {
        if source.is_empty() || encoder.channels == 0 {
            return Err(MaudioError::from_ma_result(sys::ma_result_MA_INVALID_ARGS));
        };
        let frames = source.len() / (encoder.channels as usize) / F::VEC_STORE_UNITS_PER_FRAME;

        ma_encoder_write_pcm_frames_internal(
            encoder,
            source.as_ptr() as *const core::ffi::c_void,
            frames as u64,
        )
    }

    #[inline]
    fn ma_encoder_write_pcm_frames_internal<F: PcmFormat, E: CodecFormat, D>(
        encoder: &mut Encoder<F, E, D>,
        frames_in: *const core::ffi::c_void,
        frame_count: u64,
    ) -> MaResult<u64> {
        let mut frames_written: u64 = 0;
        let res = unsafe {
            sys::ma_encoder_write_pcm_frames(
                encoder.to_raw(),
                frames_in,
                frame_count,
                &mut frames_written,
            )
        };
        MaudioError::check(res)?;
        Ok(frames_written)
    }
}

fn encoder_user_data_drop<W: WriteSeek>(ptr: *mut core::ffi::c_void) {
    drop(unsafe { Box::from_raw(ptr as *mut EncoderUserData<W>) });
}

impl<F: PcmFormat, E: CodecFormat, D> Drop for Encoder<F, E, D> {
    fn drop(&mut self) {
        encoder_ffi::ma_encoder_uninit(self);
        if let Some((ptr, destructor)) = self.user_data {
            destructor(ptr);
        }
        drop(unsafe { Box::from_raw(self.inner) });
    }
}

/// Encoding/container formats supported by [`Encoder`].
pub enum EncodingFormat {
    Wav,
    Flac,
    Mp3,
    Vorbis,
}

impl From<EncodingFormat> for sys::ma_encoding_format {
    fn from(value: EncodingFormat) -> Self {
        match value {
            EncodingFormat::Wav => sys::ma_encoding_format_ma_encoding_format_wav,
            EncodingFormat::Flac => sys::ma_encoding_format_ma_encoding_format_flac,
            EncodingFormat::Mp3 => sys::ma_encoding_format_ma_encoding_format_mp3,
            EncodingFormat::Vorbis => sys::ma_encoding_format_ma_encoding_format_vorbis,
        }
    }
}

impl TryFrom<sys::ma_encoding_format> for EncodingFormat {
    type Error = MaudioError;

    fn try_from(value: sys::ma_encoding_format) -> Result<Self, Self::Error> {
        match value {
            sys::ma_encoding_format_ma_encoding_format_wav => Ok(EncodingFormat::Wav),
            sys::ma_encoding_format_ma_encoding_format_flac => Ok(EncodingFormat::Flac),
            sys::ma_encoding_format_ma_encoding_format_mp3 => Ok(EncodingFormat::Mp3),
            sys::ma_encoding_format_ma_encoding_format_vorbis => Ok(EncodingFormat::Vorbis),
            other => Err(MaudioError::new_ma_error(ErrorKinds::unknown_enum::<
                EncodingFormat,
            >(other as i64))),
        }
    }
}

/// Builder for creating an [`Encoder`].
///
/// `EncoderBuilder` uses a staged type-state API to guide encoder construction:
///
/// 1. choose the PCM sample format with a `new_*` constructor
/// 2. choose the encoding/container format with methods like [`Self::wav`] (others not supported for now)
/// 3. build the encoder for a destination with [`Self::build_file`] or [`Self::build_writer`]
///
pub struct EncoderBuilder<F = Unknown, E = Unknown> {
    inner: sys::ma_encoder_config,
    alloc_cb: Option<Arc<AllocationCallbacks>>,
    format: Format,
    channels: u32,
    sample_rate: SampleRate,
    _format: PhantomData<F>,
    _encoding: PhantomData<E>,
}

impl<F: PcmFormat, E: CodecFormat> AsRawRef for EncoderBuilder<F, E> {
    type Raw = sys::ma_encoder_config;

    fn as_raw(&self) -> &Self::Raw {
        &self.inner
    }
}

impl EncoderBuilder<Unknown, Unknown> {
    pub fn new_inner(
        channels: u32,
        sample_rate: SampleRate,
        format: Format,
    ) -> sys::ma_encoder_config {
        // Format::U8 and encoding format unkwown are placeholders
        unsafe {
            sys::ma_encoder_config_init(
                sys::ma_encoding_format_ma_encoding_format_unknown,
                format.into(),
                channels,
                sample_rate.into(),
            )
        }
    }

    pub fn new_u8(channels: u32, sample_rate: SampleRate) -> EncoderBuilder<u8, Unknown> {
        let inner = EncoderBuilder::new_inner(channels, sample_rate, Format::U8);
        EncoderBuilder {
            inner,
            alloc_cb: None,
            format: Format::U8,
            channels,
            sample_rate,
            _format: PhantomData,
            _encoding: PhantomData,
        }
    }

    pub fn new_i16(channels: u32, sample_rate: SampleRate) -> EncoderBuilder<i16, Unknown> {
        let inner = EncoderBuilder::new_inner(channels, sample_rate, Format::S16);
        EncoderBuilder {
            inner,
            alloc_cb: None,
            format: Format::S16,
            channels,
            sample_rate,
            _format: PhantomData,
            _encoding: PhantomData,
        }
    }

    pub fn new_i32(channels: u32, sample_rate: SampleRate) -> EncoderBuilder<i32, Unknown> {
        let inner = EncoderBuilder::new_inner(channels, sample_rate, Format::S32);
        EncoderBuilder {
            inner,
            alloc_cb: None,
            format: Format::S32,
            channels,
            sample_rate,
            _format: PhantomData,
            _encoding: PhantomData,
        }
    }

    pub fn new_s24_packed(
        channels: u32,
        sample_rate: SampleRate,
    ) -> EncoderBuilder<S24Packed, Unknown> {
        let inner = EncoderBuilder::new_inner(channels, sample_rate, Format::S24Packed);
        EncoderBuilder {
            inner,
            alloc_cb: None,
            format: Format::S24Packed,
            channels,
            sample_rate,
            _format: PhantomData,
            _encoding: PhantomData,
        }
    }

    pub fn new_f32(channels: u32, sample_rate: SampleRate) -> EncoderBuilder<f32, Unknown> {
        let inner = EncoderBuilder::new_inner(channels, sample_rate, Format::F32);
        EncoderBuilder {
            inner,
            alloc_cb: None,
            format: Format::F32,
            channels,
            sample_rate,
            _format: PhantomData,
            _encoding: PhantomData,
        }
    }
}

pub struct Wav {}

/// Trait for the codec formats supporter by the `Encoder`
pub trait CodecFormat {}
impl CodecFormat for Wav {}

impl<F: PcmFormat> EncoderBuilder<F, Unknown> {
    pub fn wav(mut self) -> EncoderBuilder<F, Wav> {
        self.inner.encodingFormat = EncodingFormat::Wav.into();
        EncoderBuilder {
            inner: self.inner,
            alloc_cb: self.alloc_cb,
            format: self.format,
            channels: self.channels,
            sample_rate: self.sample_rate,
            _format: PhantomData,
            _encoding: PhantomData,
        }
    }
}

impl<F: PcmFormat, E: CodecFormat> EncoderBuilder<F, E> {
    pub fn build_file(&self, path: &Path) -> MaResult<Encoder<F, E, Fs>> {
        Encoder::<F, E, Fs>::init_from_file(self, path)
    }

    pub fn build_writer<W: WriteSeek>(&self, writer: W) -> MaResult<Encoder<F, E, Cb>> {
        Encoder::<F, E, Cb>::init_from_writer(self, writer)
    }
}

#[cfg(test)]
mod test {
    use crate::{
        audio::sample_rate::SampleRate,
        data_source::sources::decoder::{DecoderBuilder, DecoderOps},
        encoder::EncoderBuilder,
        test_assets::{
            decoded_data::{
                asset_interleaved_f32, asset_interleaved_i16, asset_interleaved_i32,
                asset_interleaved_s24_packed_le, asset_interleaved_u8,
            },
            temp_file::{unique_tmp_path, TempFileGuard},
        },
    };

    #[test]
    fn test_encoder_write_from_path_u8() {
        let frames_total: usize = 40;
        let data = asset_interleaved_u8(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));

        let mut enc = EncoderBuilder::new_u8(2, SampleRate::Sr48000)
            .wav()
            .build_file(guard.path())
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_u8(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_path_i16() {
        let frames_total: usize = 40;
        let data = asset_interleaved_i16(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));

        let mut enc = EncoderBuilder::new_i16(2, SampleRate::Sr48000)
            .wav()
            .build_file(guard.path())
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_i16(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_path_i32() {
        let frames_total: usize = 40;
        let data = asset_interleaved_i32(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));

        let mut enc = EncoderBuilder::new_i32(2, SampleRate::Sr48000)
            .wav()
            .build_file(guard.path())
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_i32(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_path_s24_packed() {
        let frames_total: usize = 40;
        let data = asset_interleaved_s24_packed_le(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));

        let mut enc = EncoderBuilder::new_s24_packed(2, SampleRate::Sr48000)
            .wav()
            .build_file(guard.path())
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_s24_packed(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_path_f32() {
        let frames_total: usize = 40;
        let data = asset_interleaved_f32(2, frames_total, 1.0);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));

        let mut enc = EncoderBuilder::new_f32(2, SampleRate::Sr48000)
            .wav()
            .build_file(guard.path())
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_f32(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_file_u8() {
        let frames_total: usize = 40;
        let data = asset_interleaved_u8(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));
        let file = std::fs::File::create(guard.path()).unwrap();

        let mut enc = EncoderBuilder::new_u8(2, SampleRate::Sr48000)
            .wav()
            .build_writer(file)
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_u8(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_file_i16() {
        let frames_total: usize = 40;
        let data = asset_interleaved_i16(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));
        let file = std::fs::File::create(guard.path()).unwrap();

        let mut enc = EncoderBuilder::new_i16(2, SampleRate::Sr48000)
            .wav()
            .build_writer(file)
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_i16(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_file_i32() {
        let frames_total: usize = 40;
        let data = asset_interleaved_i32(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));
        let file = std::fs::File::create(guard.path()).unwrap();

        let mut enc = EncoderBuilder::new_i32(2, SampleRate::Sr48000)
            .wav()
            .build_writer(file)
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_i32(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_file_s24_packed() {
        let frames_total: usize = 40;
        let data = asset_interleaved_s24_packed_le(2, frames_total, 1);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));
        let file = std::fs::File::create(guard.path()).unwrap();

        let mut enc = EncoderBuilder::new_s24_packed(2, SampleRate::Sr48000)
            .wav()
            .build_writer(file)
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_s24_packed(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }

    #[test]
    fn test_encoder_write_from_file_f32() {
        let frames_total: usize = 40;
        let data = asset_interleaved_f32(2, frames_total, 1.0);

        let guard = TempFileGuard::new(unique_tmp_path("wav"));
        let file = std::fs::File::create(guard.path()).unwrap();

        let mut enc = EncoderBuilder::new_f32(2, SampleRate::Sr48000)
            .wav()
            .build_writer(file)
            .unwrap();

        let written = enc.write_pcm_frames(&data).unwrap();

        drop(enc);

        assert_eq!(frames_total, written as usize);

        let mut dec = DecoderBuilder::new_f32(2, SampleRate::Sr48000)
            .from_file(guard.path())
            .unwrap();

        let output = dec.read_pcm_frames(frames_total as u64).unwrap();

        assert_eq!(&data, output.as_ref());
    }
}