kittyaudio 0.2.0

An audio playback library focusing on simplicity
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
use crate::{lerp_f64, Change, Command, Parameter, Resampler, Tweenable};
use parking_lot::{Mutex, MutexGuard};
use std::ops::{Add, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use std::ops::{AddAssign, RangeInclusive};
use std::sync::Arc;
use std::time::Duration;

#[cfg(feature = "symphonia")]
use {crate::KaError, std::io::Cursor};

/// Includes a sound in the executable. The `symphonia` feature must be
/// enabled for this macro to exist.
///
/// This is a shorthand for `Sound::from_cursor(Cursor::new(include_bytes!(path)))`.
#[macro_export]
#[cfg(feature = "symphonia")]
macro_rules! include_sound {
    ($path:expr) => {
        $crate::Sound::from_cursor(::std::io::Cursor::new(include_bytes!($path)))
    };
}

#[cfg(feature = "symphonia")]
use symphonia::core::{
    audio::Signal,
    audio::{AudioBuffer, AudioBufferRef},
    conv::{FromSample, IntoSample},
    io::MediaSource,
    sample::Sample,
};

/// Represents an audio sample. Stores a left and right channel.
#[derive(Debug, Copy, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Frame {
    /// Left channel value. Float.
    pub left: f32,
    /// Right channel value. Float.
    pub right: f32,
}

impl Frame {
    /// A frame with all channels set to 0.0.
    pub const ZERO: Self = Self {
        left: 0.0,
        right: 0.0,
    };

    /// Create a new audio frame from left and right values.
    #[inline]
    pub const fn new(left: f32, right: f32) -> Self {
        Self { left, right }
    }

    /// Create a new audio frame from a single value.
    #[inline]
    pub const fn from_mono(value: f32) -> Self {
        Self::new(value, value)
    }

    /// Pan a frame left or right.
    ///
    /// * `x` of 0.0 means hard left panning
    /// * `x` of 0.5 means center panning (default)
    /// * `x` of 1.0 means hard right panning
    pub fn panned(self, x: f32) -> Self {
        if x == 0.5 {
            return self;
        }
        Self::new(self.left * (1.0 - x).sqrt(), self.right * x.sqrt()) * std::f32::consts::SQRT_2
    }
}

impl From<[f32; 2]> for Frame {
    fn from(lr: [f32; 2]) -> Self {
        Self::new(lr[0], lr[1])
    }
}

impl From<(f32, f32)> for Frame {
    fn from(lr: (f32, f32)) -> Self {
        Self::new(lr.0, lr.1)
    }
}

impl From<f32> for Frame {
    fn from(value: f32) -> Self {
        Self::from_mono(value)
    }
}

impl Add for Frame {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self::new(self.left + rhs.left, self.right + rhs.right)
    }
}

impl AddAssign for Frame {
    fn add_assign(&mut self, rhs: Self) {
        self.left += rhs.left;
        self.right += rhs.right;
    }
}

impl Sub for Frame {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Self::new(self.left - rhs.left, self.right - rhs.right)
    }
}

impl SubAssign for Frame {
    fn sub_assign(&mut self, rhs: Self) {
        self.left -= rhs.left;
        self.right -= rhs.right;
    }
}

impl Mul<f32> for Frame {
    type Output = Self;

    fn mul(self, rhs: f32) -> Self::Output {
        Self::new(self.left * rhs, self.right * rhs)
    }
}

impl MulAssign<f32> for Frame {
    fn mul_assign(&mut self, rhs: f32) {
        self.left *= rhs;
        self.right *= rhs;
    }
}

impl Div<f32> for Frame {
    type Output = Self;

    fn div(self, rhs: f32) -> Self::Output {
        Self::new(self.left / rhs, self.right / rhs)
    }
}

impl DivAssign<f32> for Frame {
    fn div_assign(&mut self, rhs: f32) {
        self.left /= rhs;
        self.right /= rhs;
    }
}

impl Neg for Frame {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Self::new(-self.left, -self.right)
    }
}

/// Specifies how quickly the sound is played.
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PlaybackRate {
    /// The sound is playing at a speed factor of the original sample rate.
    ///
    /// For example, `PlaybackRate::Factor(4.0)` means that the sound is
    /// played 4 times as fast compared to `PlaybackRate::Factor(1.0)`
    Factor(f64),
    /// The speed of the sound is controlled in a way that the pitch is
    /// adjusted by the given number of semitones.
    Semitones(f64),
}

impl Default for PlaybackRate {
    fn default() -> Self {
        Self::Factor(1.0)
    }
}

impl PlaybackRate {
    /// Returns the playback rate as a factor of the original sample rate.
    #[inline] // float arithmetic is not allowed in const fns
    pub fn as_factor(self) -> f64 {
        match self {
            Self::Factor(factor) => factor,
            Self::Semitones(semitones) => (semitones / 12.0).exp2(),
        }
    }

    /// Returns the amount of semitones (pitch difference) this playback rate
    /// would result in.
    #[inline] // float arithmetic is not allowed in const fns
    pub fn as_semitones(self) -> f64 {
        match self {
            Self::Factor(factor) => 12.0 * factor.log2(),
            Self::Semitones(semitones) => semitones,
        }
    }

    /// Reverse the playback rate so the sound plays backwards.
    pub fn reverse(self) -> Self {
        match self {
            Self::Factor(factor) => Self::Factor(-factor),
            Self::Semitones(semitones) => Self::Semitones(-semitones),
        }
    }
}

impl From<f64> for PlaybackRate {
    fn from(factor: f64) -> Self {
        Self::Factor(factor)
    }
}

impl Tweenable for PlaybackRate {
    fn interpolate(a: Self, b: Self, t: f32) -> Self {
        match a {
            Self::Factor(factor) => Self::Factor(lerp_f64(factor, b.as_factor(), t as f64)),
            Self::Semitones(semitones) => {
                Self::Semitones(lerp_f64(semitones, b.as_semitones(), t as f64))
            }
        }
    }
}

/// Specifies a loop region.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct LoopPoints {
    /// Start of the loop as a frame index.
    pub start: usize,
    /// End of the loop as a frame index.
    pub end: usize,
}

impl LoopPoints {
    /// No loop.
    const NO_LOOP: Self = Self {
        start: 0,
        end: usize::MAX,
    };

    /// Make [`LoopPoints`] from an index range.
    #[inline]
    pub const fn from_range(range: RangeInclusive<usize>) -> Self {
        Self {
            start: *range.start(),
            end: *range.end(),
        }
    }

    /// Make [`LoopPoints`] from a seconds range.
    #[inline]
    pub fn from_range_secs(range: RangeInclusive<f64>, sample_rate: u32) -> Self {
        Self {
            start: (range.start() * sample_rate as f64) as usize,
            end: (range.end() * sample_rate as f64) as usize,
        }
    }

    /// Get start value in seconds.
    #[inline]
    fn start_secs(&self, sample_rate: u32) -> f64 {
        self.start as f64 / sample_rate as f64
    }

    /// Get end value in seconds.
    #[inline]
    fn end_secs(&self, sample_rate: u32) -> f64 {
        self.end as f64 / sample_rate as f64
    }
}

impl Tweenable for LoopPoints {
    fn interpolate(a: Self, b: Self, t: f32) -> Self {
        Self {
            start: lerp_f64(a.start as f64, b.start as f64, t as f64) as usize,
            end: lerp_f64(a.end as f64, b.end as f64, t as f64) as usize,
        }
    }
}

/// Audio data stored in memory. This type can be cheaply cloned, as the
/// audio data is shared between all clones.
#[derive(Debug, Clone, PartialEq)]
pub struct Sound {
    /// Sample rate of the sound.
    sample_rate: u32,
    /// Audio data. Not mutable. Shared between all clones.
    pub frames: Arc<[Frame]>,
    /// Whether the sound is paused.
    pub paused: bool,
    /// The current playback position in frames.
    index: Parameter<usize>,
    /// The resampler used to resample the audio data.
    resampler: Resampler,
    /// The current playback rate of the sound. See [`PlaybackRate`] for more
    /// details.
    playback_rate: Parameter<PlaybackRate>,
    /// Fractional position between samples. Always in the range of 0-1.
    fractional_position: f64,
    /// Current volume of the samples pushed to the resampler.
    volume: Parameter<f32>,
    /// All unfinished commands.
    commands: Vec<Command>,
    /// Current two loop points.
    loop_points: Parameter<LoopPoints>,
    /// Whether looping is enabled.
    pub loop_enabled: bool,
    /// Controls the audio panning.
    ///
    /// * Panning of 0.0 means hard left panning
    /// * Panning of 0.5 means center panning (default)
    /// * Panning of 1.0 means hard right panning
    panning: Parameter<f32>,
}

impl Default for Sound {
    fn default() -> Self {
        Self {
            sample_rate: 0,
            frames: Arc::new([]),
            paused: false,
            index: Parameter::new(0),
            resampler: Resampler::new(0),
            playback_rate: Parameter::new(PlaybackRate::Factor(1.0)),
            fractional_position: 0.0,
            volume: Parameter::new(1.0),
            commands: vec![],
            loop_points: Parameter::new(LoopPoints::NO_LOOP),
            loop_enabled: false,
            panning: Parameter::new(0.5),
        }
    }
}

/// Helper function to convert Symphonia's [`AudioBufferRef`] to a vector of [`Frame`]s.
#[cfg(feature = "symphonia")]
fn load_frames_from_buffer_ref(buffer: &AudioBufferRef) -> Result<Vec<Frame>, KaError> {
    match buffer {
        AudioBufferRef::U8(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::U16(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::U24(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::U32(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::S8(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::S16(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::S24(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::S32(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::F32(buffer) => load_frames_from_buffer(buffer),
        AudioBufferRef::F64(buffer) => load_frames_from_buffer(buffer),
    }
}

/// Convert an [`AudioBuffer`] into a [`Vec`] of [`Frame`]s.
#[cfg(feature = "symphonia")]
fn load_frames_from_buffer<S: Sample>(buffer: &AudioBuffer<S>) -> Result<Vec<Frame>, KaError>
where
    f32: FromSample<S>,
{
    let num_channels = buffer.spec().channels.count();
    match num_channels {
        1 => Ok(buffer
            .chan(0)
            .iter()
            .map(|sample| Frame::from_mono((*sample).into_sample()))
            .collect()),
        2 => Ok(buffer
            .chan(0)
            .iter()
            .zip(buffer.chan(1).iter())
            .map(|(left, right)| Frame::new((*left).into_sample(), (*right).into_sample()))
            .collect()),
        _ => Err(KaError::UnsupportedNumberOfChannels(num_channels as u32)),
    }
}

impl Sound {
    /// Make a new [`Sound`] with a given sample rate and frames.
    fn new(sample_rate: u32, frames: Arc<[Frame]>) -> Self {
        let mut sound = Sound {
            sample_rate,
            frames,
            ..Default::default()
        };

        // fill the resampler with 3 audio frames so the playback starts
        // immediately (the resampler needs 4 samples to output any audio)
        for _ in 0..3 {
            sound.update_position();
        }

        sound
    }

    /// Make a [`Sound`] from [`symphonia`]'s [`Box`]'ed [`MediaSource`].
    ///
    /// Required features: `symphonia`
    #[cfg(feature = "symphonia")]
    pub fn from_boxed_media_source(media_source: Box<dyn MediaSource>) -> Result<Self, KaError> {
        use std::io::ErrorKind::UnexpectedEof;
        use symphonia::core::codecs::DecoderOptions;
        use symphonia::core::errors::Error;
        use symphonia::core::formats::FormatOptions;
        use symphonia::core::io::MediaSourceStream;
        use symphonia::core::meta::MetadataOptions;
        use symphonia::core::probe::Hint;

        // create a media source stream from the provided media source
        let mss = MediaSourceStream::new(media_source, Default::default());

        // create a hint to help the format registry to guess what format
        // the media source is using, we'll let symphonia figure that out for us
        let hint = Hint::new();

        // use default options for reading and encoding
        let format_opts: FormatOptions = Default::default();
        let metadata_opts: MetadataOptions = Default::default();
        let decoder_opts: DecoderOptions = Default::default();

        // probe the media source for a format
        let probed =
            symphonia::default::get_probe().format(&hint, mss, &format_opts, &metadata_opts)?;

        let mut format = probed.format;
        let track = format.default_track().ok_or(KaError::NoTracksArePresent)?;

        // create a decoder for the track
        let mut decoder =
            symphonia::default::get_codecs().make(&track.codec_params, &decoder_opts)?;

        // store the track identifier, we'll use it to filter packets
        let track_id = track.id;

        // get sample rate
        let sample_rate = track
            .codec_params
            .sample_rate
            .ok_or(KaError::UnknownSampleRate)?;

        let mut frames = Vec::new(); // audio data

        loop {
            // get the next packet from the format reader
            let packet = match format.next_packet() {
                Ok(p) => p,
                Err(Error::IoError(e)) => {
                    // if we reached eof, stop decoding
                    if e.kind() == UnexpectedEof {
                        break;
                    }
                    // ...otherwise return KaError
                    return Err(Error::IoError(e).into());
                }
                Err(e) => return Err(e.into()), // not io error
            };

            // if the packet does not belong to the selected track, skip it
            if packet.track_id() != track_id {
                continue;
            }

            // decode packet
            let buffer = decoder.decode(&packet)?;
            frames.append(&mut load_frames_from_buffer_ref(&buffer)?);
        }

        Ok(Self::new(sample_rate, frames.into()))
    }

    /// Make a [`Sound`] from [`symphonia`]'s [`MediaSource`].
    ///
    /// Required features: `symphonia`
    #[cfg(feature = "symphonia")]
    #[inline]
    pub fn from_media_source(media_source: impl MediaSource + 'static) -> Result<Self, KaError> {
        Self::from_boxed_media_source(Box::new(media_source))
    }

    /// Make a [`Sound`] from a [`Cursor`] of bytes. Uses [`symphonia`] to decode audio.
    ///
    /// Required features: `symphonia`
    #[cfg(feature = "symphonia")]
    #[inline]
    pub fn from_cursor<T: AsRef<[u8]> + Send + Sync + 'static>(
        cursor: Cursor<T>,
    ) -> Result<Self, KaError> {
        Self::from_media_source(cursor)
    }

    /// Make a [`Sound`] from a file path. Uses [`symphonia`] to decode audio.
    ///
    /// Required features: `symphonia`
    #[cfg(feature = "symphonia")]
    #[inline]
    pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self, KaError> {
        Self::from_media_source(std::fs::File::open(path)?)
    }

    /// Make a [`Sound`] from a [`Vec`] of bytes ([`u8`]). Uses [`symphonia`] to decode audio.
    ///
    /// Required features: `symphonia`
    #[cfg(feature = "symphonia")]
    #[inline]
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, KaError> {
        Self::from_cursor(Cursor::new(bytes))
    }

    /// Make a [`Sound`] from a slice of [`Frame`]s and a sample rate.
    #[inline]
    pub fn from_frames(sample_rate: u32, frames: &[Frame]) -> Self {
        Self::new(sample_rate, frames.into())
    }

    /// Return the sample rate of the sound.
    #[inline]
    pub const fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    /// Return the duration of the sound.
    ///
    /// Returns [`Duration`].
    #[inline]
    pub fn duration(&self) -> Duration {
        Duration::from_secs_f64(self.duration_seconds())
    }

    /// Return the duration of the sound in seconds.
    #[inline]
    pub fn duration_seconds(&self) -> f64 {
        self.frames.len() as f64 / self.sample_rate as f64
    }

    /// Push the current frame (pointed by `self.index`) to the resampler.
    pub fn push_frame_to_resampler(&mut self) {
        let frame_index = self.index.value;
        let frame = self
            .frames
            .get(frame_index)
            .unwrap_or(&Frame::ZERO) // push silence if index is out of the range
            .panned(self.panning.value.max(0.0))
            * self.volume.value;
        self.resampler.push_frame(frame, frame_index);
    }

    /// Return whether the sound is playing backward.
    #[inline]
    pub fn is_playing_backwards(&mut self) -> bool {
        self.playback_rate.value.as_factor().is_sign_negative()
    }

    /// Increment/decrement the position value in the sound, pushing the
    /// previous sound frame to the resampler.
    pub fn update_position(&mut self) {
        if self.paused {
            self.resampler.push_frame(Frame::ZERO, self.index.value);
        } else {
            self.push_frame_to_resampler();

            // increment/decrement index
            if self.is_playing_backwards() {
                self.index.value -= 1;
            } else {
                self.index.value += 1
            }
        }
    }

    /// Return whether the sound has finished playback.
    #[inline]
    pub fn finished(&self) -> bool {
        self.index.value >= self.frames.len()
    }

    /// Render the next frame. If the sound has ended, return [`None`].
    #[inline]
    pub fn next_frame(&mut self, sample_rate: u32) -> Option<Frame> {
        if self.finished() {
            return None;
        }

        if self.loop_enabled {
            self.update_loop(self.loop_points.value.start, self.loop_points.value.end);
        }

        // update commands
        if !self.commands.is_empty() {
            self.update_commands(1.0 / sample_rate as f64);
        }

        // get resampled frame
        let frame = self.resampler.get(self.fractional_position as f32);

        // increment fractional position
        self.fractional_position += (self.sample_rate as f64 / sample_rate as f64)
            * self.playback_rate.value.as_factor().abs();

        // step the corrent amount of samples forward/backward
        while self.fractional_position >= 1.0 {
            self.fractional_position -= 1.0;
            self.update_position();
        }

        Some(frame)
    }

    fn update_loop(&mut self, start: usize, end: usize) {
        let index = self.index.value;
        if self.is_playing_backwards() {
            if index <= start {
                self.seek_to_index(end);
            }
        } else if index >= end {
            self.seek_to_index(start);
        }
    }

    /// Reset the sound to the beginning.
    #[inline]
    pub fn reset(&mut self) {
        self.seek_to_index(0);
    }

    /// Set the playback rate of the sound. See [`PlaybackRate`] for more
    /// details. Returns the previous playback rate.
    #[inline]
    pub fn set_playback_rate(&mut self, playback_rate: PlaybackRate) -> PlaybackRate {
        let prev_playback_rate = self.playback_rate.value;
        self.playback_rate.start_tween(playback_rate);
        prev_playback_rate
    }

    /// Return the current playback rate value. Can be modified with commands.
    #[inline]
    pub fn playback_rate(&self) -> PlaybackRate {
        self.playback_rate.value
    }

    /// Return the current base playback rate value. Can't be modified with commands.
    #[inline]
    pub fn base_playback_rate(&self) -> PlaybackRate {
        self.playback_rate.base_value
    }

    /// Set the current volume. Return the previous volume value.
    #[inline]
    pub fn set_volume(&mut self, volume: f32) -> f32 {
        let prev_volume = self.volume.value;
        self.volume.start_tween(volume);
        prev_volume
    }

    /// Return the current volume value. Can be modified with commands.
    #[inline]
    pub fn volume(&self) -> f32 {
        self.volume.value
    }

    /// Return the current base volume value. Can't be modified with commands.
    #[inline]
    pub fn base_volume(&self) -> f32 {
        self.volume.base_value
    }

    /// Seek to an index in the source data.
    #[inline]
    pub fn seek_to_index(&mut self, index: usize) {
        self.index.start_tween(index);

        // if the sound is playing, push this frame to the resampler so it
        // doesn't get skipped
        if !self.paused {
            self.push_frame_to_resampler();
        }
    }

    /// Seek to the end of the sound.
    #[inline]
    pub fn seek_to_end(&mut self) {
        self.seek_to_index(self.frames.len().saturating_sub(1));
    }

    /// Seek by a specified amount of seconds.
    #[inline]
    pub fn seek_by(&mut self, seconds: f64) {
        let cur_position = self.index.value as f64 / self.sample_rate as f64;
        let position = cur_position + seconds;
        let index = (position * self.sample_rate as f64) as usize;
        self.seek_to_index(index);
    }

    /// Seek to a specified position in seconds.
    #[inline]
    pub fn seek_to(&mut self, seconds: f64) {
        let index = (seconds * self.sample_rate as f64) as usize;
        self.seek_to_index(index);
    }

    /// Reverse the playback rate so the sound plays backwards.
    #[inline]
    pub fn reverse(&mut self) {
        self.playback_rate
            .start_tween(self.playback_rate.value.reverse())
    }

    /// Add a command to the sound. See [`Command`] for more details.
    #[inline]
    pub fn add_command(&mut self, command: Command) {
        self.commands.push(command)
    }

    fn update_commands(&mut self, dt: f64) {
        self.commands.retain_mut(|command| {
            let is_nonzero_duration = command.duration > 0.0;
            if !is_nonzero_duration {
                // this is on the top of this loop because the command.start_after <= check
                // must be triggered before the stop tween check so commands with
                // 0 duration are triggered
                command.start_after -= dt;
            }

            if command.start_after <= 0.0 {
                // compute value with easing
                // start_after will be negative, and it counts the amount of time the sound has been running for
                // t is a value between 0 and 1
                let t = if is_nonzero_duration {
                    // if we divide by 0 here we'll get a NaN
                    command.value((-command.start_after / command.duration) as f32)
                } else {
                    // commands with 0 or less duration end immediately
                    1.0
                };

                // apply change
                match &command.change {
                    Change::Volume(vol) => self.volume.update(*vol, t),
                    Change::Index(index) => {
                        self.index.update(*index, t);
                        // TODO: push frame to resampler
                    }
                    Change::Position(position) => {
                        let index = position * self.sample_rate as f64;
                        self.index.update(index as usize, t);
                        // TODO: push frame to resampler
                    }
                    Change::Pause(pause) => {
                        if t >= 0.5 {
                            self.paused = *pause;
                        }
                    }
                    Change::PlaybackRate(rate) => self.playback_rate.update(*rate, t),
                    Change::LoopSeconds(range) => self.loop_points.update(
                        LoopPoints::from_range_secs(range.clone(), self.sample_rate),
                        t,
                    ),
                    Change::LoopIndex(range) => self
                        .loop_points
                        .update(LoopPoints::from_range(range.clone()), t),
                    Change::Panning(panning) => self.panning.update(*panning, t),
                }
            }

            if is_nonzero_duration {
                // if start_after is negative, it measures the elapsed time the command
                // has been running
                command.start_after -= dt;
            }

            // if the command has finished, stop the tween
            let is_running = -command.start_after < command.duration;
            if !is_running {
                match command.change {
                    Change::Volume(_) => self.volume.stop_tween(),
                    Change::Index(_) => self.index.stop_tween(),
                    Change::Position(_) => self.index.stop_tween(),
                    Change::Pause(_) => (),
                    Change::PlaybackRate(_) => self.playback_rate.stop_tween(),
                    Change::LoopSeconds(_) | Change::LoopIndex(_) => self.loop_points.stop_tween(),
                    Change::Panning(_) => self.panning.stop_tween(),
                }
            }
            is_running // only keep commands that are running
        });
    }

    /// Set the loop points as a frame index.
    #[inline]
    pub fn set_loop_index(&mut self, loop_region: RangeInclusive<usize>) {
        self.loop_points
            .start_tween(LoopPoints::from_range(loop_region));
    }

    /// Set the current loop state (enabled/disabled). Return the previous loop state.
    #[inline]
    pub fn set_loop_enabled(&mut self, enabled: bool) -> bool {
        let prev_enabled = self.loop_enabled;
        self.loop_enabled = enabled;
        prev_enabled
    }

    /// Set the loop points as a position in seconds.
    #[inline]
    pub fn set_loop(&mut self, loop_region: RangeInclusive<f64>) {
        self.loop_points =
            Parameter::new(LoopPoints::from_range_secs(loop_region, self.sample_rate));
    }

    /// Return the starting point of the loop as a frame index.
    #[inline]
    pub fn loop_start(&self) -> usize {
        self.loop_points.value.start
    }

    /// Return the ending point of the loop as a frame index.
    #[inline]
    pub fn loop_end(&self) -> usize {
        self.loop_points.value.end
    }

    /// Return the starting point of the loop as seconds.
    #[inline]
    pub fn loop_start_secs(&self) -> f64 {
        self.loop_points.value.start_secs(self.sample_rate)
    }

    /// Return the ending point of the loop as seconds.
    #[inline]
    pub fn loop_end_secs(&self) -> f64 {
        self.loop_points.value.end_secs(self.sample_rate)
    }

    /// Return the current index in the source sound data. Can be modified with commands.
    #[inline]
    pub fn index(&self) -> usize {
        self.index.value
    }

    /// Return the current index in the source sound data. Cannot be modified with commands.
    #[inline]
    pub fn base_index(&self) -> usize {
        self.index.base_value
    }

    /// Return whether the sound is currently outputting silence.
    #[inline]
    pub fn outputting_silence(&self) -> bool {
        self.resampler.outputting_silence()
    }

    /// Pause the sound if it is playing. This won't cut off the audio signal, but smoothly
    /// interpolate the last audio value to 0 for 4 frames.
    #[inline]
    pub fn pause(&mut self) {
        self.paused = true;
    }

    /// Return whether the sound is paused. This does not take the playback speed for account.
    #[inline]
    pub fn paused(&self) -> bool {
        self.paused
    }

    /// Resume the sound if paused. This won't immediately start the audio signal, but smoothly
    /// interpolate the last audio value for 4 frames.
    #[inline]
    pub fn resume(&mut self) {
        self.paused = false;
    }

    /// Set the audio panning.
    ///
    /// * Panning of 0.0 means hard left panning
    /// * Panning of 0.5 means center panning (default)
    /// * Panning of 1.0 means hard right panning
    ///
    /// # Returns
    ///
    /// Returns the previous panning value
    #[inline]
    pub fn set_panning(&mut self, panning: f32) -> f32 {
        let prev_panning = self.panning.value;
        self.panning.start_tween(panning);
        prev_panning
    }

    /// Get the audio panning.
    ///
    /// * Panning of 0.0 means hard left panning
    /// * Panning of 0.5 means center panning (default)
    /// * Panning of 1.0 means hard right panning
    ///
    /// # Returns
    ///
    /// Returns the panning value
    #[inline]
    pub fn panning(&mut self) -> f32 {
        self.panning.value
    }
}

/// Wraps a [`Sound`] so it can be returned to the user after `play`.
///
/// This type can be cheaply cloned, and it will share the same data.
#[derive(Debug, Clone)]
pub struct SoundHandle(Arc<Mutex<Sound>>);

impl From<Sound> for SoundHandle {
    fn from(sound: Sound) -> Self {
        Self::new(sound)
    }
}

impl SoundHandle {
    /// Make a new [`SoundHandle`] from a [`Sound`].
    #[inline]
    pub fn new(sound: Sound) -> Self {
        Self(Arc::new(Mutex::new(sound)))
    }

    /// Lock the [`Sound`] for modification. Returns a [`MutexGuard`].
    #[inline]
    pub fn guard(&self) -> MutexGuard<Sound> {
        self.0.lock()
    }

    /// Delegate to the underlying [`Sound`].
    #[inline]
    pub fn loop_enabled(&self) -> bool {
        return self.guard().loop_enabled;
    }
}

macro_rules! delegate {
    ($($name:ident($($arg:ident: $type:ty),*) $(-> $ret:ty)?),* $(,)?) => {
        $(
            /// Delegate to the underlying [`Sound`]'s method.
            #[inline]
            pub fn $name(&self, $($arg: $type),*) $(-> $ret)? {
                self.guard().$name($($arg),*)
            }
        )*
    };
}

// best solution for now?
impl SoundHandle {
    delegate! {
        sample_rate() -> u32,
        duration() -> Duration,
        duration_seconds() -> f64,
        push_frame_to_resampler(),
        is_playing_backwards() -> bool,
        update_position(),
        finished() -> bool,
        next_frame(sample_rate: u32) -> Option<Frame>,
        reset(),
        set_playback_rate(playback_rate: PlaybackRate) -> PlaybackRate,
        playback_rate() -> PlaybackRate,
        base_playback_rate() -> PlaybackRate,
        set_volume(volume: f32) -> f32,
        volume() -> f32,
        base_volume() -> f32,
        seek_to_index(index: usize),
        seek_to_end(),
        seek_by(seconds: f64),
        seek_to(seconds: f64),
        reverse(),
        add_command(command: Command),
        set_loop_index(loop_region: RangeInclusive<usize>),
        set_loop_enabled(enabled: bool) -> bool,
        set_loop(loop_region: RangeInclusive<f64>),
        loop_start() -> usize,
        loop_end() -> usize,
        loop_start_secs() -> f64,
        loop_end_secs() -> f64,
        index() -> usize,
        base_index() -> usize,
        outputting_silence() -> bool,
        pause(),
        paused() -> bool,
        resume(),
        set_panning(panning: f32) -> f32,
        panning() -> f32,
    }
}