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
//! Handles caching and retrieval of decoded `.ogg` sfx sound data, eliminating
//! the need to decode files on each playback
use common::assets::{self, AssetExt, Loader};
use rodio::{source::Buffered, Decoder, Source};
use std::{borrow::Cow, io};
use tracing::warn;

// Implementation of sound taken from this github issue:
// https://github.com/RustAudio/rodio/issues/141

struct SoundLoader;
#[derive(Clone)]
struct OggSound(Buffered<Decoder<io::Cursor<Vec<u8>>>>);

impl Loader<OggSound> for SoundLoader {
    fn load(content: Cow<[u8]>, _: &str) -> Result<OggSound, assets::BoxedError> {
        let source = Decoder::new_vorbis(io::Cursor::new(content.into_owned()))?.buffered();
        Ok(OggSound(source))
    }
}

impl assets::Asset for OggSound {
    type Loader = SoundLoader;

    const EXTENSION: &'static str = "ogg";
}

/// Wrapper for decoded audio data
impl OggSound {
    pub fn empty() -> OggSound {
        SoundLoader::load(
            Cow::Borrowed(include_bytes!("../../../assets/voxygen/audio/null.ogg")),
            "ogg",
        )
        .unwrap()
    }
}

#[allow(clippy::implied_bounds_in_impls)]
pub fn load_ogg(specifier: &str) -> impl Source + Iterator<Item = i16> {
    OggSound::load_or_insert_with(specifier, |error| {
        warn!(?specifier, ?error, "Failed to load sound");
        OggSound::empty()
    })
    .cloned()
    .0
}