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
use std::{ffi::{CString, CStr}, time::Duration};

use crate::ffi;

/// Audio file format
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioFormat {
    /// Wave
    Wav,
    /// OGG
    Ogg,
    /// MP3
    Mp3,
    /// QOA
    Qoa,
    /// FLAC
    Flac,
}

impl AudioFormat {
    fn as_cstr(&self) -> &'static CStr {
        use AudioFormat::*;

        CStr::from_bytes_with_nul(match self {
            Wav => b".wav\0",
            Ogg => b".ogg\0",
            Mp3 => b".mp3\0",
            Qoa => b".qoa\0",
            Flac => b".flac\0",
        }).unwrap()
    }
}

/// An object that handles audio playback
#[derive(Debug)]
pub struct AudioDevice(());

impl AudioDevice {
    /// Initialize audio device and context
    #[inline]
    pub fn init() -> Option<Self> {
        unsafe {
            ffi::InitAudioDevice();
        }

        if unsafe { ffi::IsAudioDeviceReady() } {
            Some(Self(()))
        } else {
            None
        }
    }

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

impl Drop for AudioDevice {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::CloseAudioDevice() }
    }
}

/// Wave, audio wave data
#[derive(Debug)]
#[repr(transparent)]
pub struct Wave {
    raw: ffi::Wave,
}

impl Wave {
    /// Total number of frames (considering channels)
    #[inline]
    pub fn frame_count(&self) -> u32 {
        self.raw.frameCount
    }

    /// Frequency (samples per second)
    #[inline]
    pub fn sample_rate(&self) -> u32 {
        self.raw.sampleRate
    }

    /// Bit depth (bits per sample): 8, 16, 32 (24 not supported)
    #[inline]
    pub fn sample_size(&self) -> u32 {
        self.raw.sampleSize
    }

    /// Number of channels (1-mono, 2-stereo, ...)
    #[inline]
    pub fn channels(&self) -> u32 {
        self.raw.channels
    }

    /// Load wave data from file
    #[inline]
    pub fn from_file(file_name: &str) -> Option<Self> {
        let file_name = CString::new(file_name).unwrap();

        let raw = unsafe { ffi::LoadWave(file_name.as_ptr()) };

        if unsafe { ffi::IsWaveReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }

    /// Load wave from memory buffer
    #[inline]
    pub fn from_memory(file_data: &[u8], format: AudioFormat) -> Option<Self> {
        let raw = unsafe {
            ffi::LoadWaveFromMemory(format.as_cstr().as_ptr(), file_data.as_ptr(), file_data.len() as _)
        };

        if unsafe { ffi::IsWaveReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }

    /// Export wave data to file, returns true on success
    #[inline]
    pub fn export(&self, file_name: &str) -> bool {
        let file_name = CString::new(file_name).unwrap();

        unsafe { ffi::ExportWave(self.raw.clone(), file_name.as_ptr()) }
    }

    /// Export wave sample data to code (.h), returns true on success
    #[inline]
    pub fn export_as_code(&self, file_name: &str) -> bool {
        let file_name = CString::new(file_name).unwrap();

        unsafe { ffi::ExportWaveAsCode(self.raw.clone(), file_name.as_ptr()) }
    }

    /// Crop a wave to defined samples range
    #[inline]
    pub fn crop(&mut self, init_sample: u32, final_sample: u32) {
        unsafe { ffi::WaveCrop(&mut self.raw as *mut _, init_sample as _, final_sample as _) }
    }

    /// Convert wave data to desired format
    #[inline]
    pub fn convert_to_format(&mut self, sample_rate: u32, sample_size: u32, channels: u32) {
        unsafe {
            ffi::WaveFormat(
                &mut self.raw as *mut _,
                sample_rate as _,
                sample_size as _,
                channels as _,
            )
        }
    }

    /// Load samples data from wave as a 32bit float data array
    #[inline]
    pub fn load_samples(&self) -> Vec<f32> {
        let samples = unsafe { ffi::LoadWaveSamples(self.raw.clone()) };

        let mut vec = Vec::new();
        let len = (self.frame_count() * self.channels()) as usize;

        for i in 0..len {
            vec.push(unsafe { samples.add(i).read() });
        }

        unsafe {
            ffi::UnloadWaveSamples(samples);
        }

        vec
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw(&self) -> &ffi::Wave {
        &self.raw
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw_mut(&mut self) -> &mut ffi::Wave {
        &mut self.raw
    }

    /// Convert a 'raw' ffi object to a safe wrapper
    ///
    /// # Safety
    /// * The raw object must be correctly initialized
    /// * The raw object should be unique. Otherwise, make sure its clones don't outlive the newly created object.
    #[inline]
    pub unsafe fn from_raw(raw: ffi::Wave) -> Self {
        Self { raw }
    }
}

impl Clone for Wave {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            raw: unsafe { ffi::WaveCopy(self.raw.clone()) },
        }
    }
}

impl Drop for Wave {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::UnloadWave(self.raw.clone()) }
    }
}

/// AudioStream, custom audio stream
#[derive(Debug)]
#[repr(transparent)]
pub struct AudioStream {
    raw: ffi::AudioStream,
}

impl AudioStream {
    /// Frequency (samples per second)
    #[inline]
    pub fn sample_rate(&self) -> u32 {
        self.raw.sampleRate
    }

    /// Bit depth (bits per sample): 8, 16, 32 (24 not supported)
    #[inline]
    pub fn sample_size(&self) -> u32 {
        self.raw.sampleSize
    }

    /// Number of channels (1-mono, 2-stereo, ...)
    #[inline]
    pub fn channels(&self) -> u32 {
        self.raw.channels
    }

    /// Load audio stream (to stream raw audio pcm data)
    #[inline]
    pub fn new(sample_rate: u32, sample_size: u32, channels: u32) -> Option<Self> {
        let raw = unsafe { ffi::LoadAudioStream(sample_rate, sample_size, channels) };

        if unsafe { ffi::IsAudioStreamReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }

    /// Update audio stream buffers with data
    #[inline]
    pub fn update(&mut self, data: &[u8], frame_count: u32) {
        unsafe {
            ffi::UpdateAudioStream(
                self.raw.clone(),
                data.as_ptr() as *const _,
                frame_count as _,
            )
        }
    }

    /// Check if any audio stream buffers requires refill
    #[inline]
    pub fn is_processed(&self) -> bool {
        unsafe { ffi::IsAudioStreamProcessed(self.raw.clone()) }
    }

    /// Play audio stream
    #[inline]
    pub fn play(&self, _device: &mut AudioDevice) {
        unsafe { ffi::PlayAudioStream(self.raw.clone()) }
    }

    /// Pause audio stream
    #[inline]
    pub fn pause(&self, _device: &mut AudioDevice) {
        unsafe { ffi::PauseAudioStream(self.raw.clone()) }
    }

    /// Resume audio stream
    #[inline]
    pub fn resume(&self, _device: &mut AudioDevice) {
        unsafe { ffi::ResumeAudioStream(self.raw.clone()) }
    }

    /// Check if audio stream is playing
    #[inline]
    pub fn is_playing(&self, _device: &mut AudioDevice) -> bool {
        unsafe { ffi::IsAudioStreamPlaying(self.raw.clone()) }
    }

    /// Stop audio stream
    #[inline]
    pub fn stop(&self, _device: &mut AudioDevice) {
        unsafe { ffi::StopAudioStream(self.raw.clone()) }
    }

    /// Set volume for audio stream (1.0 is max level)
    #[inline]
    pub fn set_volume(&self, volume: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetAudioStreamVolume(self.raw.clone(), volume) }
    }

    /// Set pitch for audio stream (1.0 is base level)
    #[inline]
    pub fn set_pitch(&self, pitch: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetAudioStreamPitch(self.raw.clone(), pitch) }
    }

    /// Set pan for audio stream (0.5 is centered)
    #[inline]
    pub fn set_pan(&self, pan: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetAudioStreamPan(self.raw.clone(), pan) }
    }

    /// Default size for new audio streams
    #[inline]
    pub fn set_default_buffer_size(size: usize) {
        unsafe { ffi::SetAudioStreamBufferSizeDefault(size as _) }
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw(&self) -> &ffi::AudioStream {
        &self.raw
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw_mut(&mut self) -> &mut ffi::AudioStream {
        &mut self.raw
    }

    /// Convert a 'raw' ffi object to a safe wrapper
    ///
    /// # Safety
    /// * The raw object must be correctly initialized
    /// * The raw object should be unique. Otherwise, make sure its clones don't outlive the newly created object.
    #[inline]
    pub unsafe fn from_raw(raw: ffi::AudioStream) -> Self {
        Self { raw }
    }
}

impl Drop for AudioStream {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::UnloadAudioStream(self.raw.clone()) }
    }
}

/// Sound
#[derive(Debug)]
#[repr(transparent)]
pub struct Sound {
    raw: ffi::Sound,
}

impl Sound {
    /// Total number of frames (considering channels)
    #[inline]
    pub fn frame_count(&self) -> u32 {
        self.raw.frameCount
    }

    /// Load sound from file
    #[inline]
    pub fn from_file(filname: &str) -> Option<Self> {
        let file_name = CString::new(filname).unwrap();

        let raw = unsafe { ffi::LoadSound(file_name.as_ptr()) };

        if unsafe { ffi::IsSoundReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }

    /// Load sound from wave data
    #[inline]
    pub fn from_wave(wave: &Wave) -> Option<Self> {
        let raw = unsafe { ffi::LoadSoundFromWave(wave.raw.clone()) };

        if unsafe { ffi::IsSoundReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }

    /// Update sound buffer with new data
    #[inline]
    pub fn update(&mut self, data: &[u8], sample_count: u32) {
        unsafe {
            ffi::UpdateSound(
                self.raw.clone(),
                data.as_ptr() as *const _,
                sample_count as _,
            )
        }
    }

    /// Play a sound
    #[inline]
    pub fn play(&self, _device: &mut AudioDevice) {
        unsafe { ffi::PlaySound(self.raw.clone()) }
    }

    /// Stop playing a sound
    #[inline]
    pub fn stop(&self, _device: &mut AudioDevice) {
        unsafe { ffi::StopSound(self.raw.clone()) }
    }

    /// Pause a sound
    #[inline]
    pub fn pause(&self, _device: &mut AudioDevice) {
        unsafe { ffi::PauseSound(self.raw.clone()) }
    }

    /// Resume a paused sound
    #[inline]
    pub fn resume(&self, _device: &mut AudioDevice) {
        unsafe { ffi::ResumeSound(self.raw.clone()) }
    }

    /// Check if a sound is currently playing
    #[inline]
    pub fn is_playing(&self, _device: &mut AudioDevice) -> bool {
        unsafe { ffi::IsSoundPlaying(self.raw.clone()) }
    }

    /// Set volume for a sound (1.0 is max level)
    #[inline]
    pub fn set_volume(&self, volume: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetSoundVolume(self.raw.clone(), volume) }
    }

    /// Set pitch for a sound (1.0 is base level)
    #[inline]
    pub fn set_pitch(&self, pitch: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetSoundPitch(self.raw.clone(), pitch) }
    }

    /// Set pan for a sound (0.5 is center)
    #[inline]
    pub fn set_pan(&self, pan: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetSoundPan(self.raw.clone(), pan) }
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw(&self) -> &ffi::Sound {
        &self.raw
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw_mut(&mut self) -> &mut ffi::Sound {
        &mut self.raw
    }

    /// Convert a 'raw' ffi object to a safe wrapper
    ///
    /// # Safety
    /// * The raw object must be correctly initialized
    /// * The raw object should be unique. Otherwise, make sure its clones don't outlive the newly created object.
    #[inline]
    pub unsafe fn from_raw(raw: ffi::Sound) -> Self {
        Self { raw }
    }
}

impl Drop for Sound {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::UnloadSound(self.raw.clone()) }
    }
}

/// Music, audio stream, anything longer than ~10 seconds should be streamed
#[derive(Debug)]
#[repr(transparent)]
pub struct Music {
    raw: ffi::Music,
}

impl Music {
    /// Total number of frames (considering channels)
    #[inline]
    pub fn frame_count(&self) -> u32 {
        self.raw.frameCount
    }

    /// Is music looping enabled
    #[inline]
    pub fn looping(&self) -> bool {
        self.raw.looping
    }

    /// Enable/disable looping
    #[inline]
    pub fn set_looping(&mut self, looping: bool) {
        self.raw.looping = looping;
    }

    /// Load music stream from file
    #[inline]
    pub fn from_file(file_name: &str) -> Option<Self> {
        let file_name = CString::new(file_name).unwrap();

        let raw = unsafe { ffi::LoadMusicStream(file_name.as_ptr()) };

        if unsafe { ffi::IsMusicReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }
    /// Load music stream from data
    #[inline]
    pub fn from_memory(data: &[u8], format: AudioFormat) -> Option<Self> {
        let raw = unsafe {
            ffi::LoadMusicStreamFromMemory(format.as_cstr().as_ptr(), data.as_ptr(), data.len() as _)
        };

        if unsafe { ffi::IsMusicReady(raw.clone()) } {
            Some(Self { raw })
        } else {
            None
        }
    }

    /// Start music playing
    #[inline]
    pub fn play(&self, _device: &mut AudioDevice) {
        unsafe { ffi::PlayMusicStream(self.raw.clone()) }
    }

    /// Check if music is playing
    #[inline]
    pub fn is_playing(&self, _device: &mut AudioDevice) -> bool {
        unsafe { ffi::IsMusicStreamPlaying(self.raw.clone()) }
    }

    /// Updates buffers for music streaming
    #[inline]
    pub fn update(&self, _device: &mut AudioDevice) {
        unsafe { ffi::UpdateMusicStream(self.raw.clone()) }
    }

    /// Stop music playing
    #[inline]
    pub fn stop(&self, _device: &mut AudioDevice) {
        unsafe { ffi::StopMusicStream(self.raw.clone()) }
    }

    /// Pause music playing
    #[inline]
    pub fn pause(&self, _device: &mut AudioDevice) {
        unsafe { ffi::PauseMusicStream(self.raw.clone()) }
    }

    /// Resume playing paused music
    #[inline]
    pub fn resume(&self, _device: &mut AudioDevice) {
        unsafe { ffi::ResumeMusicStream(self.raw.clone()) }
    }

    /// Seek music to a position
    #[inline]
    pub fn seek(&self, position: Duration, _device: &mut AudioDevice) {
        unsafe { ffi::SeekMusicStream(self.raw.clone(), position.as_secs_f32()) }
    }

    /// Set volume for music (1.0 is max level)
    #[inline]
    pub fn set_volume(&self, volume: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetMusicVolume(self.raw.clone(), volume) }
    }

    /// Set pitch for a music (1.0 is base level)
    #[inline]
    pub fn set_pitch(&self, pitch: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetMusicPitch(self.raw.clone(), pitch) }
    }

    /// Set pan for a music (0.5 is center)
    #[inline]
    pub fn set_pan(&self, pan: f32, _device: &mut AudioDevice) {
        unsafe { ffi::SetMusicPan(self.raw.clone(), pan) }
    }

    /// Get music time length
    #[inline]
    pub fn get_time_length(&self, _device: &mut AudioDevice) -> Duration {
        Duration::from_secs_f32(unsafe { ffi::GetMusicTimeLength(self.raw.clone()) })
    }

    /// Get current music time played
    #[inline]
    pub fn get_time_played(&self, _device: &mut AudioDevice) -> Duration {
        Duration::from_secs_f32(unsafe { ffi::GetMusicTimePlayed(self.raw.clone()) })
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw(&self) -> &ffi::Music {
        &self.raw
    }

    /// Get the 'raw' ffi type
    /// Take caution when cloning so it doesn't outlive the original
    #[inline]
    pub fn as_raw_mut(&mut self) -> &mut ffi::Music {
        &mut self.raw
    }

    /// Convert a 'raw' ffi object to a safe wrapper
    ///
    /// # Safety
    /// * The raw object must be correctly initialized
    /// * The raw object should be unique. Otherwise, make sure its clones don't outlive the newly created object.
    #[inline]
    pub unsafe fn from_raw(raw: ffi::Music) -> Self {
        Self { raw }
    }
}

impl Drop for Music {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::UnloadMusicStream(self.raw.clone()) }
    }
}

//pub type AudioCallback = Option<unsafe extern "C" fn(bufferData: *mut core::ffi::c_void, frames: u32, )>;

/*
    /// Audio thread callback to request new data
    #[inline]
    pub fn SetAudioStreamCallback(stream: AudioStream, callback: AudioCallback);
    /// Attach audio stream processor to stream
    #[inline]
    pub fn AttachAudioStreamProcessor(stream: AudioStream, processor: AudioCallback);
    /// Detach audio stream processor from stream
    #[inline]
    pub fn DetachAudioStreamProcessor(stream: AudioStream, processor: AudioCallback);
    /// Attach audio stream processor to the entire audio pipeline
    #[inline]
    pub fn AttachAudioMixedProcessor(processor: AudioCallback);
    /// Detach audio stream processor from the entire audio pipeline
    #[inline]
    pub fn DetachAudioMixedProcessor(processor: AudioCallback);
*/