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
use bindings::audio_unit as au;
use error::{self, Error};
use libc;
use super::{AudioUnit, Element, Scope};
pub use self::action_flags::ActionFlags;
pub use self::data::Data;
pub type InputProcFn = FnMut(*mut au::AudioUnitRenderActionFlags,
*const au::AudioTimeStamp,
au::UInt32,
au::UInt32,
*mut au::AudioBufferList) -> au::OSStatus;
pub struct InputProcFnWrapper {
callback: Box<InputProcFn>,
}
pub struct Args<D> {
pub data: D,
pub time_stamp: au::AudioTimeStamp,
pub bus_number: u32,
pub num_frames: usize,
pub flags: action_flags::Handle,
}
pub mod data {
use bindings::audio_unit as au;
use std::marker::PhantomData;
use std::{iter, slice};
use super::super::StreamFormat;
use super::super::Sample;
pub trait Data {
fn does_stream_format_match(&StreamFormat) -> bool;
unsafe fn from_input_proc_args(num_frames: u32, io_data: *mut au::AudioBufferList) -> Self;
}
pub struct Raw {
pub data: *mut au::AudioBufferList,
}
impl Data for Raw {
fn does_stream_format_match(_: &StreamFormat) -> bool {
true
}
unsafe fn from_input_proc_args(_num_frames: u32, io_data: *mut au::AudioBufferList) -> Self {
Raw { data: io_data }
}
}
pub struct NonInterleaved<S> {
buffers: [au::AudioBuffer; 128],
num_buffers: usize,
frames: usize,
sample_format: PhantomData<S>,
}
pub struct Channels<'a, S: 'a> {
buffers: iter::Take<slice::Iter<'a, au::AudioBuffer>>,
frames: usize,
sample_format: PhantomData<S>,
}
pub struct ChannelsMut<'a, S: 'a> {
buffers: iter::Take<slice::IterMut<'a, au::AudioBuffer>>,
frames: usize,
sample_format: PhantomData<S>,
}
unsafe impl<S> Send for NonInterleaved<S> where S: Send {}
impl<'a, S> Iterator for Channels<'a, S> {
type Item = &'a [S];
#[allow(non_snake_case)]
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|&au::AudioBuffer { mNumberChannels, mData, .. }| {
let len = mNumberChannels as usize * self.frames;
let ptr = mData as *mut S;
unsafe { slice::from_raw_parts(ptr, len) }
})
}
}
impl<'a, S> Iterator for ChannelsMut<'a, S> {
type Item = &'a mut [S];
#[allow(non_snake_case)]
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|&mut au::AudioBuffer { mNumberChannels, mData, .. }| {
let len = mNumberChannels as usize * self.frames;
let ptr = mData as *mut S;
unsafe { slice::from_raw_parts_mut(ptr, len) }
})
}
}
impl<S> NonInterleaved<S> {
pub fn channels(&self) -> Channels<S> {
Channels {
buffers: self.buffers.iter().take(self.num_buffers),
frames: self.frames,
sample_format: PhantomData,
}
}
pub fn channels_mut(&mut self) -> ChannelsMut<S> {
ChannelsMut {
buffers: self.buffers.iter_mut().take(self.num_buffers),
frames: self.frames,
sample_format: PhantomData,
}
}
}
impl<S> Data for NonInterleaved<S>
where S: Sample,
{
fn does_stream_format_match(format: &StreamFormat) -> bool {
S::sample_format().does_match_flags(format.flags)
}
#[allow(non_snake_case)]
unsafe fn from_input_proc_args(frames: u32, io_data: *mut au::AudioBufferList) -> Self {
let au::AudioBufferList { mNumberBuffers, mBuffers } = *io_data;
let buffers: [au::AudioBuffer; 128] = mBuffers;
NonInterleaved {
buffers: buffers,
num_buffers: mNumberBuffers as usize,
frames: frames as usize,
sample_format: PhantomData,
}
}
}
}
pub mod action_flags {
use bindings::audio_unit as au;
bitflags!{
pub flags ActionFlags: u32 {
const PRE_RENDER = au::kAudioUnitRenderAction_PreRender,
const POST_RENDER = au::kAudioUnitRenderAction_PostRender,
const OUTPUT_IS_SILENCE = au::kAudioUnitRenderAction_OutputIsSilence,
const OFFLINE_PREFLIGHT = au::kAudioOfflineUnitRenderAction_Preflight,
const OFFLINE_RENDER = au::kAudioOfflineUnitRenderAction_Render,
const OFFLINE_COMPLETE = au::kAudioOfflineUnitRenderAction_Complete,
const POST_RENDER_ERROR = au::kAudioUnitRenderAction_PostRenderError,
const DO_NOT_CHECK_RENDER_ARGS = au::kAudioUnitRenderAction_DoNotCheckRenderArgs,
}
}
pub struct Handle {
ptr: *mut au::AudioUnitRenderActionFlags,
}
impl Handle {
pub fn get(&self) -> ActionFlags {
ActionFlags::from_bits_truncate(unsafe { *self.ptr })
}
fn set(&mut self, flags: ActionFlags) {
unsafe { *self.ptr = flags.bits() }
}
pub fn bits(&self) -> u32 {
self.get().bits()
}
pub fn is_empty(&self) -> bool {
self.get().is_empty()
}
pub fn is_all(&self) -> bool {
self.get().is_all()
}
pub fn intersects(&self, other: ActionFlags) -> bool {
self.get().intersects(other)
}
pub fn contains(&self, other: ActionFlags) -> bool {
self.get().contains(other)
}
pub fn insert(&mut self, other: ActionFlags) {
let mut flags = self.get();
flags.insert(other);
self.set(flags);
}
pub fn remove(&mut self, other: ActionFlags) {
let mut flags = self.get();
flags.remove(other);
self.set(flags);
}
pub fn toggle(&mut self, other: ActionFlags) {
let mut flags = self.get();
flags.toggle(other);
self.set(flags);
}
pub fn from_ptr(ptr: *mut au::AudioUnitRenderActionFlags) -> Self {
Handle { ptr: ptr }
}
}
unsafe impl Send for Handle {}
impl ::std::fmt::Display for ActionFlags {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{:?}", match self.bits() {
au::kAudioUnitRenderAction_PreRender => "PRE_RENDER",
au::kAudioUnitRenderAction_PostRender => "POST_RENDER",
au::kAudioUnitRenderAction_OutputIsSilence => "OUTPUT_IS_SILENCE",
au::kAudioOfflineUnitRenderAction_Preflight => "OFFLINE_PREFLIGHT",
au::kAudioOfflineUnitRenderAction_Render => "OFFLINE_RENDER",
au::kAudioOfflineUnitRenderAction_Complete => "OFFLINE_COMPLETE",
au::kAudioUnitRenderAction_PostRenderError => "POST_RENDER_ERROR",
au::kAudioUnitRenderAction_DoNotCheckRenderArgs => "DO_NOT_CHECK_RENDER_ARGS",
_ => "<Unknown ActionFlags>",
})
}
}
}
impl AudioUnit {
pub fn set_render_callback<F, D>(&mut self, mut f: F) -> Result<(), Error>
where F: FnMut(Args<D>) -> Result<(), ()> + 'static,
D: Data,
{
let stream_format = try!(self.stream_format());
if !D::does_stream_format_match(&stream_format) {
return Err(Error::RenderCallbackBufferFormatDoesNotMatchAudioUnitStreamFormat);
}
let input_proc_fn = move |io_action_flags: *mut au::AudioUnitRenderActionFlags,
in_time_stamp: *const au::AudioTimeStamp,
in_bus_number: au::UInt32,
in_number_frames: au::UInt32,
io_data: *mut au::AudioBufferList| -> au::OSStatus
{
let args = unsafe {
let data = D::from_input_proc_args(in_number_frames, io_data);
let flags = action_flags::Handle::from_ptr(io_action_flags);
Args {
data: data,
time_stamp: *in_time_stamp,
flags: flags,
bus_number: in_bus_number as u32,
num_frames: in_number_frames as usize,
}
};
match f(args) {
Ok(()) => 0 as au::OSStatus,
Err(()) => error::Error::Unspecified.to_os_status(),
}
};
let input_proc_fn_wrapper = Box::new(InputProcFnWrapper {
callback: Box::new(input_proc_fn),
});
let input_proc_fn_wrapper_ptr = Box::into_raw(input_proc_fn_wrapper) as *mut libc::c_void;
let render_callback = au::AURenderCallbackStruct {
inputProc: Some(input_proc),
inputProcRefCon: input_proc_fn_wrapper_ptr,
};
try!(self.set_property(au::kAudioUnitProperty_SetRenderCallback,
Scope::Input,
Element::Output,
Some(&render_callback)));
self.free_render_callback();
self.maybe_callback = Some(input_proc_fn_wrapper_ptr as *mut InputProcFnWrapper);
Ok(())
}
pub fn free_render_callback(&mut self) {
if let Some(callback) = self.maybe_callback.take() {
let _: Box<InputProcFnWrapper> = unsafe {
Box::from_raw(callback as *mut InputProcFnWrapper)
};
}
}
}
extern "C" fn input_proc(in_ref_con: *mut libc::c_void,
io_action_flags: *mut au::AudioUnitRenderActionFlags,
in_time_stamp: *const au::AudioTimeStamp,
in_bus_number: au::UInt32,
in_number_frames: au::UInt32,
io_data: *mut au::AudioBufferList) -> au::OSStatus
{
let wrapper = in_ref_con as *mut InputProcFnWrapper;
unsafe {
(*(*wrapper).callback)(io_action_flags,
in_time_stamp,
in_bus_number,
in_number_frames,
io_data)
}
}