Debian Codegraph @

extras/osaudio/osaudio_miniaudio.c

raw symbols SCIP
1 /*
2 Consider this a reference implementation of osaudio. It uses miniaudio under the hood. You can add
3 this file directly to your source tree, but you may need to update the miniaudio path.
4
5 This will use a mutex in osaudio_read() and osaudio_write(). It's a low-contention lock that's only
6 used for the purpose of osaudio_drain(), but it's still a lock nonetheless. I'm not worrying about
7 this too much right now because this is just an example implementation, but I might improve on this
8 at a later date.
9 */
10 #ifndef osaudio_miniaudio_c
11 #define osaudio_miniaudio_c
12
13 #include "osaudio.h"
14
15 /*
16 If you would rather define your own implementation of miniaudio, define OSAUDIO_NO_MINIAUDIO_IMPLEMENTATION. If you do this,
17 you need to make sure you include the implmeentation before osaudio.c. This would only really be useful if you are wanting
18 to do a unity build which uses other parts of miniaudio that this file is currently excluding.
19 */
20 #ifndef OSAUDIO_NO_MINIAUDIO_IMPLEMENTATION
21 #define MA_API static
22 #define MA_NO_DECODING
23 #define MA_NO_ENCODING
24 #define MA_NO_RESOURCE_MANAGER
25 #define MA_NO_NODE_GRAPH
26 #define MA_NO_ENGINE
27 #define MA_NO_GENERATION
28 #define MINIAUDIO_IMPLEMENTATION
29 #include "../../miniaudio.h"
30 #endif
31
32 struct _osaudio_t
33 {
34 ma_device device;
35 osaudio_info_t info;
36 osaudio_config_t config; /* info.configs will point to this. */
37 ma_pcm_rb buffer;
38 ma_semaphore bufferSemaphore; /* The semaphore for controlling access to the buffer. The audio thread will release the semaphore. The read and write functions will wait on it. */
39 ma_atomic_bool32 isActive; /* Starts off as false. Set to true when config.buffer_size data has been written in the case of playback, or as soon as osaudio_read() is called in the case of capture. */
40 ma_atomic_bool32 isPaused;
41 ma_atomic_bool32 isFlushed; /* When set, activation of the device will flush any data that's currently in the buffer. Defaults to false, and will be set to true in osaudio_drain() and osaudio_flush(). */
42 ma_atomic_bool32 xrunDetected; /* Used for detecting when an xrun has occurred and returning from osaudio_read/write() when OSAUDIO_FLAG_REPORT_XRUN is enabled. */
43 ma_spinlock activateLock; /* Used for starting and stopping the device. Needed because two variables control this - isActive and isPaused. */
44 ma_mutex drainLock; /* Used for osaudio_drain(). For mutal exclusion between drain() and read()/write(). Technically results in a lock in read()/write(), but not overthinking that since this is just a reference for now. */
45 };
46
47
48 static ma_bool32 osaudio_g_is_backend_known = MA_FALSE;
49 static ma_backend osaudio_g_backend = ma_backend_wasapi;
50 static ma_context osaudio_g_context;
51 static ma_mutex osaudio_g_context_lock; /* Only used for device enumeration. Created and destroyed with our context. */
52 static ma_uint32 osaudio_g_refcount = 0;
53 static ma_spinlock osaudio_g_lock = 0;
54
55
56 static osaudio_result_t osaudio_result_from_miniaudio(ma_result result)
57 {
58 switch (result)
59 {
60 case MA_SUCCESS: return OSAUDIO_SUCCESS;
61 case MA_INVALID_ARGS: return OSAUDIO_INVALID_ARGS;
62 case MA_INVALID_OPERATION: return OSAUDIO_INVALID_OPERATION;
63 case MA_OUT_OF_MEMORY: return OSAUDIO_OUT_OF_MEMORY;
64 default: return OSAUDIO_ERROR;
65 }
66 }
67
68 static ma_format osaudio_format_to_miniaudio(osaudio_format_t format)
69 {
70 switch (format)
71 {
72 case OSAUDIO_FORMAT_F32: return ma_format_f32;
73 case OSAUDIO_FORMAT_U8: return ma_format_u8;
74 case OSAUDIO_FORMAT_S16: return ma_format_s16;
75 case OSAUDIO_FORMAT_S24: return ma_format_s24;
76 case OSAUDIO_FORMAT_S32: return ma_format_s32;
77 default: return ma_format_unknown;
78 }
79 }
80
81 static osaudio_format_t osaudio_format_from_miniaudio(ma_format format)
82 {
83 switch (format)
84 {
85 case ma_format_f32: return OSAUDIO_FORMAT_F32;
86 case ma_format_u8: return OSAUDIO_FORMAT_U8;
87 case ma_format_s16: return OSAUDIO_FORMAT_S16;
88 case ma_format_s24: return OSAUDIO_FORMAT_S24;
89 case ma_format_s32: return OSAUDIO_FORMAT_S32;
90 default: return OSAUDIO_FORMAT_UNKNOWN;
91 }
92 }
93
94
95 static osaudio_channel_t osaudio_channel_from_miniaudio(ma_channel channel)
96 {
97 /* Channel positions between here and miniaudio will remain in sync. */
98 return (osaudio_channel_t)channel;
99 }
100
101 static ma_channel osaudio_channel_to_miniaudio(osaudio_channel_t channel)
102 {
103 /* Channel positions between here and miniaudio will remain in sync. */
104 return (ma_channel)channel;
105 }
106
107
108 static void osaudio_dummy_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
109 {
110 (void)pDevice;
111 (void)pOutput;
112 (void)pInput;
113 (void)frameCount;
114 }
115
116 static osaudio_result_t osaudio_determine_miniaudio_backend(ma_backend* pBackend, ma_device* pDummyDevice)
117 {
118 ma_device dummyDevice;
119 ma_device_config dummyDeviceConfig;
120 ma_result result;
121
122 /*
123 To do this we initialize a dummy device. We allow the caller to make use of this device as an optimization. This is
124 only used by osaudio_enumerate_devices() because that can make use of the context from the dummy device rather than
125 having to create its own. pDummyDevice can be null.
126 */
127 if (pDummyDevice == NULL) {
128 pDummyDevice = &dummyDevice;
129 }
130
131 dummyDeviceConfig = ma_device_config_init(ma_device_type_playback);
132 dummyDeviceConfig.dataCallback = osaudio_dummy_data_callback;
133
134 result = ma_device_init(NULL, &dummyDeviceConfig, pDummyDevice);
135 if (result != MA_SUCCESS || pDummyDevice->pContext->backend == ma_backend_null) {
136 /* Failed to open a default playback device. Try capture. */
137 if (result == MA_SUCCESS) {
138 /* This means we successfully initialize a device, but its backend is null. It could be that there's no playback devices attached. Try capture. */
139 ma_device_uninit(pDummyDevice);
140 }
141
142 dummyDeviceConfig = ma_device_config_init(ma_device_type_capture);
143 result = ma_device_init(NULL, &dummyDeviceConfig, pDummyDevice);
144 }
145
146 if (result != MA_SUCCESS) {
147 return osaudio_result_from_miniaudio(result);
148 }
149
150 *pBackend = pDummyDevice->pContext->backend;
151
152 /* We're done. */
153 if (pDummyDevice == &dummyDevice) {
154 ma_device_uninit(&dummyDevice);
155 }
156
157 return OSAUDIO_SUCCESS;
158 }
159
160 static osaudio_result_t osaudio_ref_context_nolock()
161 {
162 /* Initialize the global context if necessary. */
163 if (osaudio_g_refcount == 0) {
164 osaudio_result_t result;
165
166 /* If we haven't got a known context, we'll need to determine it here. */
167 if (osaudio_g_is_backend_known == MA_FALSE) {
168 result = osaudio_determine_miniaudio_backend(&osaudio_g_backend, NULL);
169 if (result != OSAUDIO_SUCCESS) {
170 return result;
171 }
172 }
173
174 result = osaudio_result_from_miniaudio(ma_context_init(&osaudio_g_backend, 1, NULL, &osaudio_g_context));
175 if (result != OSAUDIO_SUCCESS) {
176 return result;
177 }
178
179 /* Need a mutex for device enumeration. */
180 ma_mutex_init(&osaudio_g_context_lock);
181 }
182
183 osaudio_g_refcount += 1;
184
185 return OSAUDIO_SUCCESS;
186 }
187
188 static osaudio_result_t osaudio_unref_context_nolock()
189 {
190 if (osaudio_g_refcount == 0) {
191 return OSAUDIO_INVALID_OPERATION;
192 }
193
194 osaudio_g_refcount -= 1;
195
196 /* Uninitialize the context if we don't have any more references. */
197 if (osaudio_g_refcount == 0) {
198 ma_context_uninit(&osaudio_g_context);
199 ma_mutex_uninit(&osaudio_g_context_lock);
200 }
201
202 return OSAUDIO_SUCCESS;
203 }
204
205 static ma_context* osaudio_ref_context()
206 {
207 osaudio_result_t result;
208
209 ma_spinlock_lock(&osaudio_g_lock);
210 {
211 result = osaudio_ref_context_nolock();
212 }
213 ma_spinlock_unlock(&osaudio_g_lock);
214
215 if (result != OSAUDIO_SUCCESS) {
216 return NULL;
217 }
218
219 return &osaudio_g_context;
220 }
221
222 static osaudio_result_t osaudio_unref_context()
223 {
224 osaudio_result_t result;
225
226 ma_spinlock_lock(&osaudio_g_lock);
227 {
228 result = osaudio_unref_context_nolock();
229 }
230 ma_spinlock_unlock(&osaudio_g_lock);
231
232 return result;
233 }
234
235
236 static void osaudio_info_from_miniaudio(osaudio_info_t* info, const ma_device_info* infoMA)
237 {
238 unsigned int iNativeConfig;
239
240 /* It just so happens, by absolutely total coincidence, that the size of the ID and name are the same between here and miniaudio. What are the odds?! */
241 memcpy(info->id.data, &infoMA->id, sizeof(info->id.data));
242 memcpy(info->name, infoMA->name, sizeof(info->name));
243
244 info->config_count = (unsigned int)infoMA->nativeDataFormatCount;
245 for (iNativeConfig = 0; iNativeConfig < info->config_count; iNativeConfig += 1) {
246 unsigned int iChannel;
247
248 info->configs[iNativeConfig].device_id = &info->id;
249 info->configs[iNativeConfig].direction = info->direction;
250 info->configs[iNativeConfig].format = osaudio_format_from_miniaudio(infoMA->nativeDataFormats[iNativeConfig].format);
251 info->configs[iNativeConfig].channels = (unsigned int)infoMA->nativeDataFormats[iNativeConfig].channels;
252 info->configs[iNativeConfig].rate = (unsigned int)infoMA->nativeDataFormats[iNativeConfig].sampleRate;
253
254 /* Apparently miniaudio does not report channel positions. I don't know why I'm not doing that. */
255 for (iChannel = 0; iChannel < info->configs[iNativeConfig].channels; iChannel += 1) {
256 info->configs[iNativeConfig].channel_map[iChannel] = OSAUDIO_CHANNEL_NONE;
257 }
258 }
259 }
260
261 static osaudio_result_t osaudio_enumerate_nolock(unsigned int* count, osaudio_info_t** info, ma_context* pContext)
262 {
263 osaudio_result_t result;
264 ma_device_info* pPlaybackInfos;
265 ma_uint32 playbackCount;
266 ma_device_info* pCaptureInfos;
267 ma_uint32 captureCount;
268 ma_uint32 iInfo;
269 size_t allocSize;
270 osaudio_info_t* pRunningInfo;
271 osaudio_config_t* pRunningConfig;
272
273 /* We now need to retrieve the device information from miniaudio. */
274 result = osaudio_result_from_miniaudio(ma_context_get_devices(pContext, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount));
275 if (result != OSAUDIO_SUCCESS) {
276 osaudio_unref_context();
277 return result;
278 }
279
280 /*
281 Because the caller needs to free the returned pointer it's important that we keep it all in one allocation. Because there can be
282 a variable number of native configs we'll have to compute the size of the allocation first, and then do a second pass to fill
283 out the data.
284 */
285 allocSize = ((size_t)playbackCount + (size_t)captureCount) * sizeof(osaudio_info_t);
286
287 /* Now we need to iterate over each playback and capture device and add up the number of native configs. */
288 for (iInfo = 0; iInfo < playbackCount; iInfo += 1) {
289 ma_context_get_device_info(pContext, ma_device_type_playback, &pPlaybackInfos[iInfo].id, &pPlaybackInfos[iInfo]);
290 allocSize += pPlaybackInfos[iInfo].nativeDataFormatCount * sizeof(osaudio_config_t);
291 }
292 for (iInfo = 0; iInfo < captureCount; iInfo += 1) {
293 ma_context_get_device_info(pContext, ma_device_type_capture, &pCaptureInfos[iInfo].id, &pCaptureInfos[iInfo]);
294 allocSize += pCaptureInfos[iInfo].nativeDataFormatCount * sizeof(osaudio_config_t);
295 }
296
297 /* Now that we know the size of the allocation we can allocate it. */
298 *info = (osaudio_info_t*)calloc(1, allocSize);
299 if (*info == NULL) {
300 osaudio_unref_context();
301 return OSAUDIO_OUT_OF_MEMORY;
302 }
303
304 pRunningInfo = *info;
305 pRunningConfig = (osaudio_config_t*)(((unsigned char*)*info) + (((size_t)playbackCount + (size_t)captureCount) * sizeof(osaudio_info_t)));
306
307 for (iInfo = 0; iInfo < playbackCount; iInfo += 1) {
308 pRunningInfo->direction = OSAUDIO_OUTPUT;
309 pRunningInfo->configs = pRunningConfig;
310 osaudio_info_from_miniaudio(pRunningInfo, &pPlaybackInfos[iInfo]);
311
312 pRunningConfig += pRunningInfo->config_count;
313 pRunningInfo += 1;
314 }
315
316 for (iInfo = 0; iInfo < captureCount; iInfo += 1) {
317 pRunningInfo->direction = OSAUDIO_INPUT;
318 pRunningInfo->configs = pRunningConfig;
319 osaudio_info_from_miniaudio(pRunningInfo, &pPlaybackInfos[iInfo]);
320
321 pRunningConfig += pRunningInfo->config_count;
322 pRunningInfo += 1;
323 }
324
325 *count = (unsigned int)(playbackCount + captureCount);
326
327 return OSAUDIO_SUCCESS;
328 }
329
330 osaudio_result_t osaudio_enumerate(unsigned int* count, osaudio_info_t** info)
331 {
332 osaudio_result_t result;
333 ma_context* pContext = NULL;
334
335 if (count != NULL) {
336 *count = 0;
337 }
338 if (info != NULL) {
339 *info = NULL;
340 }
341
342 if (count == NULL || info == NULL) {
343 return OSAUDIO_INVALID_ARGS;
344 }
345
346 pContext = osaudio_ref_context();
347 if (pContext == NULL) {
348 return OSAUDIO_ERROR;
349 }
350
351 ma_mutex_lock(&osaudio_g_context_lock);
352 {
353 result = osaudio_enumerate_nolock(count, info, pContext);
354 }
355 ma_mutex_unlock(&osaudio_g_context_lock);
356
357 /* We're done. We can now return. */
358 osaudio_unref_context();
359 return result;
360 }
361
362
363 void osaudio_config_init(osaudio_config_t* config, osaudio_direction_t direction)
364 {
365 if (config == NULL) {
366 return;
367 }
368
369 memset(config, 0, sizeof(*config));
370 config->direction = direction;
371 }
372
373
374 static void osaudio_data_callback_playback(osaudio_t audio, void* pOutput, ma_uint32 frameCount)
375 {
376 /*
377 If there's content in the buffer, read from it and release the semaphore. There needs to be a whole frameCount chunk
378 in the buffer so we can keep everything in nice clean chunks. When we read from the buffer, we release a semaphore
379 which will allow the main thread to write more data to the buffer.
380 */
381 ma_uint32 framesToRead;
382 ma_uint32 framesProcessed;
383 void* pBuffer;
384
385 framesToRead = ma_pcm_rb_available_read(&audio->buffer);
386 if (framesToRead > frameCount) {
387 framesToRead = frameCount;
388 }
389
390 framesProcessed = framesToRead;
391
392 /* For robustness we should run this in a loop in case the buffer wraps around. */
393 while (frameCount > 0) {
394 framesToRead = frameCount;
395
396 ma_pcm_rb_acquire_read(&audio->buffer, &framesToRead, &pBuffer);
397 if (framesToRead == 0) {
398 break;
399 }
400
401 memcpy(pOutput, pBuffer, framesToRead * ma_get_bytes_per_frame(audio->device.playback.format, audio->device.playback.channels));
402 ma_pcm_rb_commit_read(&audio->buffer, framesToRead);
403
404 frameCount -= framesToRead;
405 pOutput = ((unsigned char*)pOutput) + (framesToRead * ma_get_bytes_per_frame(audio->device.playback.format, audio->device.playback.channels));
406 }
407
408 /* Make sure we release the semaphore if we ended up reading anything. */
409 if (framesProcessed > 0) {
410 ma_semaphore_release(&audio->bufferSemaphore);
411 }
412
413 if (frameCount > 0) {
414 /* Underrun. Pad with silence. */
415 ma_silence_pcm_frames(pOutput, frameCount, audio->device.playback.format, audio->device.playback.channels);
416 ma_atomic_bool32_set(&audio->xrunDetected, MA_TRUE);
417 }
418 }
419
420 static void osaudio_data_callback_capture(osaudio_t audio, const void* pInput, ma_uint32 frameCount)
421 {
422 /* If there's space in the buffer, write to it and release the semaphore. The semaphore is only released on full-chunk boundaries. */
423 ma_uint32 framesToWrite;
424 ma_uint32 framesProcessed;
425 void* pBuffer;
426
427 framesToWrite = ma_pcm_rb_available_write(&audio->buffer);
428 if (framesToWrite > frameCount) {
429 framesToWrite = frameCount;
430 }
431
432 framesProcessed = framesToWrite;
433
434 while (frameCount > 0) {
435 framesToWrite = frameCount;
436
437 ma_pcm_rb_acquire_write(&audio->buffer, &framesToWrite, &pBuffer);
438 if (framesToWrite == 0) {
439 break;
440 }
441
442 memcpy(pBuffer, pInput, framesToWrite * ma_get_bytes_per_frame(audio->device.capture.format, audio->device.capture.channels));
443 ma_pcm_rb_commit_write(&audio->buffer, framesToWrite);
444
445 frameCount -= framesToWrite;
446 pInput = ((unsigned char*)pInput) + (framesToWrite * ma_get_bytes_per_frame(audio->device.capture.format, audio->device.capture.channels));
447 }
448
449 /* Make sure we release the semaphore if we ended up reading anything. */
450 if (framesProcessed > 0) {
451 ma_semaphore_release(&audio->bufferSemaphore);
452 }
453
454 if (frameCount > 0) {
455 /* Overrun. Not enough room to move our input data into the buffer. */
456 ma_atomic_bool32_set(&audio->xrunDetected, MA_TRUE);
457 }
458 }
459
460 static void osaudio_nofication_callback(const ma_device_notification* pNotification)
461 {
462 osaudio_t audio = (osaudio_t)pNotification->pDevice->pUserData;
463
464 if (audio->config.notification != NULL) {
465 osaudio_notification_t notification;
466
467 switch (pNotification->type)
468 {
469 case ma_device_notification_type_started:
470 {
471 notification.type = OSAUDIO_NOTIFICATION_STARTED;
472 } break;
473 case ma_device_notification_type_stopped:
474 {
475 notification.type = OSAUDIO_NOTIFICATION_STOPPED;
476 } break;
477 case ma_device_notification_type_rerouted:
478 {
479 notification.type = OSAUDIO_NOTIFICATION_REROUTED;
480 } break;
481 case ma_device_notification_type_interruption_began:
482 {
483 notification.type = OSAUDIO_NOTIFICATION_INTERRUPTION_BEGIN;
484 } break;
485 case ma_device_notification_type_interruption_ended:
486 {
487 notification.type = OSAUDIO_NOTIFICATION_INTERRUPTION_END;
488 } break;
489 }
490
491 audio->config.notification(audio->config.user_data, &notification);
492 }
493 }
494
495 static void osaudio_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
496 {
497 osaudio_t audio = (osaudio_t)pDevice->pUserData;
498
499 if (audio->info.direction == OSAUDIO_OUTPUT) {
500 osaudio_data_callback_playback(audio, pOutput, frameCount);
501 } else {
502 osaudio_data_callback_capture(audio, pInput, frameCount);
503 }
504 }
505
506 osaudio_result_t osaudio_open(osaudio_t* audio, osaudio_config_t* config)
507 {
508 osaudio_result_t result;
509 ma_context* pContext = NULL;
510 ma_device_config deviceConfig;
511 ma_device_info deviceInfo;
512 int periodCount = 2;
513 unsigned int iChannel;
514
515 if (audio != NULL) {
516 *audio = NULL; /* Safety. */
517 }
518
519 if (audio == NULL || config == NULL) {
520 return OSAUDIO_INVALID_ARGS;
521 }
522
523 pContext = osaudio_ref_context(); /* Will be unreferenced in osaudio_close(). */
524 if (pContext == NULL) {
525 return OSAUDIO_ERROR;
526 }
527
528 *audio = (osaudio_t)calloc(1, sizeof(**audio));
529 if (*audio == NULL) {
530 osaudio_unref_context();
531 return OSAUDIO_OUT_OF_MEMORY;
532 }
533
534 if (config->direction == OSAUDIO_OUTPUT) {
535 deviceConfig = ma_device_config_init(ma_device_type_playback);
536 deviceConfig.playback.format = osaudio_format_to_miniaudio(config->format);
537 deviceConfig.playback.channels = (ma_uint32)config->channels;
538
539 if (config->channel_map[0] != OSAUDIO_CHANNEL_NONE) {
540 for (iChannel = 0; iChannel < config->channels; iChannel += 1) {
541 deviceConfig.playback.pChannelMap[iChannel] = osaudio_channel_to_miniaudio(config->channel_map[iChannel]);
542 }
543 }
544 } else {
545 deviceConfig = ma_device_config_init(ma_device_type_capture);
546 deviceConfig.capture.format = osaudio_format_to_miniaudio(config->format);
547 deviceConfig.capture.channels = (ma_uint32)config->channels;
548
549 if (config->channel_map[0] != OSAUDIO_CHANNEL_NONE) {
550 for (iChannel = 0; iChannel < config->channels; iChannel += 1) {
551 deviceConfig.capture.pChannelMap[iChannel] = osaudio_channel_to_miniaudio(config->channel_map[iChannel]);
552 }
553 }
554 }
555
556 deviceConfig.sampleRate = (ma_uint32)config->rate;
557
558 /* If the buffer size is 0, we'll default to 10ms. */
559 deviceConfig.periodSizeInFrames = (ma_uint32)config->buffer_size;
560 if (deviceConfig.periodSizeInFrames == 0) {
561 deviceConfig.periodSizeInMilliseconds = 10;
562 }
563
564 deviceConfig.dataCallback = osaudio_data_callback;
565 deviceConfig.pUserData = *audio;
566
567 if ((config->flags & OSAUDIO_FLAG_NO_REROUTING) != 0) {
568 deviceConfig.wasapi.noAutoStreamRouting = MA_TRUE;
569 }
570
571 if (config->notification != NULL) {
572 deviceConfig.notificationCallback = osaudio_nofication_callback;
573 }
574
575 result = osaudio_result_from_miniaudio(ma_device_init(pContext, &deviceConfig, &((*audio)->device)));
576 if (result != OSAUDIO_SUCCESS) {
577 free(*audio);
578 osaudio_unref_context();
579 return result;
580 }
581
582 /* The input config needs to be updated with actual values. */
583 if (config->direction == OSAUDIO_OUTPUT) {
584 config->format = osaudio_format_from_miniaudio((*audio)->device.playback.format);
585 config->channels = (unsigned int)(*audio)->device.playback.channels;
586
587 for (iChannel = 0; iChannel < config->channels; iChannel += 1) {
588 config->channel_map[iChannel] = osaudio_channel_from_miniaudio((*audio)->device.playback.channelMap[iChannel]);
589 }
590 } else {
591 config->format = osaudio_format_from_miniaudio((*audio)->device.capture.format);
592 config->channels = (unsigned int)(*audio)->device.capture.channels;
593
594 for (iChannel = 0; iChannel < config->channels; iChannel += 1) {
595 config->channel_map[iChannel] = osaudio_channel_from_miniaudio((*audio)->device.capture.channelMap[iChannel]);
596 }
597 }
598
599 config->rate = (unsigned int)(*audio)->device.sampleRate;
600
601 if (deviceConfig.periodSizeInFrames == 0) {
602 if (config->direction == OSAUDIO_OUTPUT) {
603 config->buffer_size = (int)(*audio)->device.playback.internalPeriodSizeInFrames;
604 } else {
605 config->buffer_size = (int)(*audio)->device.capture.internalPeriodSizeInFrames;
606 }
607 }
608
609
610 /* The device object needs to have its local info built. We can get the ID and name from miniaudio. */
611 result = osaudio_result_from_miniaudio(ma_device_get_info(&(*audio)->device, (*audio)->device.type, &deviceInfo));
612 if (result == MA_SUCCESS) {
613 memcpy((*audio)->info.id.data, &deviceInfo.id, sizeof((*audio)->info.id.data));
614 memcpy((*audio)->info.name, deviceInfo.name, sizeof((*audio)->info.name));
615 }
616
617 (*audio)->info.direction = config->direction;
618 (*audio)->info.config_count = 1;
619 (*audio)->info.configs = &(*audio)->config;
620 (*audio)->config = *config;
621 (*audio)->config.device_id = &(*audio)->info.id;
622
623
624 /* We need a ring buffer. */
625 result = osaudio_result_from_miniaudio(ma_pcm_rb_init(osaudio_format_to_miniaudio(config->format), (ma_uint32)config->channels, (ma_uint32)config->buffer_size * periodCount, NULL, NULL, &(*audio)->buffer));
626 if (result != OSAUDIO_SUCCESS) {
627 ma_device_uninit(&(*audio)->device);
628 free(*audio);
629 osaudio_unref_context();
630 return result;
631 }
632
633 /* Now we need a semaphore to control access to the ring buffer to block read/write when necessary. */
634 result = osaudio_result_from_miniaudio(ma_semaphore_init((config->direction == OSAUDIO_OUTPUT) ? periodCount : 0, &(*audio)->bufferSemaphore));
635 if (result != OSAUDIO_SUCCESS) {
636 ma_pcm_rb_uninit(&(*audio)->buffer);
637 ma_device_uninit(&(*audio)->device);
638 free(*audio);
639 osaudio_unref_context();
640 return result;
641 }
642
643 return OSAUDIO_SUCCESS;
644 }
645
646 osaudio_result_t osaudio_close(osaudio_t audio)
647 {
648 if (audio == NULL) {
649 return OSAUDIO_INVALID_ARGS;
650 }
651
652 ma_device_uninit(&audio->device);
653 osaudio_unref_context();
654
655 return OSAUDIO_SUCCESS;
656 }
657
658 static void osaudio_activate(osaudio_t audio)
659 {
660 ma_spinlock_lock(&audio->activateLock);
661 {
662 if (ma_atomic_bool32_get(&audio->isActive) == MA_FALSE) {
663 ma_atomic_bool32_set(&audio->isActive, MA_TRUE);
664
665 /* If we need to flush, do so now before starting the device. */
666 if (ma_atomic_bool32_get(&audio->isFlushed) == MA_TRUE) {
667 ma_pcm_rb_reset(&audio->buffer);
668 ma_atomic_bool32_set(&audio->isFlushed, MA_FALSE);
669 }
670
671 /* If we're not paused, start the device. */
672 if (ma_atomic_bool32_get(&audio->isPaused) == MA_FALSE) {
673 ma_device_start(&audio->device);
674 }
675 }
676 }
677 ma_spinlock_unlock(&audio->activateLock);
678 }
679
680 osaudio_result_t osaudio_write(osaudio_t audio, const void* data, unsigned int frame_count)
681 {
682 if (audio == NULL) {
683 return OSAUDIO_INVALID_ARGS;
684 }
685
686 ma_mutex_lock(&audio->drainLock);
687 {
688 /* Don't return until everything has been written. */
689 while (frame_count > 0) {
690 ma_uint32 framesToWrite = frame_count;
691 ma_uint32 framesAvailableInBuffer;
692
693 /* There should be enough data available in the buffer now, but check anyway. */
694 framesAvailableInBuffer = ma_pcm_rb_available_write(&audio->buffer);
695 if (framesAvailableInBuffer > 0) {
696 void* pBuffer;
697
698 if (framesToWrite > framesAvailableInBuffer) {
699 framesToWrite = framesAvailableInBuffer;
700 }
701
702 ma_pcm_rb_acquire_write(&audio->buffer, &framesToWrite, &pBuffer);
703 {
704 ma_copy_pcm_frames(pBuffer, data, framesToWrite, audio->device.playback.format, audio->device.playback.channels);
705 }
706 ma_pcm_rb_commit_write(&audio->buffer, framesToWrite);
707
708 frame_count -= (unsigned int)framesToWrite;
709 data = (const void*)((const unsigned char*)data + (framesToWrite * ma_get_bytes_per_frame(audio->device.playback.format, audio->device.playback.channels)));
710
711 if (framesToWrite > 0) {
712 osaudio_activate(audio);
713 }
714 } else {
715 /* If we get here it means there's not enough data available in the buffer. We need to wait for more. */
716 ma_semaphore_wait(&audio->bufferSemaphore);
717
718 /* If we're not active it probably means we've flushed. This write needs to be aborted. */
719 if (ma_atomic_bool32_get(&audio->isActive) == MA_FALSE) {
720 break;
721 }
722 }
723 }
724 }
725 ma_mutex_unlock(&audio->drainLock);
726
727 if ((audio->config.flags & OSAUDIO_FLAG_REPORT_XRUN) != 0) {
728 if (ma_atomic_bool32_get(&audio->xrunDetected)) {
729 ma_atomic_bool32_set(&audio->xrunDetected, MA_FALSE);
730 return OSAUDIO_XRUN;
731 }
732 }
733
734 return OSAUDIO_SUCCESS;
735 }
736
737 osaudio_result_t osaudio_read(osaudio_t audio, void* data, unsigned int frame_count)
738 {
739 if (audio == NULL) {
740 return OSAUDIO_INVALID_ARGS;
741 }
742
743 ma_mutex_lock(&audio->drainLock);
744 {
745 while (frame_count > 0) {
746 ma_uint32 framesToRead = frame_count;
747 ma_uint32 framesAvailableInBuffer;
748
749 /* There should be enough data available in the buffer now, but check anyway. */
750 framesAvailableInBuffer = ma_pcm_rb_available_read(&audio->buffer);
751 if (framesAvailableInBuffer > 0) {
752 void* pBuffer;
753
754 if (framesToRead > framesAvailableInBuffer) {
755 framesToRead = framesAvailableInBuffer;
756 }
757
758 ma_pcm_rb_acquire_read(&audio->buffer, &framesToRead, &pBuffer);
759 {
760 ma_copy_pcm_frames(data, pBuffer, framesToRead, audio->device.capture.format, audio->device.capture.channels);
761 }
762 ma_pcm_rb_commit_read(&audio->buffer, framesToRead);
763
764 frame_count -= (unsigned int)framesToRead;
765 data = (void*)((unsigned char*)data + (framesToRead * ma_get_bytes_per_frame(audio->device.capture.format, audio->device.capture.channels)));
766 } else {
767 /* Activate the device from the get go or else we'll never end up capturing anything. */
768 osaudio_activate(audio);
769
770 /* If we get here it means there's not enough data available in the buffer. We need to wait for more. */
771 ma_semaphore_wait(&audio->bufferSemaphore);
772
773 /* If we're not active it probably means we've flushed. This read needs to be aborted. */
774 if (ma_atomic_bool32_get(&audio->isActive) == MA_FALSE) {
775 break;
776 }
777 }
778 }
779 }
780 ma_mutex_unlock(&audio->drainLock);
781
782 if ((audio->config.flags & OSAUDIO_FLAG_REPORT_XRUN) != 0) {
783 if (ma_atomic_bool32_get(&audio->xrunDetected)) {
784 ma_atomic_bool32_set(&audio->xrunDetected, MA_FALSE);
785 return OSAUDIO_XRUN;
786 }
787 }
788
789 return OSAUDIO_SUCCESS;
790 }
791
792 osaudio_result_t osaudio_drain(osaudio_t audio)
793 {
794 if (audio == NULL) {
795 return OSAUDIO_INVALID_ARGS;
796 }
797
798 /* This cannot be called while the device is in a paused state. */
799 if (ma_atomic_bool32_get(&audio->isPaused)) {
800 return OSAUDIO_DEVICE_STOPPED;
801 }
802
803 /* For capture we want to stop the device immediately or else we won't ever drain the buffer because miniaudio will be constantly filling it. */
804 if (audio->info.direction == OSAUDIO_INPUT) {
805 ma_device_stop(&audio->device);
806 }
807
808 /*
809 Mark the device as inactive *before* releasing the semaphore. When read/write completes waiting
810 on the semaphore, they'll check this flag and abort.
811 */
812 ma_atomic_bool32_set(&audio->isActive, MA_FALSE);
813
814 /*
815 Again in capture mode, we need to release the semaphore before waiting for the drain lock because
816 there's a chance read() will be waiting on the semaphore and will need to be woken up in order for
817 it to be given to chance to return.
818 */
819 if (audio->info.direction == OSAUDIO_INPUT) {
820 ma_semaphore_release(&audio->bufferSemaphore);
821 }
822
823 /* Now we need to wait for any pending reads or writes to complete. */
824 ma_mutex_lock(&audio->drainLock);
825 {
826 /* No processing should be happening on the buffer at this point. Wait for miniaudio to consume the buffer. */
827 while (ma_pcm_rb_available_read(&audio->buffer) > 0) {
828 ma_sleep(1);
829 }
830
831 /*
832 At this point the buffer should be empty, and we shouldn't be in any read or write calls. If
833 it's a playback device, we'll want to stop the device. There's no need to release the semaphore.
834 */
835 if (audio->info.direction == OSAUDIO_OUTPUT) {
836 ma_device_stop(&audio->device);
837 }
838 }
839 ma_mutex_unlock(&audio->drainLock);
840
841 return OSAUDIO_SUCCESS;
842 }
843
844 osaudio_result_t osaudio_flush(osaudio_t audio)
845 {
846 if (audio == NULL) {
847 return OSAUDIO_INVALID_ARGS;
848 }
849
850 /*
851 First stop the device. This ensures the miniaudio background thread doesn't try modifying the
852 buffer from under us while we're trying to flush it.
853 */
854 ma_device_stop(&audio->device);
855
856 /*
857 Mark the device as inactive *before* releasing the semaphore. When read/write completes waiting
858 on the semaphore, they'll check this flag and abort.
859 */
860 ma_atomic_bool32_set(&audio->isActive, MA_FALSE);
861
862 /*
863 Release the semaphore after marking the device as inactive. This needs to be released in order
864 to wakeup osaudio_read() and osaudio_write().
865 */
866 ma_semaphore_release(&audio->bufferSemaphore);
867
868 /*
869 The buffer should only be modified by osaudio_read() or osaudio_write(), or the miniaudio
870 background thread. Therefore, we don't actually clear the buffer here. Instead we'll clear it
871 in osaudio_activate(), depending on whether or not the below flag is set.
872 */
873 ma_atomic_bool32_set(&audio->isFlushed, MA_TRUE);
874
875 return OSAUDIO_SUCCESS;
876 }
877
878 osaudio_result_t osaudio_pause(osaudio_t audio)
879 {
880 osaudio_result_t result = OSAUDIO_SUCCESS;
881
882 if (audio == NULL) {
883 return OSAUDIO_INVALID_ARGS;
884 }
885
886 ma_spinlock_lock(&audio->activateLock);
887 {
888 if (ma_atomic_bool32_get(&audio->isPaused) == MA_FALSE) {
889 ma_atomic_bool32_set(&audio->isPaused, MA_TRUE);
890
891 /* No need to stop the device if it's not active. */
892 if (ma_atomic_bool32_get(&audio->isActive)) {
893 result = osaudio_result_from_miniaudio(ma_device_stop(&audio->device));
894 }
895 }
896 }
897 ma_spinlock_unlock(&audio->activateLock);
898
899 return result;
900 }
901
902 osaudio_result_t osaudio_resume(osaudio_t audio)
903 {
904 osaudio_result_t result = OSAUDIO_SUCCESS;
905
906 if (audio == NULL) {
907 return OSAUDIO_INVALID_ARGS;
908 }
909
910 ma_spinlock_lock(&audio->activateLock);
911 {
912 if (ma_atomic_bool32_get(&audio->isPaused)) {
913 ma_atomic_bool32_set(&audio->isPaused, MA_FALSE);
914
915 /* Don't start the device unless it's active. */
916 if (ma_atomic_bool32_get(&audio->isActive)) {
917 result = osaudio_result_from_miniaudio(ma_device_start(&audio->device));
918 }
919 }
920 }
921 ma_spinlock_unlock(&audio->activateLock);
922
923 return result;
924 }
925
926 unsigned int osaudio_get_avail(osaudio_t audio)
927 {
928 if (audio == NULL) {
929 return 0;
930 }
931
932 if (audio->info.direction == OSAUDIO_OUTPUT) {
933 return ma_pcm_rb_available_write(&audio->buffer);
934 } else {
935 return ma_pcm_rb_available_read(&audio->buffer);
936 }
937 }
938
939 const osaudio_info_t* osaudio_get_info(osaudio_t audio)
940 {
941 if (audio == NULL) {
942 return NULL;
943 }
944
945 return &audio->info;
946 }
947
948 #endif /* osaudio_miniaudio_c */