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
#![crate_name = "ao"]
#![doc(html_root_url = "http://www.rust-ci.org/tari/rust-ao/doc/ao/")]
#![crate_type = "lib"]
#![deny(dead_code, missing_docs)]
#![feature(unsafe_destructor)]
extern crate libc;
use libc::{c_int, c_char};
use std::error::Error;
use std::ffi::{c_str_to_bytes, CString};
use std::fmt;
use std::intrinsics::size_of;
use std::marker::{ContravariantLifetime, InvariantType};
use std::mem;
use std::os;
use std::str;
use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT};
use std::ptr;
#[allow(non_camel_case_types, dead_code)]
mod ffi;
pub mod auto;
pub type AoResult<T> = Result<T, AoError>;
#[derive(PartialEq, Eq, Show)]
pub enum AoError {
NoDriver = ffi::AO_ENODRIVER as isize,
NotFile = ffi::AO_ENOTFILE as isize,
NotLive = ffi::AO_ENOTLIVE as isize,
BadOption = ffi::AO_EBADOPTION as isize,
OpenDevice = ffi::AO_EOPENDEVICE as isize,
OpenFile = ffi::AO_EOPENFILE as isize,
FileExists = ffi::AO_EFILEEXISTS as isize,
BadFormat = ffi::AO_EBADFORMAT as isize,
Unknown = ffi::AO_EFAIL as isize,
}
impl Copy for AoError { }
impl AoError {
fn from_errno() -> AoError {
match os::errno() as c_int {
ffi::AO_ENODRIVER => AoError::NoDriver,
ffi::AO_ENOTFILE => AoError::NotFile,
ffi::AO_ENOTLIVE => AoError::NotLive,
ffi::AO_EBADOPTION => AoError::BadOption,
ffi::AO_EOPENDEVICE => AoError::OpenDevice,
ffi::AO_EOPENFILE => AoError::OpenFile,
ffi::AO_EFILEEXISTS => AoError::FileExists,
ffi::AO_EBADFORMAT => AoError::BadFormat,
_ => AoError::Unknown
}
}
}
impl Error for AoError {
fn description(&self) -> &str {
match *self {
AoError::NoDriver => "No such driver",
AoError::NotFile => "Driver is not a file output device",
AoError::NotLive => "Driver is not a live output device",
AoError::BadOption => "A valid option key has an invalid value",
AoError::OpenDevice => "Cannot open the output device",
AoError::OpenFile => "Cannot open the output file",
AoError::FileExists => "File for output already exists",
AoError::BadFormat => "Requested stream format is not supported",
AoError::Unknown => "Unknown error"
}
}
}
impl fmt::Display for AoError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.write_str(self.description())
}
}
pub trait Sample : Copy {
fn channels(&self) -> usize;
}
macro_rules! sample_impl(
($t:ty) => (
#[inline]
impl Sample for $t {
fn channels(&self) -> usize { 1 }
}
);
(channels $w:expr) => (
#[inline]
impl<S: Sample> Sample for [S; $w] {
fn channels(&self) -> usize { $w }
}
)
);
sample_impl!(i8);
sample_impl!(i16);
sample_impl!(i32);
sample_impl!(channels 2);
pub struct SampleFormat<T, S> {
pub sample_rate: usize,
pub channels: usize,
pub byte_order: Endianness,
pub matrix: Option<S>,
marker: InvariantType<T>,
}
impl<T: Sample, S: Str> SampleFormat<T, S> {
pub fn new(sample_rate: usize, channels: usize, byte_order: Endianness,
matrix: Option<S>) -> SampleFormat<T, S> {
SampleFormat {
sample_rate: sample_rate,
channels: channels,
byte_order: byte_order,
matrix: matrix,
marker: InvariantType
}
}
fn with_native<F, U>(&self, f: F) -> U
where F: FnOnce(*const ffi::ao_sample_format) -> U {
let sample_size = unsafe {
size_of::<T>() * 8
};
let matrix: Option<CString> = match self.matrix {
None => None,
Some(ref s) => Some(
CString::from_slice(s.as_slice().as_bytes())
)
};
let native = ffi::ao_sample_format {
bits: sample_size as c_int,
rate: self.sample_rate as c_int,
channels: self.channels as c_int,
byte_format: self.byte_order as c_int,
matrix: matrix.map_or(ptr::null(), |cs| cs.as_ptr())
};
f(&native as *const _)
}
}
#[derive(PartialEq, Eq)]
pub enum Endianness {
Little = ffi::AO_FMT_LITTLE as isize,
Big = ffi::AO_FMT_BIG as isize,
Native = ffi::AO_FMT_NATIVE as isize,
}
impl Copy for Endianness { }
pub struct AO;
static mut FFI_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT;
impl AO {
pub fn init() -> AO {
unsafe {
if FFI_INITIALIZED.compare_and_swap(false, true, Ordering::AcqRel) {
panic!("Attempted multiple instantiation of ao::AO")
}
ffi::ao_initialize();
};
AO
}
pub fn get_driver<'a>(&'a self, name: &str) -> Option<Driver<'a>> {
let id = if name != "" {
let cs = CString::from_slice(name.as_bytes());
unsafe {
ffi::ao_driver_id(cs.as_ptr())
}
} else {
unsafe {
ffi::ao_default_driver_id()
}
};
if id == -1 {
None
} else {
Some(Driver {
id: id,
marker: ContravariantLifetime
})
}
}
}
#[unsafe_destructor]
impl Drop for AO {
fn drop(&mut self) {
unsafe {
ffi::ao_shutdown();
FFI_INITIALIZED.store(false, Ordering::Release);
}
}
}
#[derive(Show)]
pub enum DriverType {
Live,
File
}
impl Copy for DriverType { }
impl DriverType {
fn from_c_int(n: c_int) -> DriverType {
match n {
ffi::AO_TYPE_FILE => DriverType::File,
ffi::AO_TYPE_LIVE => DriverType::Live,
n => panic!("Invalid AO_TYPE_*: {}", n)
}
}
}
#[derive(Show)]
pub struct DriverInfo {
pub flavor: DriverType,
pub name: &'static str,
pub short_name: &'static str,
pub comment: Option<&'static str>,
}
impl Copy for DriverInfo { }
pub struct Driver<'a> {
id: c_int,
marker: ContravariantLifetime<'a>,
}
impl<'a> Driver<'a> {
pub fn get_info(&self) -> Option<DriverInfo> {
let id = self.id;
unsafe fn sstr(s: *const c_char) -> &'static str {
let ss = mem::transmute::<&*const c_char, &'static *const c_char>(&s);
str::from_utf8(c_str_to_bytes(ss)).unwrap()
}
unsafe {
ffi::ao_driver_info(id).as_ref().map(|info| {
DriverInfo {
name: sstr(info.name),
short_name: sstr(info.short_name),
comment: if info.comment.is_null() {
None
} else {
Some(sstr(info.comment))
},
flavor: DriverType::from_c_int(info.flavor),
}
})
}
}
pub fn open_live<T: Sample, S: Str>(&self,
format: &SampleFormat<T, S>) -> AoResult<Device<'a, T>> {
let handle = format.with_native(|f| unsafe {
ffi::ao_open_live(self.id, f, ptr::null())
});
Device::<'a, T>::init(handle)
}
pub fn open_file<T: Sample, S: Str>(&self,
format: &SampleFormat<T, S>, file: Path,
overwrite: bool) -> AoResult<Device<'a, T>> {
let c_path = CString::from_vec(file.into_vec());
let handle = format.with_native(|f| {
unsafe {
ffi::ao_open_file(self.id, c_path.as_ptr(), overwrite as c_int, f, ptr::null())
}
});
Device::<'a, T>::init(handle)
}
}
pub struct Device<'a, S> {
id: *mut ffi::ao_device,
marker0: ContravariantLifetime<'a>,
marker1: InvariantType<S>,
}
impl<'a, S: Sample> Device<'a, S> {
fn init(handle: *mut ffi::ao_device) -> AoResult<Device<'a, S>> {
if handle.is_null() {
Err(AoError::from_errno())
} else {
Ok(Device {
id: handle,
marker0: ContravariantLifetime,
marker1: InvariantType,
})
}
}
pub fn play(&self, samples: &[S]) {
unsafe {
let len = samples.len() * size_of::<S>();
ffi::ao_play(self.id, samples.as_ptr() as *const i8, len as u32);
}
}
}
#[unsafe_destructor]
impl<'a, S> Drop for Device<'a, S> {
fn drop(&mut self) {
unsafe {
ffi::ao_close(self.id);
}
}
}
#[test]
#[should_fail]
#[allow(unused_variables)]
fn test_multiple_instantiation() {
let lib = AO::init();
let lib2 = AO::init();
}