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
//! Contains code related to audio. [`RaylibAudio`] plays sounds and music.

use crate::core::RaylibThread;
use crate::ffi;
use std::ffi::CString;
use std::mem::ManuallyDrop;

make_thin_wrapper!(Wave, ffi::Wave, ffi::UnloadWave);
make_thin_wrapper!(Sound, ffi::Sound, ffi::UnloadSound);
make_thin_wrapper!(Music, ffi::Music, ffi::UnloadMusicStream);
make_thin_wrapper!(AudioStream, ffi::AudioStream, ffi::CloseAudioStream);

make_rslice!(WaveSamples, f32, ffi::UnloadWaveSamples);

/// A marker trait specifying an audio sample (`u8`, `i16`, or `f32`).
pub trait AudioSample {}
impl AudioSample for u8 {}
impl AudioSample for i16 {}
impl AudioSample for f32 {}

/// This token is used to indicate VR is initialized
#[derive(Debug)]
pub struct RaylibAudio(());

impl RaylibAudio {
    /// Initializes audio device and context.
    #[inline]
    pub fn init_audio_device() -> RaylibAudio {
        unsafe {
            ffi::InitAudioDevice();
        }
        RaylibAudio(())
    }

    /// Checks if audio device is ready.
    #[inline]
    pub fn is_audio_device_ready(&self) -> bool {
        unsafe { ffi::IsAudioDeviceReady() }
    }

    /// Sets master volume (listener).
    #[inline]
    pub fn set_master_volume(&self, volume: f32) {
        unsafe {
            ffi::SetMasterVolume(volume);
        }
    }

    /// Get number of sounds playing in the multichannel
    #[inline]
    pub fn get_sounds_playing(&self) -> i32 {
        unsafe { ffi::GetSoundsPlaying() }
    }

    /// Plays a sound.
    #[inline]
    pub fn play_sound(&mut self, sound: &Sound) {
        unsafe {
            ffi::PlaySound(sound.0);
        }
    }

    /// Play a sound (using multichannel buffer pool)
    #[inline]
    pub fn play_sound_multi(&mut self, sound: &Sound) {
        unsafe {
            ffi::PlaySoundMulti(sound.0);
        }
    }

    /// Pauses a sound.
    #[inline]
    pub fn pause_sound(&mut self, sound: &Sound) {
        unsafe {
            ffi::PauseSound(sound.0);
        }
    }

    /// Resumes a paused sound.
    #[inline]
    pub fn resume_sound(&mut self, sound: &Sound) {
        unsafe {
            ffi::ResumeSound(sound.0);
        }
    }

    /// Stops playing a sound.
    #[inline]
    pub fn stop_sound(&mut self, sound: &Sound) {
        unsafe {
            ffi::StopSound(sound.0);
        }
    }

    /// Stops playing a sound.
    #[inline]
    pub fn stop_sound_multi(&mut self) {
        unsafe {
            ffi::StopSoundMulti();
        }
    }

    /// Checks if a sound is currently playing.
    #[inline]
    pub fn is_sound_playing(&self, sound: &Sound) -> bool {
        unsafe { ffi::IsSoundPlaying(sound.0) }
    }

    /// Sets volume for a sound (`1.0` is max level).
    #[inline]
    pub fn set_sound_volume(&mut self, sound: &Sound, volume: f32) {
        unsafe {
            ffi::SetSoundVolume(sound.0, volume);
        }
    }

    /// Sets pitch for a sound (`1.0` is base level).
    #[inline]
    pub fn set_sound_pitch(&mut self, sound: &Sound, pitch: f32) {
        unsafe {
            ffi::SetSoundPitch(sound.0, pitch);
        }
    }

    /// Starts music playing.
    #[inline]
    pub fn play_music_stream(&mut self, music: &mut Music) {
        unsafe {
            ffi::PlayMusicStream(music.0);
        }
    }

    /// Updates buffers for music streaming.
    #[inline]
    pub fn update_music_stream(&mut self, music: &mut Music) {
        unsafe {
            ffi::UpdateMusicStream(music.0);
        }
    }

    /// Stops music playing.
    #[inline]
    pub fn stop_music_stream(&mut self, music: &mut Music) {
        unsafe {
            ffi::StopMusicStream(music.0);
        }
    }

    /// Pauses music playing.
    #[inline]
    pub fn pause_music_stream(&mut self, music: &mut Music) {
        unsafe {
            ffi::PauseMusicStream(music.0);
        }
    }

    /// Resumes playing paused music.
    #[inline]
    pub fn resume_music_stream(&mut self, music: &mut Music) {
        unsafe {
            ffi::ResumeMusicStream(music.0);
        }
    }

    /// Checks if music is playing.
    #[inline]
    pub fn is_music_playing(&self, music: &Music) -> bool {
        unsafe { ffi::IsMusicPlaying(music.0) }
    }

    /// Sets volume for music (`1.0` is max level).
    #[inline]
    pub fn set_music_volume(&mut self, music: &mut Music, volume: f32) {
        unsafe {
            ffi::SetMusicVolume(music.0, volume);
        }
    }

    /// Sets pitch for music (`1.0` is base level).
    #[inline]
    pub fn set_music_pitch(&mut self, music: &mut Music, pitch: f32) {
        unsafe {
            ffi::SetMusicPitch(music.0, pitch);
        }
    }

    /// Gets music time length in seconds.
    #[inline]
    pub fn get_music_time_length(&self, music: &Music) -> f32 {
        unsafe { ffi::GetMusicTimeLength(music.0) }
    }

    /// Gets current music time played in seconds.
    #[inline]
    pub fn get_music_time_played(&self, music: &Music) -> f32 {
        unsafe { ffi::GetMusicTimePlayed(music.0) }
    }

    /// Plays audio stream.
    #[inline]
    pub fn play_audio_stream(&mut self, stream: &mut AudioStream) {
        unsafe {
            ffi::PlayAudioStream(stream.0);
        }
    }

    /// Pauses audio stream.
    #[inline]
    pub fn pause_audio_stream(&mut self, stream: &mut AudioStream) {
        unsafe {
            ffi::PauseAudioStream(stream.0);
        }
    }

    /// Resumes audio stream.
    #[inline]
    pub fn resume_audio_stream(&mut self, stream: &mut AudioStream) {
        unsafe {
            ffi::ResumeAudioStream(stream.0);
        }
    }

    /// Checks if audio stream is currently playing.
    #[inline]
    pub fn is_audio_stream_playing(&self, stream: &AudioStream) -> bool {
        unsafe { ffi::IsAudioStreamPlaying(stream.0) }
    }

    /// Stops audio stream.
    #[inline]
    pub fn stop_audio_stream(&mut self, stream: &mut AudioStream) {
        unsafe {
            ffi::StopAudioStream(stream.0);
        }
    }

    /// Sets volume for audio stream (`1.0` is max level).
    #[inline]
    pub fn set_audio_stream_volume(&mut self, stream: &mut AudioStream, volume: f32) {
        unsafe {
            ffi::SetAudioStreamVolume(stream.0, volume);
        }
    }

    /// Sets pitch for audio stream (`1.0` is base level).
    #[inline]
    pub fn set_audio_stream_pitch(&mut self, stream: &mut AudioStream, pitch: f32) {
        unsafe {
            ffi::SetAudioStreamPitch(stream.0, pitch);
        }
    }

    /// Sets pitch for audio stream (`1.0` is base level).
    #[inline]
    pub fn is_audio_stream_processed(&mut self, stream: &AudioStream) -> bool {
        unsafe { ffi::IsAudioStreamProcessed(stream.0) }
    }
}

impl Drop for RaylibAudio {
    fn drop(&mut self) {
        unsafe {
            ffi::StopSoundMulti();
            ffi::CloseAudioDevice();
        }
    }
}

impl Wave {
    pub fn sample_count(&self) -> u32 {
        self.0.sampleCount
    }
    pub fn smaple_rate(&self) -> u32 {
        self.0.sampleRate
    }
    pub fn sample_size(&self) -> u32 {
        self.0.sampleSize
    }
    pub fn channels(&self) -> u32 {
        self.0.channels
    }
    pub unsafe fn inner(self) -> ffi::Wave {
        let inner = self.0;
        std::mem::forget(self);
        inner
    }
    /// Loads wave data from file into RAM.
    #[inline]
    pub fn load_wave(filename: &str) -> Result<Wave, String> {
        let c_filename = CString::new(filename).unwrap();
        let w = unsafe { ffi::LoadWave(c_filename.as_ptr()) };
        if w.data.is_null() {
            return Err(format!("Cannot load wave {}", filename));
        }
        Ok(Wave(w))
    }

    /// Export wave file. Extension must be .wav or .raw
    #[inline]
    pub fn export_wave(&self, filename: &str) -> bool {
        let c_filename = CString::new(filename).unwrap();
        unsafe { ffi::ExportWave(self.0, c_filename.as_ptr()) }
    }

    /// Export wave sample data to code (.h)
    #[inline]
    pub fn export_wave_as_code(&self, filename: &str) -> bool {
        let c_filename = CString::new(filename).unwrap();
        unsafe { ffi::ExportWaveAsCode(self.0, c_filename.as_ptr()) }
    }

    /// Converts wave data to desired format.
    #[inline]
    pub fn wave_format(&mut self, sample_rate: i32, sample_size: i32, channels: i32) {
        unsafe {
            ffi::WaveFormat(&mut self.0, sample_rate, sample_size, channels);
        }
    }

    /// Copies a wave to a new wave.
    #[inline]
    pub fn wave_copy(&self) -> Wave {
        unsafe { Wave(ffi::WaveCopy(self.0)) }
    }

    /// Crops a wave to defined sample range.
    #[inline]
    pub fn wave_crop(&mut self, init_sample: i32, final_sample: i32) {
        unsafe {
            ffi::WaveCrop(&mut self.0, init_sample, final_sample);
        }
    }

    /// Load samples data from wave as a floats array
    /// NOTE 1: Returned sample values are normalized to range [-1..1]
    /// NOTE 2: Sample data allocated should be freed with UnloadWaveSamples()
    #[inline]
    pub fn load_wave_samples(&self) -> WaveSamples {
        let as_slice = unsafe {
            let data = ffi::LoadWaveSamples(self.0);
            Box::from_raw(std::slice::from_raw_parts_mut(
                data,
                self.sample_count() as usize,
            ))
        };
        WaveSamples(ManuallyDrop::new(as_slice))
    }
}

impl AsRef<ffi::AudioStream> for Sound {
    fn as_ref(&self) -> &ffi::AudioStream {
        &self.0.stream
    }
}

impl AsMut<ffi::AudioStream> for Sound {
    fn as_mut(&mut self) -> &mut ffi::AudioStream {
        &mut self.0.stream
    }
}

impl Sound {
    pub fn sample_count(&self) -> u32 {
        self.0.sampleCount
    }
    pub unsafe fn inner(self) -> ffi::Sound {
        let inner = self.0;
        std::mem::forget(self);
        inner
    }
    /// Loads sound from file.
    pub fn load_sound(filename: &str) -> Result<Sound, String> {
        let c_filename = CString::new(filename).unwrap();
        let s = unsafe { ffi::LoadSound(c_filename.as_ptr()) };
        if s.stream.buffer.is_null() {
            return Err(format!("failed to load sound {}", filename));
        }
        Ok(Sound(s))
    }

    /// Loads sound from wave data.
    pub fn load_sound_from_wave(wave: &Wave) -> Result<Sound, String> {
        let s = unsafe { ffi::LoadSoundFromWave(wave.0) };
        if s.stream.buffer.is_null() {
            return Err(format!("failed to load sound from wave"));
        }
        Ok(Sound(s))
    }

    // Figure out how to make this safe
    // /// Updates sound buffer with new data.
    // #[inline]
    // pub fn update_sound(&mut self, data: &[impl AudioSample]) {
    //     unsafe {
    //         ffi::UpdateSound(
    //             self.0,
    //             data.as_ptr() as *const std::os::raw::c_void,
    //             data.len() as i32,
    //         );
    //     }
    // }
}

impl Music {
    /// Loads music stream from file.
    // #[inline]
    pub fn load_music_stream(_: &RaylibThread, filename: &str) -> Result<Music, String> {
        let c_filename = CString::new(filename).unwrap();
        let m = unsafe { ffi::LoadMusicStream(c_filename.as_ptr()) };
        if m.stream.buffer.is_null() {
            return Err(format!("music could not be loaded from file {}", filename));
        }
        Ok(Music(m))
    }
}

impl AudioStream {
    pub fn sample_rate(&self) -> u32 {
        self.0.sampleRate
    }
    pub fn sample_size(&self) -> u32 {
        self.0.sampleSize
    }
    pub fn channels(&self) -> u32 {
        self.0.channels
    }

    pub unsafe fn inner(self) -> ffi::AudioStream {
        let inner = self.0;
        std::mem::forget(self);
        inner
    }
    /// Initializes audio stream (to stream raw PCM data).
    #[inline]
    pub fn init_audio_stream(
        _: &RaylibThread,
        sample_rate: u32,
        sample_size: u32,
        channels: u32,
    ) -> AudioStream {
        unsafe { AudioStream(ffi::InitAudioStream(sample_rate, sample_size, channels)) }
    }

    /// Updates audio stream buffers with data.
    #[inline]
    pub fn update_audio_stream<T: AudioSample>(&mut self, data: &[T]) {
        unsafe {
            ffi::UpdateAudioStream(
                self.0,
                data.as_ptr() as *const std::os::raw::c_void,
                (data.len() * std::mem::size_of::<T>()) as i32,
            );
        }
    }
}