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
use log::debug;
use rodio::{OutputStream, OutputStreamHandle, Sink, Source};
use std::collections::VecDeque;
use std::fmt::Debug;
use std::io::Cursor;
use std::sync::RwLock;
use zengine_asset::Asset;
use zengine_asset::{AssetExtension, AssetLoader, Assets, Handle, HandleId};
use zengine_ecs::system::{Local, Res, ResMut, UnsendableRes};
use zengine_engine::{Module, Stage};
use zengine_macro::{Asset, Resource, UnsendableResource};

/// Adds audio support to the engine
///
/// Use the [`AudioDevice`] resource to play audio.
#[derive(Default)]
pub struct AudioModule;

impl Module for AudioModule {
    fn init(self, engine: &mut zengine_engine::Engine) {
        engine
            .add_asset::<Audio>()
            .add_asset::<AudioInstance>()
            .add_asset_loader(AudioLoader)
            .add_system_into_stage(audio_system, Stage::PostUpdate)
            .add_system_into_stage(update_instances, Stage::PostRender);

        #[cfg(target_os = "android")]
        engine.add_system_into_stage(handle_resume_suspended, StageLabel::PreUpdate);
    }
}

#[derive(Debug)]
struct AudioLoader;
impl AssetLoader for AudioLoader {
    fn extension(&self) -> &[&str] {
        &["ogg", "wav", "flac"]
    }

    fn load(&self, data: Vec<u8>, context: &mut zengine_asset::LoaderContext) {
        context.set_asset(Audio { data });
    }
}

/// Initial audio playback settings
#[derive(Debug)]
pub struct AudioSettings {
    /// Volume to play at
    pub volume: f32,
    /// Speed to play at
    pub speed: f32,
    /// Play in loop
    pub in_loop: bool,
}

impl Default for AudioSettings {
    fn default() -> Self {
        Self {
            volume: 1.0,
            speed: 1.0,
            in_loop: false,
        }
    }
}

impl AudioSettings {
    /// Set the speed initial of playback
    pub fn with_speed(mut self, speed: f32) -> Self {
        self.speed = speed;
        self
    }

    /// Set the volume initial of playback
    pub fn with_volume(mut self, volume: f32) -> Self {
        self.volume = volume;
        self
    }

    /// Will play the associated audio in loop
    pub fn in_loop(mut self) -> Self {
        self.in_loop = true;
        self
    }
}

/// An asset that rappresents an audio source
///
/// It could be a song or an audio effect
#[derive(Asset, Debug)]
pub struct Audio {
    data: Vec<u8>,
}

/// An asset that represents an instance of an [Audio] queued for playback
#[derive(Asset)]
pub struct AudioInstance(Option<Sink>);
impl Debug for AudioInstance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AudioInstance")
    }
}

impl AudioInstance {
    /// Get the current audio instance volume
    ///
    /// The value 1.0 is the “normal” volume. Any value other than 1.0
    /// will change the volume of the sound
    pub fn volume(&self) -> f32 {
        self.0.as_ref().unwrap().volume()
    }

    /// Set the audio instance volume
    ///
    /// The value 1.0 is the “normal” volume. Any value other than 1.0
    /// will change the volume of the sound
    pub fn set_volume(&self, volume: f32) {
        self.0.as_ref().unwrap().set_volume(volume);
    }

    /// Get the current audio instance speed
    ///
    /// The value 1.0 is the “normal” speed. Any value other than 1.0
    /// will change the speed of the sound
    pub fn speed(&self) -> f32 {
        self.0.as_ref().unwrap().speed()
    }

    /// Set the audio instance speed
    ///
    /// The value 1.0 is the “normal” speed. Any value other than 1.0
    /// will change the speed of the sound
    pub fn set_speed(&self, speed: f32) {
        self.0.as_ref().unwrap().set_speed(speed);
    }

    /// Play the audio instance
    pub fn play(&self) {
        self.0.as_ref().unwrap().play();
    }

    /// Pause the audio isntance
    pub fn pause(&self) {
        self.0.as_ref().unwrap().pause();
    }

    /// Returns true if the audio instance is paused
    pub fn is_paused(&self) -> bool {
        self.0.as_ref().unwrap().is_paused()
    }

    /// Returns true if the audio instance is stopped
    pub fn stop(&self) {
        self.0.as_ref().unwrap().stop();
    }

    /// Returns true if the audio instance has finished
    pub fn is_empty(&self) -> bool {
        self.0.as_ref().unwrap().empty()
    }
}

/// A [Resource](zengine_ecs::Resource) that rappresent an audio device
///
/// Use this resource to play audio
///
/// # Example
/// ```
/// use zengine_asset::AssetManager;
/// use zengine_ecs::system::{Res, ResMut};
/// use zengine_audio::AudioDevice;
///
/// fn play_audio_system(mut asset_manager: ResMut<AssetManager>, audio_device: Res<AudioDevice>) {
///     audio_device.play(asset_manager.load("test_sound.ogg"));
/// }
/// ```
#[derive(Resource, Default, Debug)]
pub struct AudioDevice {
    queue: RwLock<VecDeque<(HandleId, Handle<Audio>, AudioSettings)>>,
    instances: Vec<Handle<AudioInstance>>,
    suspended: Vec<Handle<AudioInstance>>,
}

impl AudioDevice {
    /// Play a sound from an [Handle] to an [Audio] asset
    ///
    /// Returns a weak handle to an [AudioInstance].
    /// Changing it to a strong handle allows to control
    /// the playback through the [AudioInstance] asset.
    ///
    /// NB: the AudioDevice maintains a strong reference
    /// to each AudioInstance that [is not empty](AudioInstance::is_empty).
    /// The strong reference are dropped when the AudioInstance is empty
    pub fn play(&self, audio: Handle<Audio>) -> Handle<AudioInstance> {
        self.play_with_settings(audio, AudioSettings::default())
    }

    /// Play a sound from an [Handle] to an [Audio] asset with an
    /// [AudioSettings]
    pub fn play_with_settings(
        &self,
        audio: Handle<Audio>,
        settings: AudioSettings,
    ) -> Handle<AudioInstance> {
        let next_id = AudioInstance::next_counter();
        let handle_id = HandleId::new_from_u64::<AudioInstance>(next_id);

        debug!("created an Audio Instance handle {:?}", handle_id);

        self.queue
            .write()
            .unwrap()
            .push_back((handle_id, audio, settings));

        Handle::weak(handle_id)
    }

    /// Suspend the audio device pausing every [AudioInstance] that is currently playing
    pub fn suspend(&mut self, audio_instances: &Assets<AudioInstance>) {
        for i in self.instances.iter() {
            let instance = audio_instances.get(i).unwrap();
            if !instance.is_paused() {
                instance.pause();
                self.suspended.push(i.clone_as_weak());
            }
        }
    }

    /// Resume the audio device starting every [AudioInstance] that were playing before the suspend
    pub fn resume(&mut self, audio_instances: &Assets<AudioInstance>) {
        for i in self.suspended.drain(..) {
            let instance = audio_instances.get(&i).unwrap();
            instance.play();
        }
    }
}

/// Used internally to play audio on the platform
#[derive(UnsendableResource)]
pub struct AudioOutput {
    _stream: OutputStream,
    stream_handle: OutputStreamHandle,
}

impl Debug for AudioOutput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AudioManager")
    }
}

impl Default for AudioOutput {
    fn default() -> Self {
        let stream_handle = OutputStream::try_default().expect("Audio device not found");
        Self {
            _stream: stream_handle.0,
            stream_handle: stream_handle.1,
        }
    }
}

fn audio_system(
    audio_output: UnsendableRes<AudioOutput>,
    mut audio_device: ResMut<AudioDevice>,
    audio: Option<Res<Assets<Audio>>>,
    audio_instances: Option<ResMut<Assets<AudioInstance>>>,
    to_add: Local<Vec<Handle<AudioInstance>>>,
) {
    if let (Some(audio), Some(mut audio_instances)) = (audio, audio_instances) {
        {
            let mut queue = audio_device.queue.write().unwrap();
            let len = queue.len();
            let mut i = 0;

            while i < len {
                let (instance_id, audio_handle, settings) = queue.pop_front().unwrap();
                if let Some(audio) = audio.get(&audio_handle) {
                    let sink = Sink::try_new(&audio_output.stream_handle).unwrap();

                    if settings.in_loop {
                        sink.append(
                            rodio::Decoder::new(Cursor::new(audio.data.clone()))
                                .unwrap()
                                .repeat_infinite(),
                        );
                    } else {
                        sink.append(rodio::Decoder::new(Cursor::new(audio.data.clone())).unwrap())
                    };

                    sink.set_speed(settings.speed);
                    sink.set_volume(settings.volume);

                    let audio_instance = AudioInstance(Some(sink));
                    let handle = audio_instances.set(Handle::weak(instance_id), audio_instance);
                    to_add.push(handle);
                } else {
                    queue.push_back((instance_id, audio_handle, settings));
                }
                i += 1;
            }
        }

        for i in to_add.drain(..) {
            audio_device.instances.push(i);
        }
    }
}

#[cfg(target_os = "android")]
fn handle_resume_suspended(
    engine_event: zengine_ecs::system::EventStream<zengine_engine::EngineEvent>,
    mut audio_device: zengine_ecs::system::ResMut<AudioDevice>,
    audio_instances: OptionalRes<Assets<AudioInstance>>,
) {
    let last_event = engine_event.read().last();
    if last_event == Some(&zengine_engine::EngineEvent::Suspended) {
        if let Some(audio_instances) = audio_instances.as_ref() {
            audio_device.suspend(audio_instances);
        }
    }

    if last_event == Some(&zengine_engine::EngineEvent::Resumed) {
        if let Some(audio_instances) = audio_instances.as_ref() {
            audio_device.resume(audio_instances);
        }
    }
}

fn update_instances(
    mut audio_device: ResMut<AudioDevice>,
    audio_instances: Option<Res<Assets<AudioInstance>>>,
    to_remove: Local<Vec<usize>>,
) {
    if let Some(audio_instances) = audio_instances.as_ref() {
        for (index, handle) in audio_device.instances.iter().enumerate() {
            let instance = audio_instances.get(handle).unwrap();
            if instance.is_empty() {
                to_remove.push(index);
            }
        }

        for i in to_remove.drain(..).rev() {
            audio_device.instances.swap_remove(i);
        }
    }
}