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
use std::ffi::{CStr, CString};
use num::FromPrimitive;
use libc::{c_int, c_void, uint8_t, c_char};
use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::marker::PhantomData;
use std::mem;
use std::ptr;
use AudioSubsystem;
use get_error;
use rwops::RWops;
use sys::audio as ll;
impl AudioSubsystem {
#[inline]
pub fn open_playback<CB, F>(&self, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String>
where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB
{
AudioDevice::open_playback(self, device, spec, get_callback)
}
#[inline]
pub fn open_queue<Channel>(&self, device: Option<&str>, spec: &AudioSpecDesired) -> Result<AudioQueue<Channel>, String> where Channel: AudioFormatNum
{
AudioQueue::open_queue(self, device, spec)
}
pub fn current_audio_driver(&self) -> &'static str {
unsafe {
let buf = ll::SDL_GetCurrentAudioDriver();
assert!(!buf.is_null());
CStr::from_ptr(buf as *const _).to_str().unwrap()
}
}
pub fn num_audio_playback_devices(&self) -> Option<u32> {
let result = unsafe { ll::SDL_GetNumAudioDevices(0) };
if result < 0 {
None
} else {
Some(result as u32)
}
}
pub fn audio_playback_device_name(&self, index: u32) -> Result<String, String> {
unsafe {
let dev_name = ll::SDL_GetAudioDeviceName(index as c_int, 0);
if dev_name.is_null() {
Err(get_error())
} else {
let cstr = CStr::from_ptr(dev_name as *const _);
Ok(cstr.to_str().unwrap().to_owned())
}
}
}
}
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum AudioFormat {
U8 = ll::AUDIO_U8 as i32,
S8 = ll::AUDIO_S8 as i32,
U16LSB = ll::AUDIO_U16LSB as i32,
U16MSB = ll::AUDIO_U16MSB as i32,
S16LSB = ll::AUDIO_S16LSB as i32,
S16MSB = ll::AUDIO_S16MSB as i32,
S32LSB = ll::AUDIO_S32LSB as i32,
S32MSB = ll::AUDIO_S32MSB as i32,
F32LSB = ll::AUDIO_F32LSB as i32,
F32MSB = ll::AUDIO_F32MSB as i32
}
impl AudioFormat {
fn from_ll(raw: ll::SDL_AudioFormat) -> Option<AudioFormat> {
use self::AudioFormat::*;
match raw {
ll::AUDIO_U8 => Some(U8),
ll::AUDIO_S8 => Some(S8),
ll::AUDIO_U16LSB => Some(U16LSB),
ll::AUDIO_U16MSB => Some(U16MSB),
ll::AUDIO_S16LSB => Some(S16LSB),
ll::AUDIO_S16MSB => Some(S16MSB),
ll::AUDIO_S32LSB => Some(S32LSB),
ll::AUDIO_S32MSB => Some(S32MSB),
ll::AUDIO_F32LSB => Some(F32LSB),
ll::AUDIO_F32MSB => Some(F32MSB),
_ => None
}
}
fn to_ll(self) -> ll::SDL_AudioFormat {
self as ll::SDL_AudioFormat
}
}
#[cfg(target_endian = "little")]
impl AudioFormat {
#[inline] pub fn u16_sys() -> AudioFormat { AudioFormat::U16LSB }
#[inline] pub fn s16_sys() -> AudioFormat { AudioFormat::S16LSB }
#[inline] pub fn s32_sys() -> AudioFormat { AudioFormat::S32LSB }
#[inline] pub fn f32_sys() -> AudioFormat { AudioFormat::F32LSB }
}
#[cfg(target_endian = "big")]
impl AudioFormat {
#[inline] pub fn u16_sys() -> AudioFormat { AudioFormat::U16MSB }
#[inline] pub fn s16_sys() -> AudioFormat { AudioFormat::S16MSB }
#[inline] pub fn s32_sys() -> AudioFormat { AudioFormat::S32MSB }
#[inline] pub fn f32_sys() -> AudioFormat { AudioFormat::F32MSB }
}
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum AudioStatus {
Stopped = ll::SDL_AUDIO_STOPPED as i32,
Playing = ll::SDL_AUDIO_PLAYING as i32,
Paused = ll::SDL_AUDIO_PAUSED as i32,
}
impl FromPrimitive for AudioStatus {
fn from_i64(n: i64) -> Option<AudioStatus> {
use self::AudioStatus::*;
Some( match n as ll::SDL_AudioStatus {
ll::SDL_AUDIO_STOPPED => Stopped,
ll::SDL_AUDIO_PLAYING => Playing,
ll::SDL_AUDIO_PAUSED => Paused,
_ => return None,
})
}
fn from_u64(n: u64) -> Option<AudioStatus> { FromPrimitive::from_i64(n as i64) }
}
#[derive(Copy, Clone)]
pub struct DriverIterator {
length: i32,
index: i32
}
impl Iterator for DriverIterator {
type Item = &'static str;
#[inline]
fn next(&mut self) -> Option<&'static str> {
if self.index >= self.length {
None
} else {
unsafe {
let buf = ll::SDL_GetAudioDriver(self.index);
assert!(!buf.is_null());
self.index += 1;
Some(CStr::from_ptr(buf as *const _).to_str().unwrap())
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let l = self.length as usize;
(l, Some(l))
}
}
impl ExactSizeIterator for DriverIterator { }
#[inline]
pub fn drivers() -> DriverIterator {
DriverIterator {
length: unsafe { ll::SDL_GetNumAudioDrivers() },
index: 0
}
}
pub struct AudioSpecWAV {
pub freq: i32,
pub format: AudioFormat,
pub channels: u8,
audio_buf: *mut u8,
audio_len: u32
}
impl AudioSpecWAV {
pub fn load_wav<P: AsRef<Path>>(path: P) -> Result<AudioSpecWAV, String> {
let mut file = try!(RWops::from_file(path, "rb"));
AudioSpecWAV::load_wav_rw(&mut file)
}
pub fn load_wav_rw(src: &mut RWops) -> Result<AudioSpecWAV, String> {
use std::mem::uninitialized;
use std::ptr::null_mut;
let mut desired = unsafe { uninitialized::<ll::SDL_AudioSpec>() };
let mut audio_buf: *mut u8 = null_mut();
let mut audio_len: u32 = 0;
unsafe {
let ret = ll::SDL_LoadWAV_RW(src.raw(), 0, &mut desired, &mut audio_buf, &mut audio_len);
if ret.is_null() {
Err(get_error())
} else {
Ok(AudioSpecWAV {
freq: desired.freq,
format: AudioFormat::from_ll(desired.format).unwrap(),
channels: desired.channels,
audio_buf: audio_buf,
audio_len: audio_len
})
}
}
}
pub fn buffer(&self) -> &[u8] {
use std::slice::from_raw_parts;
unsafe {
let ptr = self.audio_buf as *const u8;
let len = self.audio_len as usize;
from_raw_parts(ptr, len)
}
}
}
impl Drop for AudioSpecWAV {
fn drop(&mut self) {
unsafe { ll::SDL_FreeWAV(self.audio_buf); }
}
}
pub trait AudioCallback: Send
where Self::Channel: AudioFormatNum + 'static
{
type Channel;
fn callback(&mut self, &mut [Self::Channel]);
}
pub trait AudioFormatNum {
fn audio_format() -> AudioFormat;
fn zero() -> Self;
}
impl AudioFormatNum for i8 {
fn audio_format() -> AudioFormat { AudioFormat::S8 }
fn zero() -> i8 { 0 }
}
impl AudioFormatNum for u8 {
fn audio_format() -> AudioFormat { AudioFormat::U8 }
fn zero() -> u8 { 0 }
}
impl AudioFormatNum for i16 {
fn audio_format() -> AudioFormat { AudioFormat::s16_sys() }
fn zero() -> i16 { 0 }
}
impl AudioFormatNum for u16 {
fn audio_format() -> AudioFormat { AudioFormat::u16_sys() }
fn zero() -> u16 { 0 }
}
impl AudioFormatNum for i32 {
fn audio_format() -> AudioFormat { AudioFormat::s32_sys() }
fn zero() -> i32 { 0 }
}
impl AudioFormatNum for f32 {
fn audio_format() -> AudioFormat { AudioFormat::f32_sys() }
fn zero() -> f32 { 0.0 }
}
extern "C" fn audio_callback_marshall<CB: AudioCallback>
(userdata: *mut c_void, stream: *mut uint8_t, len: c_int) {
use std::slice::from_raw_parts_mut;
use std::mem::{size_of, transmute};
unsafe {
let mut cb_userdata: &mut CB = transmute(userdata);
let buf: &mut [CB::Channel] = from_raw_parts_mut(
stream as *mut CB::Channel,
len as usize / size_of::<CB::Channel>()
);
cb_userdata.callback(buf);
}
}
#[derive(Clone)]
pub struct AudioSpecDesired {
pub freq: Option<i32>,
pub channels: Option<u8>,
pub samples: Option<u16>,
}
impl AudioSpecDesired {
fn convert_to_ll<CB: AudioCallback>(freq: Option<i32>, channels: Option<u8>, samples: Option<u16>, userdata: *mut CB) -> ll::SDL_AudioSpec {
use std::mem::transmute;
if let Some(freq) = freq { assert!(freq > 0); }
if let Some(channels) = channels { assert!(channels > 0); }
if let Some(samples) = samples { assert!(samples > 0); }
unsafe {
ll::SDL_AudioSpec {
freq: freq.unwrap_or(0),
format: <CB::Channel as AudioFormatNum>::audio_format().to_ll(),
channels: channels.unwrap_or(0),
silence: 0,
samples: samples.unwrap_or(0),
padding: 0,
size: 0,
callback: Some(audio_callback_marshall::<CB>
as extern "C" fn
(arg1: *mut c_void,
arg2: *mut uint8_t,
arg3: c_int)),
userdata: transmute(userdata)
}
}
}
fn convert_queue_to_ll<Channel: AudioFormatNum>(freq: Option<i32>, channels: Option<u8>, samples: Option<u16>) -> ll::SDL_AudioSpec {
if let Some(freq) = freq { assert!(freq > 0); }
if let Some(channels) = channels { assert!(channels > 0); }
if let Some(samples) = samples { assert!(samples > 0); }
ll::SDL_AudioSpec {
freq: freq.unwrap_or(0),
format: <Channel as AudioFormatNum>::audio_format().to_ll(),
channels: channels.unwrap_or(0),
silence: 0,
samples: samples.unwrap_or(0),
padding: 0,
size: 0,
callback: None,
userdata: 0 as *mut c_void
}
}
}
#[allow(missing_copy_implementations)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct AudioSpec {
pub freq: i32,
pub format: AudioFormat,
pub channels: u8,
pub silence: u8,
pub samples: u16,
pub size: u32
}
impl AudioSpec {
fn convert_from_ll(spec: ll::SDL_AudioSpec) -> AudioSpec {
AudioSpec {
freq: spec.freq,
format: AudioFormat::from_ll(spec.format).unwrap(),
channels: spec.channels,
silence: spec.silence,
samples: spec.samples,
size: spec.size
}
}
}
enum AudioDeviceID {
PlaybackDevice(ll::SDL_AudioDeviceID)
}
impl AudioDeviceID {
fn id(&self) -> ll::SDL_AudioDeviceID {
match self {
&AudioDeviceID::PlaybackDevice(id) => id
}
}
}
impl Drop for AudioDeviceID {
fn drop(&mut self) {
unsafe { ll::SDL_CloseAudioDevice(self.id()) }
}
}
pub struct AudioQueue<Channel: AudioFormatNum> {
subsystem: AudioSubsystem,
device_id: AudioDeviceID,
phantom: PhantomData<Channel>
}
impl<Channel: AudioFormatNum> AudioQueue<Channel> {
pub fn open_queue(a: &AudioSubsystem, device: Option<&str>, spec: &AudioSpecDesired) -> Result<AudioQueue<Channel>, String> {
let desired = AudioSpecDesired::convert_queue_to_ll::<Channel>(spec.freq, spec.channels, spec.samples);
let mut obtained = unsafe { mem::uninitialized::<ll::SDL_AudioSpec>() };
unsafe {
let device = match device {
Some(device) => Some(CString::new(device).unwrap()),
None => None
};
let device_ptr = device.map_or(ptr::null(), |s| s.as_ptr());
let iscapture_flag = 0;
let device_id = ll::SDL_OpenAudioDevice(
device_ptr as *const c_char, iscapture_flag, &desired,
&mut obtained, 0
);
match device_id {
0 => {
Err(get_error())
},
id => {
let device_id = AudioDeviceID::PlaybackDevice(id);
Ok(AudioQueue {
subsystem: a.clone(),
device_id: device_id,
phantom: PhantomData::default()
})
}
}
}
}
#[inline]
pub fn subsystem(&self) -> &AudioSubsystem { &self.subsystem }
pub fn status(&self) -> AudioStatus {
unsafe {
let status = ll::SDL_GetAudioDeviceStatus(self.device_id.id());
FromPrimitive::from_i32(status as i32).unwrap()
}
}
pub fn pause(&self) {
unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 1) }
}
pub fn resume(&self) {
unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 0) }
}
pub fn queue(&self, data: &[Channel]) -> bool {
let result = unsafe {ll::SDL_QueueAudio(self.device_id.id(), data.as_ptr() as *const c_void, (data.len() * mem::size_of::<Channel>()) as u32)};
result == 0
}
pub fn size(&self) -> u32 {
unsafe {ll::SDL_GetQueuedAudioSize(self.device_id.id())}
}
pub fn clear(&self) {
unsafe {ll::SDL_ClearQueuedAudio(self.device_id.id());}
}
}
pub struct AudioDevice<CB: AudioCallback> {
subsystem: AudioSubsystem,
device_id: AudioDeviceID,
userdata: Box<CB>
}
impl<CB: AudioCallback> AudioDevice<CB> {
pub fn open_playback<F>(a: &AudioSubsystem, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String>
where F: FnOnce(AudioSpec) -> CB
{
let userdata: *mut CB = unsafe {
let b: Box<CB> = Box::new(mem::uninitialized());
mem::transmute(b)
};
let desired = AudioSpecDesired::convert_to_ll(spec.freq, spec.channels, spec.samples, userdata);
let mut obtained = unsafe { mem::uninitialized::<ll::SDL_AudioSpec>() };
unsafe {
let device = match device {
Some(device) => Some(CString::new(device).unwrap()),
None => None
};
let device_ptr = device.map_or(ptr::null(), |s| s.as_ptr());
let iscapture_flag = 0;
let device_id = ll::SDL_OpenAudioDevice(
device_ptr as *const c_char, iscapture_flag, &desired,
&mut obtained, 0
);
match device_id {
0 => {
Err(get_error())
},
id => {
let device_id = AudioDeviceID::PlaybackDevice(id);
let spec = AudioSpec::convert_from_ll(obtained);
let mut userdata: Box<CB> = mem::transmute(userdata);
let garbage = mem::replace(&mut userdata as &mut CB, get_callback(spec));
mem::forget(garbage);
Ok(AudioDevice {
subsystem: a.clone(),
device_id: device_id,
userdata: userdata
})
}
}
}
}
#[inline]
pub fn subsystem(&self) -> &AudioSubsystem { &self.subsystem }
pub fn status(&self) -> AudioStatus {
unsafe {
let status = ll::SDL_GetAudioDeviceStatus(self.device_id.id());
FromPrimitive::from_i32(status as i32).unwrap()
}
}
pub fn pause(&self) {
unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 1) }
}
pub fn resume(&self) {
unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 0) }
}
pub fn lock<'a>(&'a mut self) -> AudioDeviceLockGuard<'a, CB> {
unsafe { ll::SDL_LockAudioDevice(self.device_id.id()) };
AudioDeviceLockGuard {
device: self,
_nosend: PhantomData
}
}
pub fn close_and_get_callback(self) -> CB {
drop(self.device_id);
*self.userdata
}
}
pub struct AudioDeviceLockGuard<'a, CB> where CB: AudioCallback, CB: 'a {
device: &'a mut AudioDevice<CB>,
_nosend: PhantomData<*mut ()>
}
impl<'a, CB: AudioCallback> Deref for AudioDeviceLockGuard<'a, CB> {
type Target = CB;
fn deref(&self) -> &CB { &self.device.userdata }
}
impl<'a, CB: AudioCallback> DerefMut for AudioDeviceLockGuard<'a, CB> {
fn deref_mut(&mut self) -> &mut CB { &mut self.device.userdata }
}
impl<'a, CB: AudioCallback> Drop for AudioDeviceLockGuard<'a, CB> {
fn drop(&mut self) {
unsafe { ll::SDL_UnlockAudioDevice(self.device.device_id.id()) }
}
}
#[derive(Copy, Clone)]
pub struct AudioCVT {
raw: ll::SDL_AudioCVT
}
impl AudioCVT {
pub fn new(src_format: AudioFormat, src_channels: u8, src_rate: i32,
dst_format: AudioFormat, dst_channels: u8, dst_rate: i32) -> Result<AudioCVT, String>
{
use std::mem;
unsafe {
let mut raw: ll::SDL_AudioCVT = mem::uninitialized();
let ret = ll::SDL_BuildAudioCVT(&mut raw,
src_format.to_ll(), src_channels, src_rate as c_int,
dst_format.to_ll(), dst_channels, dst_rate as c_int);
if ret == 1 || ret == 0 {
Ok(AudioCVT { raw: raw })
} else {
Err(get_error())
}
}
}
pub fn convert(&self, mut src: Vec<u8>) -> Vec<u8> {
use num::traits as num;
unsafe {
if self.raw.needed != 0 {
let mut raw = self.raw;
raw.len = num::cast(src.len()).expect("Buffer length overflow");
let dst_size = self.capacity(src.len());
let needed = dst_size - src.len();
src.reserve_exact(needed);
raw.buf = src.as_mut_ptr();
let ret = ll::SDL_ConvertAudio(&mut raw);
if ret != 0 { panic!(get_error()) }
debug_assert!(raw.len_cvt > 0);
debug_assert!(raw.len_cvt as usize <= src.capacity());
src.set_len(raw.len_cvt as usize);
src
} else {
src
}
}
}
pub fn is_conversion_needed(&self) -> bool { self.raw.needed != 0 }
pub fn capacity(&self, src_len: usize) -> usize {
src_len.checked_mul(self.raw.len_mult as usize).expect("Integer overflow")
}
}
#[cfg(test)]
mod test {
use super::{AudioCVT, AudioFormat};
#[test]
fn test_audio_cvt() {
use std::iter::repeat;
let buffer: Vec<u8> = (0..255).collect();
let new_buffer_expected: Vec<u8> = (0..255).flat_map(|v| repeat(v).take(2)).collect();
let cvt = AudioCVT::new(AudioFormat::U8, 1, 44100, AudioFormat::U8, 2, 44100).unwrap();
assert!(cvt.is_conversion_needed());
assert_eq!(cvt.capacity(255), 255*2);
let new_buffer = cvt.convert(buffer);
assert_eq!(new_buffer.len(), new_buffer_expected.len());
assert_eq!(new_buffer, new_buffer_expected);
}
}