nstd_audio 0.5.0

NSTD audio playback/data callback crate.
Documentation
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
use cpal::{
    traits::*, BufferSize, BuildStreamError, Device, Host, Sample, SampleFormat, SampleRate,
    Stream, StreamConfig,
};
use nstd_fs::NSTDFile;
use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink};
use std::{
    ffi::CString,
    io::BufReader,
    os::raw::{c_char, c_float, c_int, c_void},
    ptr,
};
#[cfg(feature = "deps")]
pub mod deps {
    pub use cpal;
    pub use nstd_fs;
    pub use rodio;
}

/// Represents an audio host.
pub type NSTDAudioHost = *mut Host;

/// Represents an audio device.
pub type NSTDAudioDevice = *mut Device;

/// Represents an audio stream.
pub type NSTDAudioStream = *mut Stream;

/// Represents an audio sample format.
#[repr(C)]
#[allow(non_camel_case_types)]
pub enum NSTDAudioSampleFormat {
    INT16,
    UINT16,
    FLOAT32,
}

/// Represents a stream config.
/// NOTE: `buffer_size` will be set to 0 for default.
#[repr(C)]
pub struct NSTDAudioStreamConfig {
    pub channels: u16,
    pub sample_rate: u32,
    pub buffer_size: u32,
    pub format: NSTDAudioSampleFormat,
}

/// Represents an audio play stream.
#[repr(C)]
pub struct NSTDAudioPlayStream {
    pub stream: *mut OutputStream,
    pub handle: *mut OutputStreamHandle,
}
impl Default for NSTDAudioPlayStream {
    fn default() -> Self {
        Self {
            stream: ptr::null_mut(),
            handle: ptr::null_mut(),
        }
    }
}

/// Represents an audio sink.
pub type NSTDAudioSink = *mut Sink;

/// Gets the default audio host.
/// Returns: `NSTDAudioHost host` - The default audio host.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_host_default() -> NSTDAudioHost {
    Box::into_raw(Box::new(cpal::default_host()))
}

/// Generates `nstd_audio_host_default_*_device` functions.
macro_rules! generate_default_device {
    ($name: ident, $method: ident) => {
        #[inline]
        #[cfg_attr(feature = "clib", no_mangle)]
        pub unsafe extern "C" fn $name(host: NSTDAudioHost) -> NSTDAudioDevice {
            match (*host).$method() {
                Some(device) => Box::into_raw(Box::new(device)),
                _ => ptr::null_mut(),
            }
        }
    };
}
generate_default_device!(nstd_audio_host_default_input_device, default_input_device);
generate_default_device!(nstd_audio_host_default_output_device, default_output_device);

/// Frees a host's memory.
/// Parameters:
///     `NSTDAudioHost *host` - Pointer to an audio host.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_host_free(host: *mut NSTDAudioHost) {
    Box::from_raw(*host);
    *host = ptr::null_mut();
}

/// Gets the name of a device.
/// Parameters:
///     `NSTDAudioDevice device` - The device.
/// Returns: `char *name` - The device name.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_device_name(device: NSTDAudioDevice) -> *mut c_char {
    match (*device).name() {
        Ok(name) => {
            let mut bytes = name.into_bytes();
            bytes.push(0);
            CString::from_vec_unchecked(bytes).into_raw()
        }
        _ => ptr::null_mut(),
    }
}

/// Frees a device name.
/// Parameters:
///     `const char **name` - A device name.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_device_free_name(name: *mut *mut c_char) {
    drop(CString::from_raw(*name));
    *name = ptr::null_mut();
}

/// Generates `nstd_audio_device_default_*_config` functions.
macro_rules! generate_device_default_config {
    ($name: ident, $method: ident) => {
        #[cfg_attr(feature = "clib", no_mangle)]
        pub unsafe extern "C" fn $name(
            device: NSTDAudioDevice,
            config: *mut NSTDAudioStreamConfig,
        ) -> c_int {
            match (*device).$method() {
                Ok(cpal_supported_config) => {
                    let format = cpal_supported_config.sample_format();
                    let cpal_config = cpal_supported_config.config();
                    *config = NSTDAudioStreamConfig {
                        channels: cpal_config.channels,
                        sample_rate: cpal_config.sample_rate.0,
                        buffer_size: match cpal_config.buffer_size {
                            BufferSize::Default => 0,
                            BufferSize::Fixed(size) => size,
                        },
                        format: match format {
                            SampleFormat::I16 => NSTDAudioSampleFormat::INT16,
                            SampleFormat::U16 => NSTDAudioSampleFormat::UINT16,
                            SampleFormat::F32 => NSTDAudioSampleFormat::FLOAT32,
                        },
                    };
                    0
                }
                _ => 1,
            }
        }
    };
}
generate_device_default_config!(nstd_audio_device_default_input_config, default_input_config);
generate_device_default_config!(
    nstd_audio_device_default_output_config,
    default_output_config
);

/// Generates `nstd_audio_device_build_*_stream` functions.
macro_rules! generate_device_build_stream {
    ($name: ident, $func: ident, $ptr_ty: ty) => {
        #[cfg_attr(feature = "clib", no_mangle)]
        pub unsafe extern "C" fn $name(
            device: NSTDAudioDevice,
            config: *const NSTDAudioStreamConfig,
            format: NSTDAudioSampleFormat,
            callback: extern "C" fn($ptr_ty, usize),
            err_callback: extern "C" fn(),
        ) -> NSTDAudioStream {
            let config = StreamConfig {
                channels: (*config).channels,
                sample_rate: SampleRate((*config).sample_rate),
                buffer_size: match (*config).buffer_size {
                    0 => BufferSize::Default,
                    size => BufferSize::Fixed(size),
                },
            };
            match match format {
                NSTDAudioSampleFormat::INT16 => {
                    $func::<i16>(&*device, &config, callback, err_callback)
                }
                NSTDAudioSampleFormat::UINT16 => {
                    $func::<u16>(&*device, &config, callback, err_callback)
                }
                NSTDAudioSampleFormat::FLOAT32 => {
                    $func::<f32>(&*device, &config, callback, err_callback)
                }
            } {
                Ok(stream) => match stream.play() {
                    Ok(_) => Box::into_raw(Box::new(stream)),
                    _ => ptr::null_mut(),
                },
                _ => ptr::null_mut(),
            }
        }
    };
}
generate_device_build_stream!(
    nstd_audio_device_build_input_stream,
    build_input_stream,
    *const c_void
);
generate_device_build_stream!(
    nstd_audio_device_build_output_stream,
    build_output_stream,
    *mut c_void
);

/// Frees a device.
/// Parameters:
///     `NSTDAudioDevice *device` - Pointer to a device.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_device_free(device: *mut NSTDAudioDevice) {
    Box::from_raw(*device);
    *device = ptr::null_mut();
}

/// Generates `nstd_audio_stream_*` functions.
macro_rules! generate_stream_play_pause {
    ($name: ident, $method: ident) => {
        #[inline]
        #[cfg_attr(feature = "clib", no_mangle)]
        pub unsafe extern "C" fn $name(stream: NSTDAudioStream) -> c_int {
            match (*stream).$method() {
                Ok(_) => 0,
                _ => 1,
            }
        }
    };
}
generate_stream_play_pause!(nstd_audio_stream_play, play);
generate_stream_play_pause!(nstd_audio_stream_pause, pause);

/// Frees an audio stream
/// Parameters:
///     `NSTDAudioStream *stream` - Pointer to an audio stream.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_stream_free(stream: *mut NSTDAudioStream) {
    Box::from_raw(*stream);
    *stream = ptr::null_mut();
}

/// Generates `build_*_stream` functions.
macro_rules! generate_build_stream {
    ($name: ident, $ptr_method: ident, $cbptr_ty: ty, $slice_ty: ty) => {
        #[inline]
        fn $name<T: Sample>(
            device: &Device,
            config: &StreamConfig,
            callback: extern "C" fn($cbptr_ty, usize),
            err_callback: extern "C" fn(),
        ) -> Result<Stream, BuildStreamError> {
            device.$name(
                &config,
                move |data: $slice_ty, _| callback(data.$ptr_method() as $cbptr_ty, data.len()),
                move |_| err_callback(),
            )
        }
    };
}
generate_build_stream!(build_input_stream, as_ptr, *const c_void, &[T]);
generate_build_stream!(build_output_stream, as_mut_ptr, *mut c_void, &mut [T]);

/// Creates a play stream.
/// Returns: `NSTDAudioPlayStream stream` - The new play stream.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_play_stream_new() -> NSTDAudioPlayStream {
    match OutputStream::try_default() {
        Ok((stream, handle)) => NSTDAudioPlayStream {
            stream: Box::into_raw(Box::new(stream)),
            handle: Box::into_raw(Box::new(handle)),
        },
        _ => NSTDAudioPlayStream::default(),
    }
}

/// Frees a play stream.
/// Parameters:
///     `NSTDAudioPlayStream *stream` - The play stream.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_play_stream_free(stream: &mut NSTDAudioPlayStream) {
    Box::from_raw(stream.stream);
    Box::from_raw(stream.handle);
    stream.stream = ptr::null_mut();
    stream.handle = ptr::null_mut();
}

/// Creates a new audio sink.
/// Parameters:
///     `const NSTDAudioPlayStream *const stream` - The stream to create the sink on.
/// Returns: `NSTDAudioSink sink` - The new audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_new(stream: &NSTDAudioPlayStream) -> NSTDAudioSink {
    match Sink::try_new(&*stream.handle) {
        Ok(sink) => Box::into_raw(Box::new(sink)),
        _ => ptr::null_mut(),
    }
}

/// Appends audio to a sink from a file.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
///     `NSTDFile file` - The audio file.
///     `const int should_loop` - Nonzero if the audio should be looped.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_append_from_file(
    sink: NSTDAudioSink,
    file: NSTDFile,
    should_loop: c_int,
) -> c_int {
    let buf = BufReader::new(&*file);
    match should_loop {
        0 => match Decoder::new(buf) {
            Ok(decoder) => {
                (*sink).append(decoder);
                0
            }
            _ => 1,
        },
        _ => match Decoder::new_looped(buf) {
            Ok(decoder) => {
                (*sink).append(decoder);
                0
            }
            _ => 1,
        },
    }
}

/// Plays an audio sink.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_play(sink: NSTDAudioSink) {
    (*sink).play();
}

/// Pauses an audio sink.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_pause(sink: NSTDAudioSink) {
    (*sink).pause();
}

/// Checks if an audio sink is paused.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
/// Returns: `int is_paused` - Whether or not the audio sink is paused.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_is_paused(sink: NSTDAudioSink) -> c_int {
    (*sink).is_paused() as c_int
}

/// Stops audio playback for a sink by clearing it's queue.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_stop(sink: NSTDAudioSink) {
    (*sink).stop();
}

/// Sleeps the current thread until all sounds in the sink are done playing.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_sleep_until_end(sink: NSTDAudioSink) {
    (*sink).sleep_until_end();
}

/// Returns the volume of the audio sink.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
/// Returns: `float volume` - The volume of the sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_get_volume(sink: NSTDAudioSink) -> c_float {
    (*sink).volume()
}

/// Sets the volume of the audio sink.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
///     `const float volume` - The volume of the sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_set_volume(sink: NSTDAudioSink, volume: c_float) {
    (*sink).set_volume(volume);
}

/// Gets the number of audio sources currently in a sink.
/// Parameters:
///     `NSTDAudioSink sink` - The audio sink.
/// Returns: `NSTDUSize size` - The number of audio sources in an audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_length(sink: NSTDAudioSink) -> usize {
    (*sink).len()
}

/// Detaches a sink from it's thread while freeing its memory.
/// Parameters:
///     `NSTDAudioSink *sink` - The audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_detach(sink: &mut NSTDAudioSink) {
    let boxed_sink = Box::from_raw(*sink);
    boxed_sink.detach();
    *sink = ptr::null_mut();
}

/// Frees an audio sink.
/// Parameters:
///     `NSTDAudioSink *sink` - The audio sink.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_audio_sink_free(sink: &mut NSTDAudioSink) {
    Box::from_raw(*sink);
    *sink = ptr::null_mut();
}