euphorium 0.2.0

Painless audio playback for native and web platforms
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//! Individual sound playback and control.

#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
#[cfg(target_arch = "wasm32")]
use std::rc::Rc;
use std::{
    collections::VecDeque,
    ops::Range,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use dasp_sample::FromSample;
use rodio::{Player, Source};

use crate::{
    PlaybackRangeSource, SoundAsset, SoundEffects, SoundSource, SoundscapeError, decoder,
    format_timestamp, scene::SoundGroupId, wsola::Wsola,
};

/// The current playback lifecycle state of a [`crate::Sound`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PlaybackState {
    /// No source is currently playing or loading.
    Idle,
    /// An audio asset is being loaded asynchronously.
    Loading,
    /// A source is actively playing.
    Playing,
    /// The current source is paused.
    Paused,
    /// The current source reached the end of playback.
    Ended,
    /// The most recent loading or playback operation failed.
    Failed,
}

/// A playback lifecycle event emitted by [`crate::Sound::poll_event`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PlaybackEvent {
    /// The sound moved from one lifecycle state to another.
    StateChanged {
        /// The state before the transition.
        previous: PlaybackState,
        /// The state after the transition.
        current: PlaybackState,
    },
}

/// The complete mutable state of one sound in an audio scene.
pub struct SoundNode {
    pub(crate) name: String,
    pub(crate) group: SoundGroupId,
    pub(crate) source: SoundSource,
    pub(crate) source_revision: u64,
    pub(crate) source_loaded: bool,
    pub(crate) wants_playing: bool,
    pub(crate) locally_paused: bool,

    mixer: rodio::mixer::Mixer,
    voice: Player,

    /// The total duration of the current source, if known.
    duration: Option<Duration>,

    /// The offset of the current position in the source.
    position_offset: Duration,

    /// The player position corresponding to [`Self::position_offset`].
    player_position_anchor: Duration,
    speed: f32,
    preserve_pitch: bool,
    volume: f32,
    effects: SoundEffects,

    /// Whether playback repeats at its configured boundary.
    looping: Arc<AtomicBool>,

    /// The configured playback boundary within a source.
    loop_range: Option<Range<Duration>>,

    /// Whether the offset is the complete position while no source is actively playing.
    position_is_held: bool,

    /// The last observed playback lifecycle state.
    playback_state: PlaybackState,

    /// Playback lifecycle transitions waiting to be observed.
    playback_events: VecDeque<PlaybackEvent>,

    /// Playback lifecycle transitions waiting to be published by the scene.
    scene_events: VecDeque<PlaybackEvent>,

    /// Maximum number of playback lifecycle transitions retained for observation.
    event_capacity: usize,

    /// The result of an audio asset being loaded in the browser.
    #[cfg(target_arch = "wasm32")]
    pending_playback: Option<PendingPlayback>,
}

#[cfg(target_arch = "wasm32")]
type PendingPlayback = Rc<RefCell<Option<Result<Arc<[u8]>, SoundscapeError>>>>;

#[derive(Clone, Copy)]
enum SourceMetadata {
    Unloaded,
    Loaded(Option<Duration>),
}

impl SoundNode {
    pub(crate) fn new(
        name: String,
        group: SoundGroupId,
        source: SoundSource,
        mixer: rodio::mixer::Mixer,
    ) -> Result<Self, SoundscapeError> {
        let voice = Player::connect_new(&mixer);
        let mut sound = Self {
            name,
            group,
            source,
            source_revision: 0,
            source_loaded: false,
            wants_playing: false,
            locally_paused: false,
            mixer,
            voice,
            duration: None,
            position_offset: Duration::ZERO,
            player_position_anchor: Duration::ZERO,
            speed: 1.0,
            preserve_pitch: false,
            volume: 1.0,
            effects: SoundEffects::default(),
            looping: Arc::new(AtomicBool::new(false)),
            loop_range: None,
            position_is_held: true,
            playback_state: PlaybackState::Idle,
            playback_events: VecDeque::new(),
            scene_events: VecDeque::new(),
            event_capacity: usize::MAX,
            #[cfg(target_arch = "wasm32")]
            pending_playback: None,
        };
        sound.source_loaded = sound.load_source()?;
        Ok(sound)
    }

    fn connect_voice(&self) -> Player {
        Player::connect_new(&self.mixer)
    }

    fn has_current_source(&self) -> bool {
        self.source_loaded
    }

    pub(crate) fn replace_routing_preserving_playback(&mut self, mixer: rodio::mixer::Mixer) {
        let position = self.position();
        let was_playing = self.is_playing();
        let was_paused = self.is_paused();
        let has_source = self.has_current_source();
        self.mixer = mixer;

        if (was_playing || was_paused) && has_source {
            if self.try_seek(position).is_err() {
                self.voice = self.connect_voice();
                self.voice.set_volume(self.volume());
                self.voice.set_speed(self.player_speed());
                self.position_offset = position;
                self.player_position_anchor = Duration::ZERO;
                self.position_is_held = true;
            }

            return;
        }

        self.voice = self.connect_voice();
        self.voice.set_volume(self.volume());
        self.voice.set_speed(self.player_speed());
    }

    pub(crate) fn load_source(&mut self) -> Result<bool, SoundscapeError> {
        let metadata = Self::source_metadata(&self.source.clone())
            .map_err(|error| self.record_failure(error))?;
        match metadata {
            SourceMetadata::Unloaded => {
                self.reset_loaded_source(None);
                Ok(false)
            }
            SourceMetadata::Loaded(duration) => {
                self.reset_loaded_source(duration);
                Ok(true)
            }
        }
    }

    pub(crate) fn replace_source(&mut self, source: SoundSource) -> Result<(), SoundscapeError> {
        if self.source.same_resource(&source) {
            return Ok(());
        }

        let metadata = Self::source_metadata(&source)?;
        let position = self.position();
        let previous_state = self.state();
        let was_playing = previous_state == PlaybackState::Playing;
        let was_paused = previous_state == PlaybackState::Paused;
        let was_locally_paused = self.locally_paused;
        self.cancel_pending_playback();
        self.source = source;
        self.source_revision = self.source_revision.wrapping_add(1);
        let (source_loaded, duration) = match metadata {
            SourceMetadata::Unloaded => (false, None),
            SourceMetadata::Loaded(duration) => (true, duration),
        };

        self.source_loaded = source_loaded;
        self.reset_loaded_source(duration);
        let position = duration.map_or(position, |duration| position.min(duration));
        self.position_offset = position;

        if source_loaded && (was_playing || was_paused) {
            self.play_current_source_at(position)?;
            if was_paused {
                self.pause();
            }
        }

        self.wants_playing = was_playing || was_paused;
        self.locally_paused = was_locally_paused;
        Ok(())
    }

    fn source_metadata(source: &SoundSource) -> Result<SourceMetadata, SoundscapeError> {
        let duration = match source {
            SoundSource::Empty => return Ok(SourceMetadata::Unloaded),
            SoundSource::StaticBytes(bytes) => decoder::from_static_bytes(bytes)?.total_duration(),
            SoundSource::SharedBytes(bytes) => {
                decoder::from_shared_bytes(bytes.clone())?.total_duration()
            }
            #[cfg(not(target_arch = "wasm32"))]
            SoundSource::File(path) => decoder::from_file(path)?.total_duration(),
            SoundSource::Asset(asset) => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    decoder::from_file(asset.native_path())?.total_duration()
                }

                #[cfg(target_arch = "wasm32")]
                {
                    let Some(bytes) = asset.cached_browser_bytes() else {
                        return Ok(SourceMetadata::Unloaded);
                    };
                    decoder::from_shared_bytes(bytes)?.total_duration()
                }
            }
        };
        Ok(SourceMetadata::Loaded(duration))
    }

    /// Resumes playback of a paused player.
    ///
    /// No effect if not paused.
    fn play_source<S>(&mut self, source: S) -> Result<(), SoundscapeError>
    where
        S: Source + Send + 'static,
        f32: FromSample<S::Item>,
    {
        self.play_source_at(source, None)
    }

    fn play_source_at<S>(
        &mut self,
        source: S,
        requested_position: Option<Duration>,
    ) -> Result<(), SoundscapeError>
    where
        S: Source + Send + 'static,
        f32: FromSample<S::Item>,
    {
        self.queue_source_at(source, requested_position, true)
    }

    fn queue_source_at<S>(
        &mut self,
        mut source: S,
        requested_position: Option<Duration>,
        autoplay: bool,
    ) -> Result<(), SoundscapeError>
    where
        S: Source + Send + 'static,
        f32: FromSample<S::Item>,
    {
        let duration = source.total_duration();
        let (range_start, range_end) = self
            .playback_bounds(duration)
            .map_err(|error| self.record_failure(error))?;
        let position = if let Some(position) = requested_position {
            position
        } else if self.is_empty() {
            match source.total_duration() {
                Some(duration) => self.position_offset.min(duration),
                None => self.position_offset,
            }
        } else {
            Duration::ZERO
        };
        let position = range_end.map_or(position.max(range_start), |end| {
            position.clamp(range_start, end)
        });

        if !position.is_zero() {
            source
                .try_seek(position)
                .map_err(SoundscapeError::Seek)
                .map_err(|error| self.record_failure(error))?;
        }

        let source = PlaybackRangeSource::new(
            source,
            range_start,
            range_end,
            position,
            self.looping.clone(),
        );
        let source = self.process_source(source);
        self.position_offset = position;
        self.player_position_anchor = Duration::ZERO;
        self.position_is_held = true;
        self.duration = duration;

        let new_player = self.connect_voice();
        let volume = self.volume();

        new_player.set_volume(volume);
        new_player.set_speed(self.player_speed());
        if !autoplay {
            new_player.pause();
        }
        new_player.append(source);
        if autoplay {
            new_player.play();
        }

        self.voice = new_player;
        self.position_offset = position;
        self.player_position_anchor = Duration::ZERO;
        self.position_is_held = false;
        if autoplay {
            self.set_playback_state(PlaybackState::Playing);
        }

        Ok(())
    }

    fn play_current_source_at(&mut self, position: Duration) -> Result<(), SoundscapeError> {
        match self.source.clone() {
            SoundSource::Empty => Err(self.record_failure(SoundscapeError::NoAudioSource)),
            SoundSource::StaticBytes(bytes) => {
                let source = decoder::from_static_bytes(bytes)
                    .map_err(|error| self.record_failure(error))?;
                self.play_source_at(source, Some(position))
            }
            SoundSource::SharedBytes(bytes) => {
                let source = decoder::from_shared_bytes(bytes)
                    .map_err(|error| self.record_failure(error))?;
                self.play_source_at(source, Some(position))
            }
            #[cfg(not(target_arch = "wasm32"))]
            SoundSource::File(path) => {
                let source =
                    decoder::from_file(path).map_err(|error| self.record_failure(error))?;
                self.play_source_at(source, Some(position))
            }
            SoundSource::Asset(asset) => {
                #[cfg(not(target_arch = "wasm32"))]
                let source = decoder::from_file(asset.native_path())
                    .map_err(|error| self.record_failure(error))?;

                #[cfg(target_arch = "wasm32")]
                let source = decoder::from_shared_bytes(
                    asset
                        .cached_browser_bytes()
                        .ok_or_else(|| self.record_failure(SoundscapeError::NoAudioSource))?,
                )
                .map_err(|error| self.record_failure(error))?;

                self.play_source_at(source, Some(position))
            }
        }
    }

    fn playback_bounds(
        &self,
        duration: Option<Duration>,
    ) -> Result<(Duration, Option<Duration>), SoundscapeError> {
        let Some(range) = self.loop_range.as_ref() else {
            return Ok((Duration::ZERO, duration));
        };
        let end = duration.map_or(range.end, |duration| range.end.min(duration));

        if range.start >= end {
            return Err(SoundscapeError::InvalidPlaybackRange);
        }

        Ok((range.start, Some(end)))
    }

    fn process_source<S>(&self, source: S) -> Box<dyn Source<Item = f32> + Send>
    where
        S: Source + Send + 'static,
        f32: FromSample<S::Item>,
    {
        let source = self.effects.apply(source);

        if self.preserve_pitch {
            Box::new(Wsola::new(source, self.speed))
        } else {
            source
        }
    }

    fn player_speed(&self) -> f32 {
        if self.preserve_pitch { 1.0 } else { self.speed }
    }

    fn reset_loaded_source(&mut self, duration: Option<Duration>) {
        self.voice.stop();

        self.position_offset = Duration::ZERO;
        self.player_position_anchor = Duration::ZERO;
        self.position_is_held = true;
        self.duration = duration;
        self.set_playback_state(PlaybackState::Idle);
    }

    #[cfg(target_arch = "wasm32")]
    pub(crate) fn load_resolved_bytes(&mut self, bytes: Arc<[u8]>) -> Result<(), SoundscapeError> {
        let duration = decoder::from_shared_bytes(bytes)
            .map_err(|error| self.record_failure(error))?
            .total_duration();

        self.reset_loaded_source(duration);
        Ok(())
    }

    /// Plays an audio asset using its native path.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn play_file(&mut self, path: impl AsRef<Path>) -> Result<(), SoundscapeError> {
        let path = path.as_ref().to_path_buf();
        let source = decoder::from_file(&path).map_err(|error| self.record_failure(error))?;

        self.play_source(source)?;
        Ok(())
    }

    /// Starts playing an audio asset while keeping browser loading state in this instance.
    ///
    /// Native assets start synchronously. Browser assets are fetched in the background and
    /// completed by polling the owning scene.
    pub fn start_asset_playback(&mut self, asset: &SoundAsset) -> Result<(), SoundscapeError> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            self.play_file(asset.native_path())
        }

        #[cfg(target_arch = "wasm32")]
        {
            if self.pending_playback.is_some() {
                return Ok(());
            }

            if let Some(bytes) = asset.cached_browser_bytes() {
                let source = decoder::from_shared_bytes(bytes.clone())
                    .map_err(|error| self.record_failure(error))?;

                self.play_source(source)?;
                return Ok(());
            }

            let pending_playback = PendingPlayback::default();
            let pending_result = pending_playback.clone();
            let asset = asset.clone();

            wasm_bindgen_futures::spawn_local(async move {
                *pending_result.borrow_mut() = Some(asset.load_browser_bytes().await);
            });

            self.pending_playback = Some(pending_playback);
            self.set_playback_state(PlaybackState::Loading);

            Ok(())
        }
    }

    /// Completes a browser asset playback once its fetch has finished.
    ///
    /// Returns `None` while no playback is pending or the current fetch is still in progress.
    pub fn poll_pending_playback(&mut self) -> Option<Result<(), SoundscapeError>> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            None
        }

        #[cfg(target_arch = "wasm32")]
        {
            let result = self.pending_playback.as_ref()?.borrow_mut().take()?;
            self.pending_playback = None;

            let result = result.and_then(|bytes| {
                let source = decoder::from_shared_bytes(bytes.clone())?;
                self.play_source(source)?;
                Ok(())
            });

            if result.is_err() {
                self.set_playback_state(PlaybackState::Failed);
            }

            Some(result)
        }
    }

    pub(crate) fn cancel_pending_playback(&mut self) {
        #[cfg(target_arch = "wasm32")]
        {
            self.pending_playback = None;
        }
    }

    /// Returns the current playback lifecycle state.
    pub fn state(&mut self) -> PlaybackState {
        self.refresh_playback_state();
        self.playback_state
    }

    /// Returns the next pending playback lifecycle event.
    ///
    /// Natural playback completion is detected when this method or [`Self::state`] is called.
    pub fn poll_event(&mut self) -> Option<PlaybackEvent> {
        self.refresh_playback_state();
        self.playback_events.pop_front()
    }

    pub(crate) fn poll_scene_event(&mut self) -> Option<PlaybackEvent> {
        self.refresh_playback_state();
        self.scene_events.pop_front()
    }

    pub(crate) fn set_event_capacity(&mut self, capacity: usize) {
        self.event_capacity = capacity;
        while self.playback_events.len() > capacity {
            self.playback_events.pop_front();
        }
    }

    fn refresh_playback_state(&mut self) {
        let state = self.playback_state;

        if matches!(state, PlaybackState::Playing | PlaybackState::Paused) && self.voice.empty() {
            self.set_playback_state(PlaybackState::Ended);
        }
    }

    fn set_playback_state(&mut self, state: PlaybackState) {
        if self.playback_state == state {
            return;
        }

        let previous = self.playback_state;
        self.playback_state = state;

        let event = PlaybackEvent::StateChanged {
            previous,
            current: state,
        };
        self.scene_events.push_back(event);

        if self.event_capacity > 0 {
            if self.playback_events.len() >= self.event_capacity {
                self.playback_events.pop_front();
            }
            self.playback_events.push_back(event);
        }
    }

    fn record_failure(&mut self, error: SoundscapeError) -> SoundscapeError {
        self.set_playback_state(PlaybackState::Failed);
        error
    }

    /// Returns whether a browser audio asset is currently loading.
    pub fn is_loading(&mut self) -> bool {
        self.state() == PlaybackState::Loading
    }

    /// Convenience version of [`Self::try_seek`] that accepts the position in seconds.
    pub fn try_seek_secs(&mut self, position_secs: f64) -> Result<(), SoundscapeError> {
        if position_secs.is_nan() || position_secs.is_infinite() || position_secs < 0.0 {
            return Err(self.record_failure(SoundscapeError::InvalidSeekPosition));
        }

        self.try_seek(Duration::from_secs_f64(position_secs))
    }

    /// Attempts to seek to a given position in the current source.
    ///
    /// This blocks between 0 and ~5 milliseconds.
    ///
    /// As long as the duration of the source is known, seek is guaranteed to saturate
    /// at the end of the source. For example given a source that reports a total duration
    /// of 42 seconds calling `try_seek()` with 60 seconds as argument will seek to
    /// 42 seconds.
    pub fn try_seek_without_decoding(&mut self, position: Duration) -> Result<(), SoundscapeError> {
        if self.set_position_if_empty(position) {
            return Ok(());
        }

        // `Player` applies `speed` through its internal `Speed` filter (or through
        // `Wsola` when pitch is preserved). In both cases player time runs at
        // `source_time / speed`, and `Speed::try_seek`/`Wsola::try_seek` multiply
        // the requested player position by `speed` to obtain the source position.
        // Passing the source position directly therefore overshoots by `speed`,
        // which seeks past the end (and immediately ends playback) when
        // `speed > 1` and the target is near the end.
        let player_position = if self.speed.is_finite() && self.speed > 0.0 {
            position.div_f32(self.speed)
        } else {
            position
        };
        self.voice
            .try_seek(player_position)
            .map_err(SoundscapeError::Seek)
            .map_err(|error| self.record_failure(error))?;
        self.position_offset = position;
        self.player_position_anchor = player_position;
        self.position_is_held = false;

        Ok(())
    }

    /// Functionally equivalent to `try_seek_without_decoding`, but avoids the deadlock that occurs
    /// when calling [`Player::try_seek`] on the same thread as the audio callback.
    pub fn try_seek(&mut self, position: Duration) -> Result<(), SoundscapeError> {
        if self.set_position_if_empty(position) {
            return Ok(());
        }

        let position = match self.duration() {
            Some(duration) => position.min(duration),
            None => position,
        };

        match self.source.clone() {
            SoundSource::Empty => Err(SoundscapeError::NoAudioSource),
            SoundSource::StaticBytes(bytes) => {
                self.seek_with_decode_source(decoder::from_static_bytes(bytes)?, position)
            }
            SoundSource::SharedBytes(bytes) => {
                self.seek_with_decode_source(decoder::from_shared_bytes(bytes)?, position)
            }
            #[cfg(not(target_arch = "wasm32"))]
            SoundSource::File(path) => {
                self.seek_with_decode_source(decoder::from_file(path)?, position)
            }
            SoundSource::Asset(asset) => {
                #[cfg(not(target_arch = "wasm32"))]
                let source = decoder::from_file(asset.native_path())?;

                #[cfg(target_arch = "wasm32")]
                let source = decoder::from_shared_bytes(
                    asset
                        .cached_browser_bytes()
                        .ok_or(SoundscapeError::NoAudioSource)?,
                )?;

                self.seek_with_decode_source(source, position)
            }
        }
    }

    fn set_position_if_empty(&mut self, position: Duration) -> bool {
        if !self.is_empty() {
            return false;
        }

        let position = match self.duration() {
            Some(duration) => position.min(duration),
            None => position,
        };
        let volume = self.volume();
        let was_paused = self.is_paused();

        let new_player = self.connect_voice();
        new_player.set_volume(volume);
        new_player.set_speed(self.player_speed());

        if was_paused {
            new_player.pause();
        }

        self.voice = new_player;

        self.position_offset = position;
        self.player_position_anchor = Duration::ZERO;
        self.position_is_held = true;

        if self.playback_state == PlaybackState::Ended {
            self.set_playback_state(PlaybackState::Idle);
        }

        true
    }

    fn seek_with_decode_source<S>(
        &mut self,
        mut source: S,
        position: Duration,
    ) -> Result<(), SoundscapeError>
    where
        S: Source + Send + 'static,
        f32: FromSample<S::Item>,
    {
        let was_paused = self.voice.is_paused();

        // This decoder is NOT owned by the audio callback yet,
        // therefore this seek executes directly on this thread.

        let (range_start, range_end) = self
            .playback_bounds(source.total_duration())
            .map_err(|error| self.record_failure(error))?;
        let position = range_end.map_or(position.max(range_start), |end| {
            position.clamp(range_start, end)
        });
        source
            .try_seek(position)
            .map_err(SoundscapeError::Seek)
            .map_err(|error| self.record_failure(error))?;
        let source = PlaybackRangeSource::new(
            source,
            range_start,
            range_end,
            position,
            self.looping.clone(),
        );
        let source = self.process_source(source);

        let volume = self.volume();

        let new_player = self.connect_voice();

        new_player.set_volume(volume);
        new_player.set_speed(self.player_speed());

        if was_paused {
            new_player.pause();
        }

        new_player.append(source);

        if !was_paused {
            new_player.play();
        }

        // Dropping the old Player only marks its source as stopped.
        // It does not synchronously wait for WebAudio.
        self.voice = new_player;

        self.position_offset = position;
        self.player_position_anchor = Duration::ZERO;
        self.position_is_held = false;

        Ok(())
    }

    /// Returns the current rodio post-processing settings.
    pub fn effects(&self) -> SoundEffects {
        self.effects
    }

    /// Replaces the rodio post-processing chain.
    ///
    /// If a source is playing, its decoder is rebuilt at the current position and keeps its
    /// paused state. Loaded or stopped sources use the settings the next time playback starts.
    pub fn set_effects(&mut self, effects: SoundEffects) -> Result<(), SoundscapeError> {
        effects.validate()?;

        if effects == self.effects {
            return Ok(());
        }

        if self.is_empty() {
            self.effects = effects;
            return Ok(());
        }

        let position = self.position();
        let previous_effects = std::mem::replace(&mut self.effects, effects);
        let result = self.try_seek(position);

        if result.is_err() {
            self.effects = previous_effects;
        }

        result
    }

    /// Returns the position of the sound that's being played.
    ///
    /// This takes into account any speedup or delay applied.
    ///
    /// Example: if you apply a speedup of *2* to an mp3 decoder source and
    /// [`get_pos()`](Player::get_pos) returns *5s* then the position in the mp3
    /// recording is *10s* from its start.
    pub fn position(&self) -> Duration {
        let player_position = if self.position_is_held {
            Duration::ZERO
        } else {
            self.voice.get_pos()
        };

        self.position_at_player_time(player_position)
    }

    fn position_at_player_time(&self, player_position: Duration) -> Duration {
        let elapsed = player_position.saturating_sub(self.player_position_anchor);
        let mut position = self
            .position_offset
            .saturating_add(elapsed.mul_f32(self.speed));

        if self.is_looping()
            && let Ok((start, Some(end))) = self.playback_bounds(self.duration())
            && position >= end
        {
            let range_duration = end - start;
            let range_nanos = range_duration.as_nanos();

            if range_nanos > 0 {
                let position_nanos = position.saturating_sub(start).as_nanos() % range_nanos;
                position = start
                    + Duration::new(
                        (position_nanos / 1_000_000_000) as u64,
                        (position_nanos % 1_000_000_000) as u32,
                    );
            }
        }

        match self.duration() {
            Some(duration) => position.min(duration),
            None => position,
        }
    }

    /// Returns the position of the sound that's being played in the format `H:MM:SS` or `M:SS`.
    pub fn position_formatted(&self) -> String {
        format_timestamp(self.position())
    }

    /// Returns the total duration of the audio source.
    pub fn duration(&self) -> Option<Duration> {
        self.duration
    }

    /// Returns the total duration of the audio source in the format `H:MM:SS` or `M:SS`.
    ///
    /// Falls back to `0:00` if the duration is unknown.
    pub fn duration_formatted(&self) -> String {
        self.duration()
            .map(format_timestamp)
            .unwrap_or_else(|| "0:00".into())
    }

    /// [`Self::position`] clamped to the range `[0, duration]`.
    ///
    /// This is useful for user input.
    pub fn clamped_position(&self) -> Duration {
        self.position()
            .min(self.duration().unwrap_or_default())
            .max(Duration::ZERO)
    }

    /// Attempts to produce a valid range suitable for a seek slider, even if the duration is unknown.
    ///
    /// Will return `0.0..=1.0` if the duration is unknown, otherwise returns `0.0..=duration`.
    pub fn seek_range(&self) -> std::ops::RangeInclusive<f64> {
        0.0..=self.duration().unwrap_or_default().as_secs_f64().max(1.0)
    }

    /// Pauses playback of this player.
    ///
    /// No effect if already paused.
    ///
    /// A paused sink can be resumed with `play()`.
    pub fn pause(&mut self) {
        self.voice.pause();

        if self.state() == PlaybackState::Playing {
            self.set_playback_state(PlaybackState::Paused);
        }
    }

    /// Resumes playback of a paused player.
    ///
    /// No effect if not paused.
    pub fn resume(&mut self) {
        self.voice.play();

        if self.state() == PlaybackState::Paused {
            self.set_playback_state(PlaybackState::Playing);
        }
    }

    /// Stops the sink by emptying the queue and resets its position.
    pub fn stop(&mut self) {
        self.voice.stop();

        self.position_offset = Duration::ZERO;
        self.player_position_anchor = Duration::ZERO;
        self.position_is_held = true;
        self.set_playback_state(PlaybackState::Idle);
    }

    /// Seeks to `position` and starts playback.
    ///
    /// If a source is actively playing or paused, this seeks in place and resumes
    /// playing. Otherwise, if a source was loaded, stopped with
    /// stopped, or ended, this rebuilds playback from the
    /// retained source at `position`.
    ///
    /// The requested position is clamped to the known duration and the configured
    /// playback bounds (see [`Self::set_loop_range`]).
    ///
    /// Returns [`SoundscapeError::NoAudioSource`] when no source is available.
    pub fn try_play_at(&mut self, position: Duration) -> Result<(), SoundscapeError> {
        if !self.has_current_source() {
            return Err(self.record_failure(SoundscapeError::NoAudioSource));
        }

        let duration = self.duration();
        let (range_start, range_end) = self
            .playback_bounds(duration)
            .map_err(|error| self.record_failure(error))?;
        let position = range_end.map_or(position.max(range_start), |end| {
            position.clamp(range_start, end)
        });

        let playback_state = self.state();
        if playback_state == PlaybackState::Paused && position == self.position() {
            self.resume();
            return Ok(());
        }

        if playback_state == PlaybackState::Playing || playback_state == PlaybackState::Paused {
            self.try_seek(position)?;
            self.resume();
            return Ok(());
        }

        self.play_current_source_at(position)
    }

    /// Changes the volume of the sound.
    ///
    /// The value `1.0` is the "normal" volume (unfiltered input). Any value other than `1.0` will
    /// multiply each sample by this value.
    pub fn set_volume(&mut self, volume: f32) {
        self.volume = volume;

        self.voice.set_volume(volume);
    }

    /// Gets the volume of the sound.
    ///
    /// The value `1.0` is the "normal" volume (unfiltered input). Any value other than 1.0 will
    /// multiply each sample by this value.
    pub fn volume(&self) -> f32 {
        self.volume
    }

    /// Changes playback speed and reports errors from rebuilding a pitch-preserving source.
    pub fn try_set_speed(&mut self, speed: f32) -> Result<(), SoundscapeError> {
        if self.preserve_pitch && self.speed != speed && !self.is_empty() {
            let position = self.position();
            let previous_speed = std::mem::replace(&mut self.speed, speed);
            let result = self.try_seek(position);

            if result.is_err() {
                self.speed = previous_speed;
            }

            return result;
        }

        if !self.position_is_held {
            let player_position = self.voice.get_pos();
            self.position_offset = self.position_at_player_time(player_position);
            self.player_position_anchor = player_position;
        }

        self.speed = speed;

        self.voice.set_speed(self.player_speed());

        Ok(())
    }

    /// Gets the playback speed of the sound.
    pub fn speed(&self) -> f32 {
        self.speed
    }

    /// Enables or disables pitch preservation for playback speed changes.
    ///
    /// Active playback is rebuilt at its current source position so the new mode takes effect
    /// immediately while preserving whether playback is paused.
    pub fn set_preserve_pitch(&mut self, preserve_pitch: bool) -> Result<(), SoundscapeError> {
        if preserve_pitch == self.preserve_pitch {
            return Ok(());
        }

        if self.is_empty() {
            self.preserve_pitch = preserve_pitch;

            self.voice.set_speed(self.player_speed());

            return Ok(());
        }

        let position = self.position();
        self.preserve_pitch = preserve_pitch;
        let result = self.try_seek(position);

        if result.is_err() {
            self.preserve_pitch = !preserve_pitch;
        }

        result
    }

    /// Returns whether playback speed changes preserve the source pitch.
    pub fn preserves_pitch(&self) -> bool {
        self.preserve_pitch
    }

    /// Enables or disables repeating at the configured playback boundary.
    ///
    /// Without a loop range, the complete source repeats. Changes apply to active playback at
    /// its next boundary as well as to future sources.
    pub fn set_looping(&self, looping: bool) {
        self.looping.store(looping, Ordering::Relaxed);
    }

    /// Returns whether playback repeats at its configured boundary.
    pub fn is_looping(&self) -> bool {
        self.looping.load(Ordering::Relaxed)
    }

    /// Sets the source-time range used as the playback and looping boundary.
    ///
    /// The range applies to active and future playback. Its end is clamped to the source duration.
    pub fn set_loop_range(&mut self, range: Range<Duration>) -> Result<(), SoundscapeError> {
        if range.start >= range.end {
            return Err(SoundscapeError::InvalidPlaybackRange);
        }

        let state = self.state();
        let position = self.position().clamp(range.start, range.end);
        let previous_range = self.loop_range.replace(range);

        if matches!(state, PlaybackState::Playing | PlaybackState::Paused)
            && let Err(error) = self.try_seek(position)
        {
            self.loop_range = previous_range;
            return Err(error);
        }

        Ok(())
    }

    /// Returns the configured playback and looping range.
    pub fn loop_range(&self) -> Option<Range<Duration>> {
        self.loop_range.clone()
    }

    /// Removes the configured playback and looping range.
    pub fn clear_loop_range(&mut self) {
        self.loop_range = None;
    }

    /// Gets if a sink is playing
    ///
    /// Equivalent to `!is_paused() && !is_empty()`.
    ///
    /// Players can be paused and resumed using `pause()` and `play()`. This returns `true` if the
    /// sink is playing.
    pub fn is_playing(&mut self) -> bool {
        self.state() == PlaybackState::Playing
    }

    /// Gets if a sink is paused
    ///
    /// Players can be paused and resumed using `pause()` and `play()`. This returns `true` if the
    /// sink is paused.
    pub fn is_paused(&mut self) -> bool {
        self.state() == PlaybackState::Paused
    }

    /// Returns true if this sink has no more sounds to play.
    pub fn is_empty(&mut self) -> bool {
        !matches!(self.state(), PlaybackState::Playing | PlaybackState::Paused)
    }

    /// Sleeps the current thread until the sound ends.
    pub fn wait_until_end(&self) {
        self.voice.sleep_until_end();
    }
}