Debian Codegraph @

sokol/sokol_audio.h

raw symbols SCIP
1 #if defined(SOKOL_IMPL) && !defined(SOKOL_AUDIO_IMPL)
2 #define SOKOL_AUDIO_IMPL
3 #endif
4 #ifndef SOKOL_AUDIO_INCLUDED
5 /*
6 sokol_audio.h -- cross-platform audio-streaming API
7
8 Project URL: https://github.com/floooh/sokol
9
10 Do this:
11 #define SOKOL_IMPL or
12 #define SOKOL_AUDIO_IMPL
13 before you include this file in *one* C or C++ file to create the
14 implementation.
15
16 Optionally provide the following defines with your own implementations:
17
18 SOKOL_DUMMY_BACKEND - use a dummy backend
19 SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
20 SOKOL_AUDIO_API_DECL- public function declaration prefix (default: extern)
21 SOKOL_API_DECL - same as SOKOL_AUDIO_API_DECL
22 SOKOL_API_IMPL - public function implementation prefix (default: -)
23
24 SAUDIO_RING_MAX_SLOTS - max number of slots in the push-audio ring buffer (default 1024)
25 SAUDIO_OSX_USE_SYSTEM_HEADERS - define this to force inclusion of system headers on
26 macOS instead of using embedded CoreAudio declarations
27 SAUDIO_ANDROID_AAUDIO - on Android, select the AAudio backend (default)
28 SAUDIO_ANDROID_SLES - on Android, select the OpenSLES backend
29
30 If sokol_audio.h is compiled as a DLL, define the following before
31 including the declaration or implementation:
32
33 SOKOL_DLL
34
35 On Windows, SOKOL_DLL will define SOKOL_AUDIO_API_DECL as __declspec(dllexport)
36 or __declspec(dllimport) as needed.
37
38 Link with the following libraries:
39
40 - on macOS: AudioToolbox
41 - on iOS: AudioToolbox, AVFoundation
42 - on Linux: asound
43 - on Android: link with OpenSLES or aaudio
44 - on Windows with MSVC or Clang toolchain: no action needed, libs are defined in-source via pragma-comment-lib
45 - on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' and link with -lole32
46
47 FEATURE OVERVIEW
48 ================
49 You provide a mono- or stereo-stream of 32-bit float samples, which
50 Sokol Audio feeds into platform-specific audio backends:
51
52 - Windows: WASAPI
53 - Linux: ALSA
54 - macOS: CoreAudio
55 - iOS: CoreAudio+AVAudioSession
56 - emscripten: WebAudio with ScriptProcessorNode
57 - Android: AAudio (default) or OpenSLES, select at build time
58
59 Sokol Audio will not do any buffer mixing or volume control, if you have
60 multiple independent input streams of sample data you need to perform the
61 mixing yourself before forwarding the data to Sokol Audio.
62
63 There are two mutually exclusive ways to provide the sample data:
64
65 1. Callback model: You provide a callback function, which will be called
66 when Sokol Audio needs new samples. On all platforms except emscripten,
67 this function is called from a separate thread.
68 2. Push model: Your code pushes small blocks of sample data from your
69 main loop or a thread you created. The pushed data is stored in
70 a ring buffer where it is pulled by the backend code when
71 needed.
72
73 The callback model is preferred because it is the most direct way to
74 feed sample data into the audio backends and also has less moving parts
75 (there is no ring buffer between your code and the audio backend).
76
77 Sometimes it is not possible to generate the audio stream directly in a
78 callback function running in a separate thread, for such cases Sokol Audio
79 provides the push-model as a convenience.
80
81 SOKOL AUDIO, SOLOUD AND MINIAUDIO
82 =================================
83 The WASAPI, ALSA, OpenSLES and CoreAudio backend code has been taken from the
84 SoLoud library (with some modifications, so any bugs in there are most
85 likely my fault). If you need a more fully-featured audio solution, check
86 out SoLoud, it's excellent:
87
88 https://github.com/jarikomppa/soloud
89
90 Another alternative which feature-wise is somewhere inbetween SoLoud and
91 sokol-audio might be MiniAudio:
92
93 https://github.com/mackron/miniaudio
94
95 GLOSSARY
96 ========
97 - stream buffer:
98 The internal audio data buffer, usually provided by the backend API. The
99 size of the stream buffer defines the base latency, smaller buffers have
100 lower latency but may cause audio glitches. Bigger buffers reduce or
101 eliminate glitches, but have a higher base latency.
102
103 - stream callback:
104 Optional callback function which is called by Sokol Audio when it
105 needs new samples. On Windows, macOS/iOS and Linux, this is called in
106 a separate thread, on WebAudio, this is called per-frame in the
107 browser thread.
108
109 - channel:
110 A discrete track of audio data, currently 1-channel (mono) and
111 2-channel (stereo) is supported and tested.
112
113 - sample:
114 The magnitude of an audio signal on one channel at a given time. In
115 Sokol Audio, samples are 32-bit float numbers in the range -1.0 to
116 +1.0.
117
118 - frame:
119 The tightly packed set of samples for all channels at a given time.
120 For mono 1 frame is 1 sample. For stereo, 1 frame is 2 samples.
121
122 - packet:
123 In Sokol Audio, a small chunk of audio data that is moved from the
124 main thread to the audio streaming thread in order to decouple the
125 rate at which the main thread provides new audio data, and the
126 streaming thread consuming audio data.
127
128 WORKING WITH SOKOL AUDIO
129 ========================
130 First call saudio_setup() with your preferred audio playback options.
131 In most cases you can stick with the default values, these provide
132 a good balance between low-latency and glitch-free playback
133 on all audio backends.
134
135 You should always provide a logging callback to be aware of any
136 warnings and errors. The easiest way is to use sokol_log.h for this:
137
138 #include "sokol_log.h"
139 // ...
140 saudio_setup(&(saudio_desc){
141 .logger = {
142 .func = slog_func,
143 }
144 });
145
146 If you want to use the callback-model, you need to provide a stream
147 callback function either in saudio_desc.stream_cb or saudio_desc.stream_userdata_cb,
148 otherwise keep both function pointers zero-initialized.
149
150 Use push model and default playback parameters:
151
152 saudio_setup(&(saudio_desc){ .logger.func = slog_func });
153
154 Use stream callback model and default playback parameters:
155
156 saudio_setup(&(saudio_desc){
157 .stream_cb = my_stream_callback
158 .logger.func = slog_func,
159 });
160
161 The standard stream callback doesn't have a user data argument, if you want
162 that, use the alternative stream_userdata_cb and also set the user_data pointer:
163
164 saudio_setup(&(saudio_desc){
165 .stream_userdata_cb = my_stream_callback,
166 .user_data = &my_data
167 .logger.func = slog_func,
168 });
169
170 The following playback parameters can be provided through the
171 saudio_desc struct:
172
173 General parameters (both for stream-callback and push-model):
174
175 int sample_rate -- the sample rate in Hz, default: 44100
176 int num_channels -- number of channels, default: 1 (mono)
177 int buffer_frames -- number of frames in streaming buffer, default: 2048
178
179 The stream callback prototype (either with or without userdata):
180
181 void (*stream_cb)(float* buffer, int num_frames, int num_channels)
182 void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data)
183 Function pointer to the user-provide stream callback.
184
185 Push-model parameters:
186
187 int packet_frames -- number of frames in a packet, default: 128
188 int num_packets -- number of packets in ring buffer, default: 64
189
190 The sample_rate and num_channels parameters are only hints for the audio
191 backend, it isn't guaranteed that those are the values used for actual
192 playback.
193
194 To get the actual parameters, call the following functions after
195 saudio_setup():
196
197 int saudio_sample_rate(void)
198 int saudio_channels(void);
199
200 It's unlikely that the number of channels will be different than requested,
201 but a different sample rate isn't uncommon.
202
203 (NOTE: there's an yet unsolved issue when an audio backend might switch
204 to a different sample rate when switching output devices, for instance
205 plugging in a bluetooth headset, this case is currently not handled in
206 Sokol Audio).
207
208 You can check if audio initialization was successful with
209 saudio_isvalid(). If backend initialization failed for some reason
210 (for instance when there's no audio device in the machine), this
211 will return false. Not checking for success won't do any harm, all
212 Sokol Audio function will silently fail when called after initialization
213 has failed, so apart from missing audio output, nothing bad will happen.
214
215 Before your application exits, you should call
216
217 saudio_shutdown();
218
219 This stops the audio thread (on Linux, Windows and macOS/iOS) and
220 properly shuts down the audio backend.
221
222 THE STREAM CALLBACK MODEL
223 =========================
224 To use Sokol Audio in stream-callback-mode, provide a callback function
225 like this in the saudio_desc struct when calling saudio_setup():
226
227 void stream_cb(float* buffer, int num_frames, int num_channels) {
228 ...
229 }
230
231 Or the alternative version with a user-data argument:
232
233 void stream_userdata_cb(float* buffer, int num_frames, int num_channels, void* user_data) {
234 my_data_t* my_data = (my_data_t*) user_data;
235 ...
236 }
237
238 The job of the callback function is to fill the *buffer* with 32-bit
239 float sample values.
240
241 To output silence, fill the buffer with zeros:
242
243 void stream_cb(float* buffer, int num_frames, int num_channels) {
244 const int num_samples = num_frames * num_channels;
245 for (int i = 0; i < num_samples; i++) {
246 buffer[i] = 0.0f;
247 }
248 }
249
250 For stereo output (num_channels == 2), the samples for the left
251 and right channel are interleaved:
252
253 void stream_cb(float* buffer, int num_frames, int num_channels) {
254 assert(2 == num_channels);
255 for (int i = 0; i < num_frames; i++) {
256 buffer[2*i + 0] = ...; // left channel
257 buffer[2*i + 1] = ...; // right channel
258 }
259 }
260
261 Please keep in mind that the stream callback function is running in a
262 separate thread, if you need to share data with the main thread you need
263 to take care yourself to make the access to the shared data thread-safe!
264
265 THE PUSH MODEL
266 ==============
267 To use the push-model for providing audio data, simply don't set (keep
268 zero-initialized) the stream_cb field in the saudio_desc struct when
269 calling saudio_setup().
270
271 To provide sample data with the push model, call the saudio_push()
272 function at regular intervals (for instance once per frame). You can
273 call the saudio_expect() function to ask Sokol Audio how much room is
274 in the ring buffer, but if you provide a continuous stream of data
275 at the right sample rate, saudio_expect() isn't required (it's a simple
276 way to sync/throttle your sample generation code with the playback
277 rate though).
278
279 With saudio_push() you may need to maintain your own intermediate sample
280 buffer, since pushing individual sample values isn't very efficient.
281 The following example is from the MOD player sample in
282 sokol-samples (https://github.com/floooh/sokol-samples):
283
284 const int num_frames = saudio_expect();
285 if (num_frames > 0) {
286 const int num_samples = num_frames * saudio_channels();
287 read_samples(flt_buf, num_samples);
288 saudio_push(flt_buf, num_frames);
289 }
290
291 Another option is to ignore saudio_expect(), and just push samples as they
292 are generated in small batches. In this case you *need* to generate the
293 samples at the right sample rate:
294
295 The following example is taken from the Tiny Emulators project
296 (https://github.com/floooh/chips-test), this is for mono playback,
297 so (num_samples == num_frames):
298
299 // tick the sound generator
300 if (ay38910_tick(&sys->psg)) {
301 // new sample is ready
302 sys->sample_buffer[sys->sample_pos++] = sys->psg.sample;
303 if (sys->sample_pos == sys->num_samples) {
304 // new sample packet is ready
305 saudio_push(sys->sample_buffer, sys->num_samples);
306 sys->sample_pos = 0;
307 }
308 }
309
310 THE WEBAUDIO BACKEND
311 ====================
312 The WebAudio backend is currently using a ScriptProcessorNode callback to
313 feed the sample data into WebAudio. ScriptProcessorNode has been
314 deprecated for a while because it is running from the main thread, with
315 the default initialization parameters it works 'pretty well' though.
316 Ultimately Sokol Audio will use Audio Worklets, but this requires a few
317 more things to fall into place (Audio Worklets implemented everywhere,
318 SharedArrayBuffers enabled again, and I need to figure out a 'low-cost'
319 solution in terms of implementation effort, since Audio Worklets are
320 a lot more complex than ScriptProcessorNode if the audio data needs to come
321 from the main thread).
322
323 The WebAudio backend is automatically selected when compiling for
324 emscripten (__EMSCRIPTEN__ define exists).
325
326 https://developers.google.com/web/updates/2017/12/audio-worklet
327 https://developers.google.com/web/updates/2018/06/audio-worklet-design-pattern
328
329 "Blob URLs": https://www.html5rocks.com/en/tutorials/workers/basics/
330
331 Also see: https://blog.paul.cx/post/a-wait-free-spsc-ringbuffer-for-the-web/
332
333 THE COREAUDIO BACKEND
334 =====================
335 The CoreAudio backend is selected on macOS and iOS (__APPLE__ is defined).
336 Since the CoreAudio API is implemented in C (not Objective-C) on macOS the
337 implementation part of Sokol Audio can be included into a C source file.
338
339 However on iOS, Sokol Audio must be compiled as Objective-C due to it's
340 reliance on the AVAudioSession object. The iOS code path support both
341 being compiled with or without ARC (Automatic Reference Counting).
342
343 For thread synchronisation, the CoreAudio backend will use the
344 pthread_mutex_* functions.
345
346 The incoming floating point samples will be directly forwarded to
347 CoreAudio without further conversion.
348
349 macOS and iOS applications that use Sokol Audio need to link with
350 the AudioToolbox framework.
351
352 THE WASAPI BACKEND
353 ==================
354 The WASAPI backend is automatically selected when compiling on Windows
355 (_WIN32 is defined).
356
357 For thread synchronisation a Win32 critical section is used.
358
359 WASAPI may use a different size for its own streaming buffer then requested,
360 so the base latency may be slightly bigger. The current backend implementation
361 converts the incoming floating point sample values to signed 16-bit
362 integers.
363
364 The required Windows system DLLs are linked with #pragma comment(lib, ...),
365 so you shouldn't need to add additional linker libs in the build process
366 (otherwise this is a bug which should be fixed in sokol_audio.h).
367
368 THE ALSA BACKEND
369 ================
370 The ALSA backend is automatically selected when compiling on Linux
371 ('linux' is defined).
372
373 For thread synchronisation, the pthread_mutex_* functions are used.
374
375 Samples are directly forwarded to ALSA in 32-bit float format, no
376 further conversion is taking place.
377
378 You need to link with the 'asound' library, and the <alsa/asoundlib.h>
379 header must be present (usually both are installed with some sort
380 of ALSA development package).
381
382
383 MEMORY ALLOCATION OVERRIDE
384 ==========================
385 You can override the memory allocation functions at initialization time
386 like this:
387
388 void* my_alloc(size_t size, void* user_data) {
389 return malloc(size);
390 }
391
392 void my_free(void* ptr, void* user_data) {
393 free(ptr);
394 }
395
396 ...
397 saudio_setup(&(saudio_desc){
398 // ...
399 .allocator = {
400 .alloc_fn = my_alloc,
401 .free_fn = my_free,
402 .user_data = ...,
403 }
404 });
405 ...
406
407 If no overrides are provided, malloc and free will be used.
408
409 This only affects memory allocation calls done by sokol_audio.h
410 itself though, not any allocations in OS libraries.
411
412 Memory allocation will only happen on the same thread where saudio_setup()
413 was called, so you don't need to worry about thread-safety.
414
415
416 ERROR REPORTING AND LOGGING
417 ===========================
418 To get any logging information at all you need to provide a logging callback in the setup call
419 the easiest way is to use sokol_log.h:
420
421 #include "sokol_log.h"
422
423 saudio_setup(&(saudio_desc){ .logger.func = slog_func });
424
425 To override logging with your own callback, first write a logging function like this:
426
427 void my_log(const char* tag, // e.g. 'saudio'
428 uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
429 uint32_t log_item_id, // SAUDIO_LOGITEM_*
430 const char* message_or_null, // a message string, may be nullptr in release mode
431 uint32_t line_nr, // line number in sokol_audio.h
432 const char* filename_or_null, // source filename, may be nullptr in release mode
433 void* user_data)
434 {
435 ...
436 }
437
438 ...and then setup sokol-audio like this:
439
440 saudio_setup(&(saudio_desc){
441 .logger = {
442 .func = my_log,
443 .user_data = my_user_data,
444 }
445 });
446
447 The provided logging function must be reentrant (e.g. be callable from
448 different threads).
449
450 If you don't want to provide your own custom logger it is highly recommended to use
451 the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
452 errors.
453
454 LICENSE
455 =======
456
457 zlib/libpng license
458
459 Copyright (c) 2018 Andre Weissflog
460
461 This software is provided 'as-is', without any express or implied warranty.
462 In no event will the authors be held liable for any damages arising from the
463 use of this software.
464
465 Permission is granted to anyone to use this software for any purpose,
466 including commercial applications, and to alter it and redistribute it
467 freely, subject to the following restrictions:
468
469 1. The origin of this software must not be misrepresented; you must not
470 claim that you wrote the original software. If you use this software in a
471 product, an acknowledgment in the product documentation would be
472 appreciated but is not required.
473
474 2. Altered source versions must be plainly marked as such, and must not
475 be misrepresented as being the original software.
476
477 3. This notice may not be removed or altered from any source
478 distribution.
479 */
480 #define SOKOL_AUDIO_INCLUDED (1)
481 #include <stddef.h> // size_t
482 #include <stdint.h>
483 #include <stdbool.h>
484
485 #if defined(SOKOL_API_DECL) && !defined(SOKOL_AUDIO_API_DECL)
486 #define SOKOL_AUDIO_API_DECL SOKOL_API_DECL
487 #endif
488 #ifndef SOKOL_AUDIO_API_DECL
489 #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_AUDIO_IMPL)
490 #define SOKOL_AUDIO_API_DECL __declspec(dllexport)
491 #elif defined(_WIN32) && defined(SOKOL_DLL)
492 #define SOKOL_AUDIO_API_DECL __declspec(dllimport)
493 #else
494 #define SOKOL_AUDIO_API_DECL extern
495 #endif
496 #endif
497
498 #ifdef __cplusplus
499 extern "C" {
500 #endif
501
502 /*
503 saudio_log_item
504
505 Log items are defined via X-Macros, and expanded to an
506 enum 'saudio_log_item', and in debug mode only,
507 corresponding strings.
508
509 Used as parameter in the logging callback.
510 */
511 #define _SAUDIO_LOG_ITEMS \
512 _SAUDIO_LOGITEM_XMACRO(OK, "Ok") \
513 _SAUDIO_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
514 _SAUDIO_LOGITEM_XMACRO(ALSA_SND_PCM_OPEN_FAILED, "snd_pcm_open() failed") \
515 _SAUDIO_LOGITEM_XMACRO(ALSA_FLOAT_SAMPLES_NOT_SUPPORTED, "floating point sample format not supported") \
516 _SAUDIO_LOGITEM_XMACRO(ALSA_REQUESTED_BUFFER_SIZE_NOT_SUPPORTED, "requested buffer size not supported") \
517 _SAUDIO_LOGITEM_XMACRO(ALSA_REQUESTED_CHANNEL_COUNT_NOT_SUPPORTED, "requested channel count not supported") \
518 _SAUDIO_LOGITEM_XMACRO(ALSA_SND_PCM_HW_PARAMS_SET_RATE_NEAR_FAILED, "snd_pcm_hw_params_set_rate_near() failed") \
519 _SAUDIO_LOGITEM_XMACRO(ALSA_SND_PCM_HW_PARAMS_FAILED, "snd_pcm_hw_params() failed") \
520 _SAUDIO_LOGITEM_XMACRO(ALSA_PTHREAD_CREATE_FAILED, "pthread_create() failed") \
521 _SAUDIO_LOGITEM_XMACRO(WASAPI_CREATE_EVENT_FAILED, "CreateEvent() failed") \
522 _SAUDIO_LOGITEM_XMACRO(WASAPI_CREATE_DEVICE_ENUMERATOR_FAILED, "CoCreateInstance() for IMMDeviceEnumerator failed") \
523 _SAUDIO_LOGITEM_XMACRO(WASAPI_GET_DEFAULT_AUDIO_ENDPOINT_FAILED, "IMMDeviceEnumerator.GetDefaultAudioEndpoint() failed") \
524 _SAUDIO_LOGITEM_XMACRO(WASAPI_DEVICE_ACTIVATE_FAILED, "IMMDevice.Activate() failed") \
525 _SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_INITIALIZE_FAILED, "IAudioClient.Initialize() failed") \
526 _SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_GET_BUFFER_SIZE_FAILED, "IAudioClient.GetBufferSize() failed") \
527 _SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_GET_SERVICE_FAILED, "IAudioClient.GetService() failed") \
528 _SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_SET_EVENT_HANDLE_FAILED, "IAudioClient.SetEventHandle() failed") \
529 _SAUDIO_LOGITEM_XMACRO(WASAPI_CREATE_THREAD_FAILED, "CreateThread() failed") \
530 _SAUDIO_LOGITEM_XMACRO(AAUDIO_STREAMBUILDER_OPEN_STREAM_FAILED, "AAudioStreamBuilder_openStream() failed") \
531 _SAUDIO_LOGITEM_XMACRO(AAUDIO_PTHREAD_CREATE_FAILED, "pthread_create() failed after AAUDIO_ERROR_DISCONNECTED") \
532 _SAUDIO_LOGITEM_XMACRO(AAUDIO_RESTARTING_STREAM_AFTER_ERROR, "restarting AAudio stream after error") \
533 _SAUDIO_LOGITEM_XMACRO(USING_AAUDIO_BACKEND, "using AAudio backend") \
534 _SAUDIO_LOGITEM_XMACRO(AAUDIO_CREATE_STREAMBUILDER_FAILED, "AAudio_createStreamBuilder() failed") \
535 _SAUDIO_LOGITEM_XMACRO(USING_SLES_BACKEND, "using OpenSLES backend") \
536 _SAUDIO_LOGITEM_XMACRO(SLES_CREATE_ENGINE_FAILED, "slCreateEngine() failed") \
537 _SAUDIO_LOGITEM_XMACRO(SLES_ENGINE_GET_ENGINE_INTERFACE_FAILED, "GetInterface() for SL_IID_ENGINE failed") \
538 _SAUDIO_LOGITEM_XMACRO(SLES_CREATE_OUTPUT_MIX_FAILED, "CreateOutputMix() failed") \
539 _SAUDIO_LOGITEM_XMACRO(SLES_MIXER_GET_VOLUME_INTERFACE_FAILED, "GetInterface() for SL_IID_VOLUME failed") \
540 _SAUDIO_LOGITEM_XMACRO(SLES_ENGINE_CREATE_AUDIO_PLAYER_FAILED, "CreateAudioPlayer() failed") \
541 _SAUDIO_LOGITEM_XMACRO(SLES_PLAYER_GET_PLAY_INTERFACE_FAILED, "GetInterface() for SL_IID_PLAY failed") \
542 _SAUDIO_LOGITEM_XMACRO(SLES_PLAYER_GET_VOLUME_INTERFACE_FAILED, "GetInterface() for SL_IID_VOLUME failed") \
543 _SAUDIO_LOGITEM_XMACRO(SLES_PLAYER_GET_BUFFERQUEUE_INTERFACE_FAILED, "GetInterface() for SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed") \
544 _SAUDIO_LOGITEM_XMACRO(COREAUDIO_NEW_OUTPUT_FAILED, "AudioQueueNewOutput() failed") \
545 _SAUDIO_LOGITEM_XMACRO(COREAUDIO_ALLOCATE_BUFFER_FAILED, "AudioQueueAllocateBuffer() failed") \
546 _SAUDIO_LOGITEM_XMACRO(COREAUDIO_START_FAILED, "AudioQueueStart() failed") \
547 _SAUDIO_LOGITEM_XMACRO(BACKEND_BUFFER_SIZE_ISNT_MULTIPLE_OF_PACKET_SIZE, "backend buffer size isn't multiple of packet size") \
548
549 #define _SAUDIO_LOGITEM_XMACRO(item,msg) SAUDIO_LOGITEM_##item,
550 typedef enum saudio_log_item {
551 _SAUDIO_LOG_ITEMS
552 } saudio_log_item;
553 #undef _SAUDIO_LOGITEM_XMACRO
554
555 /*
556 saudio_logger
557
558 Used in saudio_desc to provide a custom logging and error reporting
559 callback to sokol-audio.
560 */
561 typedef struct saudio_logger {
562 void (*func)(
563 const char* tag, // always "saudio"
564 uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
565 uint32_t log_item_id, // SAUDIO_LOGITEM_*
566 const char* message_or_null, // a message string, may be nullptr in release mode
567 uint32_t line_nr, // line number in sokol_audio.h
568 const char* filename_or_null, // source filename, may be nullptr in release mode
569 void* user_data);
570 void* user_data;
571 } saudio_logger;
572
573 /*
574 saudio_allocator
575
576 Used in saudio_desc to provide custom memory-alloc and -free functions
577 to sokol_audio.h. If memory management should be overridden, both the
578 alloc_fn and free_fn function must be provided (e.g. it's not valid to
579 override one function but not the other).
580 */
581 typedef struct saudio_allocator {
582 void* (*alloc_fn)(size_t size, void* user_data);
583 void (*free_fn)(void* ptr, void* user_data);
584 void* user_data;
585 } saudio_allocator;
586
587 typedef struct saudio_desc {
588 int sample_rate; // requested sample rate
589 int num_channels; // number of channels, default: 1 (mono)
590 int buffer_frames; // number of frames in streaming buffer
591 int packet_frames; // number of frames in a packet
592 int num_packets; // number of packets in packet queue
593 void (*stream_cb)(float* buffer, int num_frames, int num_channels); // optional streaming callback (no user data)
594 void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data); //... and with user data
595 void* user_data; // optional user data argument for stream_userdata_cb
596 saudio_allocator allocator; // optional allocation override functions
597 saudio_logger logger; // optional logging function (default: NO LOGGING!)
598 } saudio_desc;
599
600 /* setup sokol-audio */
601 SOKOL_AUDIO_API_DECL void saudio_setup(const saudio_desc* desc);
602 /* shutdown sokol-audio */
603 SOKOL_AUDIO_API_DECL void saudio_shutdown(void);
604 /* true after setup if audio backend was successfully initialized */
605 SOKOL_AUDIO_API_DECL bool saudio_isvalid(void);
606 /* return the saudio_desc.user_data pointer */
607 SOKOL_AUDIO_API_DECL void* saudio_userdata(void);
608 /* return a copy of the original saudio_desc struct */
609 SOKOL_AUDIO_API_DECL saudio_desc saudio_query_desc(void);
610 /* actual sample rate */
611 SOKOL_AUDIO_API_DECL int saudio_sample_rate(void);
612 /* return actual backend buffer size in number of frames */
613 SOKOL_AUDIO_API_DECL int saudio_buffer_frames(void);
614 /* actual number of channels */
615 SOKOL_AUDIO_API_DECL int saudio_channels(void);
616 /* return true if audio context is currently suspended (only in WebAudio backend, all other backends return false) */
617 SOKOL_AUDIO_API_DECL bool saudio_suspended(void);
618 /* get current number of frames to fill packet queue */
619 SOKOL_AUDIO_API_DECL int saudio_expect(void);
620 /* push sample frames from main thread, returns number of frames actually pushed */
621 SOKOL_AUDIO_API_DECL int saudio_push(const float* frames, int num_frames);
622
623 #ifdef __cplusplus
624 } /* extern "C" */
625
626 /* reference-based equivalents for c++ */
627 inline void saudio_setup(const saudio_desc& desc) { return saudio_setup(&desc); }
628
629 #endif
630 #endif // SOKOL_AUDIO_INCLUDED
631
632 // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
633 // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
634 // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
635 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
636 // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
637 //
638 // >>implementation
639 #ifdef SOKOL_AUDIO_IMPL
640 #define SOKOL_AUDIO_IMPL_INCLUDED (1)
641
642 #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
643 #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use saudio_desc.allocator to override memory allocation functions"
644 #endif
645
646 #include <stdlib.h> // alloc, free
647 #include <string.h> // memset, memcpy
648 #include <stddef.h> // size_t
649
650 #ifndef SOKOL_API_IMPL
651 #define SOKOL_API_IMPL
652 #endif
653 #ifndef SOKOL_DEBUG
654 #ifndef NDEBUG
655 #define SOKOL_DEBUG
656 #endif
657 #endif
658 #ifndef SOKOL_ASSERT
659 #include <assert.h>
660 #define SOKOL_ASSERT(c) assert(c)
661 #endif
662
663 #ifndef _SOKOL_PRIVATE
664 #if defined(__GNUC__) || defined(__clang__)
665 #define _SOKOL_PRIVATE __attribute__((unused)) static
666 #else
667 #define _SOKOL_PRIVATE static
668 #endif
669 #endif
670
671 #ifndef _SOKOL_UNUSED
672 #define _SOKOL_UNUSED(x) (void)(x)
673 #endif
674
675 // platform detection defines
676 #if defined(SOKOL_DUMMY_BACKEND)
677 // nothing
678 #elif defined(__APPLE__)
679 #define _SAUDIO_APPLE (1)
680 #include <TargetConditionals.h>
681 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
682 #define _SAUDIO_IOS (1)
683 #else
684 #define _SAUDIO_MACOS (1)
685 #endif
686 #elif defined(__EMSCRIPTEN__)
687 #define _SAUDIO_EMSCRIPTEN (1)
688 #elif defined(_WIN32)
689 #define _SAUDIO_WINDOWS (1)
690 #include <winapifamily.h>
691 #if (defined(WINAPI_FAMILY_PARTITION) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
692 #error "sokol_audio.h no longer supports UWP"
693 #endif
694 #elif defined(__ANDROID__)
695 #define _SAUDIO_ANDROID (1)
696 #if !defined(SAUDIO_ANDROID_SLES) && !defined(SAUDIO_ANDROID_AAUDIO)
697 #define SAUDIO_ANDROID_AAUDIO (1)
698 #endif
699 #elif defined(__linux__) || defined(__unix__)
700 #define _SAUDIO_LINUX (1)
701 #else
702 #error "sokol_audio.h: Unknown platform"
703 #endif
704
705 // platform-specific headers and definitions
706 #if defined(SOKOL_DUMMY_BACKEND)
707 #define _SAUDIO_NOTHREADS (1)
708 #elif defined(_SAUDIO_WINDOWS)
709 #define _SAUDIO_WINTHREADS (1)
710 #ifndef WIN32_LEAN_AND_MEAN
711 #define WIN32_LEAN_AND_MEAN
712 #endif
713 #ifndef NOMINMAX
714 #define NOMINMAX
715 #endif
716 #include <windows.h>
717 #include <synchapi.h>
718 #pragma comment (lib, "kernel32")
719 #pragma comment (lib, "ole32")
720 #ifndef CINTERFACE
721 #define CINTERFACE
722 #endif
723 #ifndef COBJMACROS
724 #define COBJMACROS
725 #endif
726 #ifndef CONST_VTABLE
727 #define CONST_VTABLE
728 #endif
729 #include <mmdeviceapi.h>
730 #include <audioclient.h>
731 static const IID _saudio_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, {0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2} };
732 static const IID _saudio_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, {0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6} };
733 static const CLSID _saudio_CLSID_IMMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e} };
734 static const IID _saudio_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, {0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2} };
735 static const IID _saudio_IID_Devinterface_Audio_Render = { 0xe6327cad, 0xdcec, 0x4949, {0xae, 0x8a, 0x99, 0x1e, 0x97, 0x6a, 0x79, 0xd2} };
736 static const IID _saudio_IID_IActivateAudioInterface_Completion_Handler = { 0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90} };
737 static const GUID _saudio_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71} };
738 #if defined(__cplusplus)
739 #define _SOKOL_AUDIO_WIN32COM_ID(x) (x)
740 #else
741 #define _SOKOL_AUDIO_WIN32COM_ID(x) (&x)
742 #endif
743 /* fix for Visual Studio 2015 SDKs */
744 #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
745 #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
746 #endif
747 #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
748 #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
749 #endif
750 #ifdef _MSC_VER
751 #pragma warning(push)
752 #pragma warning(disable:4505) /* unreferenced local function has been removed */
753 #endif
754 #elif defined(_SAUDIO_APPLE)
755 #define _SAUDIO_PTHREADS (1)
756 #include <pthread.h>
757 #if defined(_SAUDIO_IOS)
758 // always use system headers on iOS (for now at least)
759 #if !defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
760 #define SAUDIO_OSX_USE_SYSTEM_HEADERS (1)
761 #endif
762 #if !defined(__cplusplus)
763 #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
764 #error "sokol_audio.h on iOS requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
765 #endif
766 #endif
767 #include <AudioToolbox/AudioToolbox.h>
768 #include <AVFoundation/AVFoundation.h>
769 #else
770 #if defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
771 #include <AudioToolbox/AudioToolbox.h>
772 #endif
773 #endif
774 #elif defined(_SAUDIO_ANDROID)
775 #define _SAUDIO_PTHREADS (1)
776 #include <pthread.h>
777 #if defined(SAUDIO_ANDROID_SLES)
778 #include "SLES/OpenSLES_Android.h"
779 #elif defined(SAUDIO_ANDROID_AAUDIO)
780 #include "aaudio/AAudio.h"
781 #endif
782 #elif defined(_SAUDIO_LINUX)
783 #include <alloca.h>
784 #define _SAUDIO_PTHREADS (1)
785 #include <pthread.h>
786 #define ALSA_PCM_NEW_HW_PARAMS_API
787 #include <alsa/asoundlib.h>
788 #elif defined(__EMSCRIPTEN__)
789 #define _SAUDIO_NOTHREADS (1)
790 #include <emscripten/emscripten.h>
791 #endif
792
793 #define _saudio_def(val, def) (((val) == 0) ? (def) : (val))
794 #define _saudio_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
795
796 #define _SAUDIO_DEFAULT_SAMPLE_RATE (44100)
797 #define _SAUDIO_DEFAULT_BUFFER_FRAMES (2048)
798 #define _SAUDIO_DEFAULT_PACKET_FRAMES (128)
799 #define _SAUDIO_DEFAULT_NUM_PACKETS ((_SAUDIO_DEFAULT_BUFFER_FRAMES/_SAUDIO_DEFAULT_PACKET_FRAMES)*4)
800
801 #ifndef SAUDIO_RING_MAX_SLOTS
802 #define SAUDIO_RING_MAX_SLOTS (1024)
803 #endif
804
805 // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
806 // ██ ██ ██ ██ ██ ██ ██ ██ ██
807 // ███████ ██ ██████ ██ ██ ██ ██ ███████
808 // ██ ██ ██ ██ ██ ██ ██ ██ ██
809 // ███████ ██ ██ ██ ██████ ██████ ██ ███████
810 //
811 // >>structs
812 #if defined(_SAUDIO_PTHREADS)
813
814 typedef struct {
815 pthread_mutex_t mutex;
816 } _saudio_mutex_t;
817
818 #elif defined(_SAUDIO_WINTHREADS)
819
820 typedef struct {
821 CRITICAL_SECTION critsec;
822 } _saudio_mutex_t;
823
824 #elif defined(_SAUDIO_NOTHREADS)
825
826 typedef struct {
827 int dummy_mutex;
828 } _saudio_mutex_t;
829
830 #endif
831
832 #if defined(SOKOL_DUMMY_BACKEND)
833
834 typedef struct {
835 int dummy;
836 } _saudio_dummy_backend_t;
837
838 #elif defined(_SAUDIO_APPLE)
839
840 #if defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
841
842 typedef AudioQueueRef _saudio_AudioQueueRef;
843 typedef AudioQueueBufferRef _saudio_AudioQueueBufferRef;
844 typedef AudioStreamBasicDescription _saudio_AudioStreamBasicDescription;
845 typedef OSStatus _saudio_OSStatus;
846
847 #define _saudio_kAudioFormatLinearPCM (kAudioFormatLinearPCM)
848 #define _saudio_kLinearPCMFormatFlagIsFloat (kLinearPCMFormatFlagIsFloat)
849 #define _saudio_kAudioFormatFlagIsPacked (kAudioFormatFlagIsPacked)
850
851 #else
852 #ifdef __cplusplus
853 extern "C" {
854 #endif
855
856 // embedded AudioToolbox declarations
857 typedef uint32_t _saudio_AudioFormatID;
858 typedef uint32_t _saudio_AudioFormatFlags;
859 typedef int32_t _saudio_OSStatus;
860 typedef uint32_t _saudio_SMPTETimeType;
861 typedef uint32_t _saudio_SMPTETimeFlags;
862 typedef uint32_t _saudio_AudioTimeStampFlags;
863 typedef void* _saudio_CFRunLoopRef;
864 typedef void* _saudio_CFStringRef;
865 typedef void* _saudio_AudioQueueRef;
866
867 #define _saudio_kAudioFormatLinearPCM ('lpcm')
868 #define _saudio_kLinearPCMFormatFlagIsFloat (1U << 0)
869 #define _saudio_kAudioFormatFlagIsPacked (1U << 3)
870
871 typedef struct _saudio_AudioStreamBasicDescription {
872 double mSampleRate;
873 _saudio_AudioFormatID mFormatID;
874 _saudio_AudioFormatFlags mFormatFlags;
875 uint32_t mBytesPerPacket;
876 uint32_t mFramesPerPacket;
877 uint32_t mBytesPerFrame;
878 uint32_t mChannelsPerFrame;
879 uint32_t mBitsPerChannel;
880 uint32_t mReserved;
881 } _saudio_AudioStreamBasicDescription;
882
883 typedef struct _saudio_AudioStreamPacketDescription {
884 int64_t mStartOffset;
885 uint32_t mVariableFramesInPacket;
886 uint32_t mDataByteSize;
887 } _saudio_AudioStreamPacketDescription;
888
889 typedef struct _saudio_SMPTETime {
890 int16_t mSubframes;
891 int16_t mSubframeDivisor;
892 uint32_t mCounter;
893 _saudio_SMPTETimeType mType;
894 _saudio_SMPTETimeFlags mFlags;
895 int16_t mHours;
896 int16_t mMinutes;
897 int16_t mSeconds;
898 int16_t mFrames;
899 } _saudio_SMPTETime;
900
901 typedef struct _saudio_AudioTimeStamp {
902 double mSampleTime;
903 uint64_t mHostTime;
904 double mRateScalar;
905 uint64_t mWordClockTime;
906 _saudio_SMPTETime mSMPTETime;
907 _saudio_AudioTimeStampFlags mFlags;
908 uint32_t mReserved;
909 } _saudio_AudioTimeStamp;
910
911 typedef struct _saudio_AudioQueueBuffer {
912 const uint32_t mAudioDataBytesCapacity;
913 void* const mAudioData;
914 uint32_t mAudioDataByteSize;
915 void * mUserData;
916 const uint32_t mPacketDescriptionCapacity;
917 _saudio_AudioStreamPacketDescription* const mPacketDescriptions;
918 uint32_t mPacketDescriptionCount;
919 } _saudio_AudioQueueBuffer;
920 typedef _saudio_AudioQueueBuffer* _saudio_AudioQueueBufferRef;
921
922 typedef void (*_saudio_AudioQueueOutputCallback)(void* user_data, _saudio_AudioQueueRef inAQ, _saudio_AudioQueueBufferRef inBuffer);
923
924 extern _saudio_OSStatus AudioQueueNewOutput(const _saudio_AudioStreamBasicDescription* inFormat, _saudio_AudioQueueOutputCallback inCallbackProc, void* inUserData, _saudio_CFRunLoopRef inCallbackRunLoop, _saudio_CFStringRef inCallbackRunLoopMode, uint32_t inFlags, _saudio_AudioQueueRef* outAQ);
925 extern _saudio_OSStatus AudioQueueDispose(_saudio_AudioQueueRef inAQ, bool inImmediate);
926 extern _saudio_OSStatus AudioQueueAllocateBuffer(_saudio_AudioQueueRef inAQ, uint32_t inBufferByteSize, _saudio_AudioQueueBufferRef* outBuffer);
927 extern _saudio_OSStatus AudioQueueEnqueueBuffer(_saudio_AudioQueueRef inAQ, _saudio_AudioQueueBufferRef inBuffer, uint32_t inNumPacketDescs, const _saudio_AudioStreamPacketDescription* inPacketDescs);
928 extern _saudio_OSStatus AudioQueueStart(_saudio_AudioQueueRef inAQ, const _saudio_AudioTimeStamp * inStartTime);
929 extern _saudio_OSStatus AudioQueueStop(_saudio_AudioQueueRef inAQ, bool inImmediate);
930
931 #ifdef __cplusplus
932 } // extern "C"
933 #endif
934
935 #endif // SAUDIO_OSX_USE_SYSTEM_HEADERS
936
937 typedef struct {
938 _saudio_AudioQueueRef ca_audio_queue;
939 #if defined(_SAUDIO_IOS)
940 id ca_interruption_handler;
941 #endif
942 } _saudio_apple_backend_t;
943
944 #elif defined(_SAUDIO_LINUX)
945
946 typedef struct {
947 snd_pcm_t* device;
948 float* buffer;
949 int buffer_byte_size;
950 int buffer_frames;
951 pthread_t thread;
952 bool thread_stop;
953 } _saudio_alsa_backend_t;
954
955 #elif defined(SAUDIO_ANDROID_SLES)
956
957 #define SAUDIO_SLES_NUM_BUFFERS (2)
958
959 typedef struct {
960 pthread_mutex_t mutex;
961 pthread_cond_t cond;
962 int count;
963 } _saudio_sles_semaphore_t;
964
965 typedef struct {
966 SLObjectItf engine_obj;
967 SLEngineItf engine;
968 SLObjectItf output_mix_obj;
969 SLVolumeItf output_mix_vol;
970 SLDataLocator_OutputMix out_locator;
971 SLDataSink dst_data_sink;
972 SLObjectItf player_obj;
973 SLPlayItf player;
974 SLVolumeItf player_vol;
975 SLAndroidSimpleBufferQueueItf player_buffer_queue;
976
977 int16_t* output_buffers[SAUDIO_SLES_NUM_BUFFERS];
978 float* src_buffer;
979 int active_buffer;
980 _saudio_sles_semaphore_t buffer_sem;
981 pthread_t thread;
982 volatile int thread_stop;
983 SLDataLocator_AndroidSimpleBufferQueue in_locator;
984 } _saudio_sles_backend_t;
985
986 #elif defined(SAUDIO_ANDROID_AAUDIO)
987
988 typedef struct {
989 AAudioStreamBuilder* builder;
990 AAudioStream* stream;
991 pthread_t thread;
992 pthread_mutex_t mutex;
993 } _saudio_aaudio_backend_t;
994
995 #elif defined(_SAUDIO_WINDOWS)
996
997 typedef struct {
998 HANDLE thread_handle;
999 HANDLE buffer_end_event;
1000 bool stop;
1001 UINT32 dst_buffer_frames;
1002 int src_buffer_frames;
1003 int src_buffer_byte_size;
1004 int src_buffer_pos;
1005 float* src_buffer;
1006 } _saudio_wasapi_thread_data_t;
1007
1008 typedef struct {
1009 IMMDeviceEnumerator* device_enumerator;
1010 IMMDevice* device;
1011 IAudioClient* audio_client;
1012 IAudioRenderClient* render_client;
1013 _saudio_wasapi_thread_data_t thread;
1014 } _saudio_wasapi_backend_t;
1015
1016 #elif defined(_SAUDIO_EMSCRIPTEN)
1017
1018 typedef struct {
1019 uint8_t* buffer;
1020 } _saudio_web_backend_t;
1021
1022 #else
1023 #error "unknown platform"
1024 #endif
1025
1026 #if defined(SOKOL_DUMMY_BACKEND)
1027 typedef _saudio_dummy_backend_t _saudio_backend_t;
1028 #elif defined(_SAUDIO_APPLE)
1029 typedef _saudio_apple_backend_t _saudio_backend_t;
1030 #elif defined(_SAUDIO_EMSCRIPTEN)
1031 typedef _saudio_web_backend_t _saudio_backend_t;
1032 #elif defined(_SAUDIO_WINDOWS)
1033 typedef _saudio_wasapi_backend_t _saudio_backend_t;
1034 #elif defined(SAUDIO_ANDROID_SLES)
1035 typedef _saudio_sles_backend_t _saudio_backend_t;
1036 #elif defined(SAUDIO_ANDROID_AAUDIO)
1037 typedef _saudio_aaudio_backend_t _saudio_backend_t;
1038 #elif defined(_SAUDIO_LINUX)
1039 typedef _saudio_alsa_backend_t _saudio_backend_t;
1040 #endif
1041
1042 /* a ringbuffer structure */
1043 typedef struct {
1044 int head; // next slot to write to
1045 int tail; // next slot to read from
1046 int num; // number of slots in queue
1047 int queue[SAUDIO_RING_MAX_SLOTS];
1048 } _saudio_ring_t;
1049
1050 /* a packet FIFO structure */
1051 typedef struct {
1052 bool valid;
1053 int packet_size; /* size of a single packets in bytes(!) */
1054 int num_packets; /* number of packet in fifo */
1055 uint8_t* base_ptr; /* packet memory chunk base pointer (dynamically allocated) */
1056 int cur_packet; /* current write-packet */
1057 int cur_offset; /* current byte-offset into current write packet */
1058 _saudio_mutex_t mutex; /* mutex for thread-safe access */
1059 _saudio_ring_t read_queue; /* buffers with data, ready to be streamed */
1060 _saudio_ring_t write_queue; /* empty buffers, ready to be pushed to */
1061 } _saudio_fifo_t;
1062
1063 /* sokol-audio state */
1064 typedef struct {
1065 bool valid;
1066 void (*stream_cb)(float* buffer, int num_frames, int num_channels);
1067 void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data);
1068 void* user_data;
1069 int sample_rate; /* sample rate */
1070 int buffer_frames; /* number of frames in streaming buffer */
1071 int bytes_per_frame; /* filled by backend */
1072 int packet_frames; /* number of frames in a packet */
1073 int num_packets; /* number of packets in packet queue */
1074 int num_channels; /* actual number of channels */
1075 saudio_desc desc;
1076 _saudio_fifo_t fifo;
1077 _saudio_backend_t backend;
1078 } _saudio_state_t;
1079
1080 _SOKOL_PRIVATE _saudio_state_t _saudio;
1081
1082 _SOKOL_PRIVATE bool _saudio_has_callback(void) {
1083 return (_saudio.stream_cb || _saudio.stream_userdata_cb);
1084 }
1085
1086 _SOKOL_PRIVATE void _saudio_stream_callback(float* buffer, int num_frames, int num_channels) {
1087 if (_saudio.stream_cb) {
1088 _saudio.stream_cb(buffer, num_frames, num_channels);
1089 }
1090 else if (_saudio.stream_userdata_cb) {
1091 _saudio.stream_userdata_cb(buffer, num_frames, num_channels, _saudio.user_data);
1092 }
1093 }
1094
1095 // ██ ██████ ██████ ██████ ██ ███ ██ ██████
1096 // ██ ██ ██ ██ ██ ██ ████ ██ ██
1097 // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
1098 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1099 // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
1100 //
1101 // >>logging
1102 #if defined(SOKOL_DEBUG)
1103 #define _SAUDIO_LOGITEM_XMACRO(item,msg) #item ": " msg,
1104 static const char* _saudio_log_messages[] = {
1105 _SAUDIO_LOG_ITEMS
1106 };
1107 #undef _SAUDIO_LOGITEM_XMACRO
1108 #endif // SOKOL_DEBUG
1109
1110 #define _SAUDIO_PANIC(code) _saudio_log(SAUDIO_LOGITEM_ ##code, 0, __LINE__)
1111 #define _SAUDIO_ERROR(code) _saudio_log(SAUDIO_LOGITEM_ ##code, 1, __LINE__)
1112 #define _SAUDIO_WARN(code) _saudio_log(SAUDIO_LOGITEM_ ##code, 2, __LINE__)
1113 #define _SAUDIO_INFO(code) _saudio_log(SAUDIO_LOGITEM_ ##code, 3, __LINE__)
1114
1115 static void _saudio_log(saudio_log_item log_item, uint32_t log_level, uint32_t line_nr) {
1116 if (_saudio.desc.logger.func) {
1117 #if defined(SOKOL_DEBUG)
1118 const char* filename = __FILE__;
1119 const char* message = _saudio_log_messages[log_item];
1120 #else
1121 const char* filename = 0;
1122 const char* message = 0;
1123 #endif
1124 _saudio.desc.logger.func("saudio", log_level, log_item, message, line_nr, filename, _saudio.desc.logger.user_data);
1125 }
1126 else {
1127 // for log level PANIC it would be 'undefined behaviour' to continue
1128 if (log_level == 0) {
1129 abort();
1130 }
1131 }
1132 }
1133
1134 // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
1135 // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
1136 // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
1137 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1138 // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
1139 //
1140 // >>memory
1141 _SOKOL_PRIVATE void _saudio_clear(void* ptr, size_t size) {
1142 SOKOL_ASSERT(ptr && (size > 0));
1143 memset(ptr, 0, size);
1144 }
1145
1146 _SOKOL_PRIVATE void* _saudio_malloc(size_t size) {
1147 SOKOL_ASSERT(size > 0);
1148 void* ptr;
1149 if (_saudio.desc.allocator.alloc_fn) {
1150 ptr = _saudio.desc.allocator.alloc_fn(size, _saudio.desc.allocator.user_data);
1151 } else {
1152 ptr = malloc(size);
1153 }
1154 if (0 == ptr) {
1155 _SAUDIO_PANIC(MALLOC_FAILED);
1156 }
1157 return ptr;
1158 }
1159
1160 _SOKOL_PRIVATE void* _saudio_malloc_clear(size_t size) {
1161 void* ptr = _saudio_malloc(size);
1162 _saudio_clear(ptr, size);
1163 return ptr;
1164 }
1165
1166 _SOKOL_PRIVATE void _saudio_free(void* ptr) {
1167 if (_saudio.desc.allocator.free_fn) {
1168 _saudio.desc.allocator.free_fn(ptr, _saudio.desc.allocator.user_data);
1169 } else {
1170 free(ptr);
1171 }
1172 }
1173
1174 // ███ ███ ██ ██ ████████ ███████ ██ ██
1175 // ████ ████ ██ ██ ██ ██ ██ ██
1176 // ██ ████ ██ ██ ██ ██ █████ ███
1177 // ██ ██ ██ ██ ██ ██ ██ ██ ██
1178 // ██ ██ ██████ ██ ███████ ██ ██
1179 //
1180 // >>mutex
1181 #if defined(_SAUDIO_NOTHREADS)
1182
1183 _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) { (void)m; }
1184 _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) { (void)m; }
1185 _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) { (void)m; }
1186 _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) { (void)m; }
1187
1188 #elif defined(_SAUDIO_PTHREADS)
1189
1190 _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) {
1191 pthread_mutexattr_t attr;
1192 pthread_mutexattr_init(&attr);
1193 pthread_mutex_init(&m->mutex, &attr);
1194 }
1195
1196 _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) {
1197 pthread_mutex_destroy(&m->mutex);
1198 }
1199
1200 _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) {
1201 pthread_mutex_lock(&m->mutex);
1202 }
1203
1204 _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) {
1205 pthread_mutex_unlock(&m->mutex);
1206 }
1207
1208 #elif defined(_SAUDIO_WINTHREADS)
1209
1210 _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) {
1211 InitializeCriticalSection(&m->critsec);
1212 }
1213
1214 _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) {
1215 DeleteCriticalSection(&m->critsec);
1216 }
1217
1218 _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) {
1219 EnterCriticalSection(&m->critsec);
1220 }
1221
1222 _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) {
1223 LeaveCriticalSection(&m->critsec);
1224 }
1225 #else
1226 #error "sokol_audio.h: unknown platform!"
1227 #endif
1228
1229 // ██████ ██ ███ ██ ██████ ██████ ██ ██ ███████ ███████ ███████ ██████
1230 // ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1231 // ██████ ██ ██ ██ ██ ██ ███ ██████ ██ ██ █████ █████ █████ ██████
1232 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1233 // ██ ██ ██ ██ ████ ██████ ██████ ██████ ██ ██ ███████ ██ ██
1234 //
1235 // >>ringbuffer
1236 _SOKOL_PRIVATE int _saudio_ring_idx(_saudio_ring_t* ring, int i) {
1237 return (i % ring->num);
1238 }
1239
1240 _SOKOL_PRIVATE void _saudio_ring_init(_saudio_ring_t* ring, int num_slots) {
1241 SOKOL_ASSERT((num_slots + 1) <= SAUDIO_RING_MAX_SLOTS);
1242 ring->head = 0;
1243 ring->tail = 0;
1244 /* one slot reserved to detect 'full' vs 'empty' */
1245 ring->num = num_slots + 1;
1246 }
1247
1248 _SOKOL_PRIVATE bool _saudio_ring_full(_saudio_ring_t* ring) {
1249 return _saudio_ring_idx(ring, ring->head + 1) == ring->tail;
1250 }
1251
1252 _SOKOL_PRIVATE bool _saudio_ring_empty(_saudio_ring_t* ring) {
1253 return ring->head == ring->tail;
1254 }
1255
1256 _SOKOL_PRIVATE int _saudio_ring_count(_saudio_ring_t* ring) {
1257 int count;
1258 if (ring->head >= ring->tail) {
1259 count = ring->head - ring->tail;
1260 }
1261 else {
1262 count = (ring->head + ring->num) - ring->tail;
1263 }
1264 SOKOL_ASSERT(count < ring->num);
1265 return count;
1266 }
1267
1268 _SOKOL_PRIVATE void _saudio_ring_enqueue(_saudio_ring_t* ring, int val) {
1269 SOKOL_ASSERT(!_saudio_ring_full(ring));
1270 ring->queue[ring->head] = val;
1271 ring->head = _saudio_ring_idx(ring, ring->head + 1);
1272 }
1273
1274 _SOKOL_PRIVATE int _saudio_ring_dequeue(_saudio_ring_t* ring) {
1275 SOKOL_ASSERT(!_saudio_ring_empty(ring));
1276 int val = ring->queue[ring->tail];
1277 ring->tail = _saudio_ring_idx(ring, ring->tail + 1);
1278 return val;
1279 }
1280
1281 // ███████ ██ ███████ ██████
1282 // ██ ██ ██ ██ ██
1283 // █████ ██ █████ ██ ██
1284 // ██ ██ ██ ██ ██
1285 // ██ ██ ██ ██████
1286 //
1287 // >>fifo
1288 _SOKOL_PRIVATE void _saudio_fifo_init_mutex(_saudio_fifo_t* fifo) {
1289 /* this must be called before initializing both the backend and the fifo itself! */
1290 _saudio_mutex_init(&fifo->mutex);
1291 }
1292
1293 _SOKOL_PRIVATE void _saudio_fifo_destroy_mutex(_saudio_fifo_t* fifo) {
1294 _saudio_mutex_destroy(&fifo->mutex);
1295 }
1296
1297 _SOKOL_PRIVATE void _saudio_fifo_init(_saudio_fifo_t* fifo, int packet_size, int num_packets) {
1298 /* NOTE: there's a chicken-egg situation during the init phase where the
1299 streaming thread must be started before the fifo is actually initialized,
1300 thus the fifo init must already be protected from access by the fifo_read() func.
1301 */
1302 _saudio_mutex_lock(&fifo->mutex);
1303 SOKOL_ASSERT((packet_size > 0) && (num_packets > 0));
1304 fifo->packet_size = packet_size;
1305 fifo->num_packets = num_packets;
1306 fifo->base_ptr = (uint8_t*) _saudio_malloc((size_t)(packet_size * num_packets));
1307 fifo->cur_packet = -1;
1308 fifo->cur_offset = 0;
1309 _saudio_ring_init(&fifo->read_queue, num_packets);
1310 _saudio_ring_init(&fifo->write_queue, num_packets);
1311 for (int i = 0; i < num_packets; i++) {
1312 _saudio_ring_enqueue(&fifo->write_queue, i);
1313 }
1314 SOKOL_ASSERT(_saudio_ring_full(&fifo->write_queue));
1315 SOKOL_ASSERT(_saudio_ring_count(&fifo->write_queue) == num_packets);
1316 SOKOL_ASSERT(_saudio_ring_empty(&fifo->read_queue));
1317 SOKOL_ASSERT(_saudio_ring_count(&fifo->read_queue) == 0);
1318 fifo->valid = true;
1319 _saudio_mutex_unlock(&fifo->mutex);
1320 }
1321
1322 _SOKOL_PRIVATE void _saudio_fifo_shutdown(_saudio_fifo_t* fifo) {
1323 SOKOL_ASSERT(fifo->base_ptr);
1324 _saudio_free(fifo->base_ptr);
1325 fifo->base_ptr = 0;
1326 fifo->valid = false;
1327 }
1328
1329 _SOKOL_PRIVATE int _saudio_fifo_writable_bytes(_saudio_fifo_t* fifo) {
1330 _saudio_mutex_lock(&fifo->mutex);
1331 int num_bytes = (_saudio_ring_count(&fifo->write_queue) * fifo->packet_size);
1332 if (fifo->cur_packet != -1) {
1333 num_bytes += fifo->packet_size - fifo->cur_offset;
1334 }
1335 _saudio_mutex_unlock(&fifo->mutex);
1336 SOKOL_ASSERT((num_bytes >= 0) && (num_bytes <= (fifo->num_packets * fifo->packet_size)));
1337 return num_bytes;
1338 }
1339
1340 /* write new data to the write queue, this is called from main thread */
1341 _SOKOL_PRIVATE int _saudio_fifo_write(_saudio_fifo_t* fifo, const uint8_t* ptr, int num_bytes) {
1342 /* returns the number of bytes written, this will be smaller then requested
1343 if the write queue runs full
1344 */
1345 int all_to_copy = num_bytes;
1346 while (all_to_copy > 0) {
1347 /* need to grab a new packet? */
1348 if (fifo->cur_packet == -1) {
1349 _saudio_mutex_lock(&fifo->mutex);
1350 if (!_saudio_ring_empty(&fifo->write_queue)) {
1351 fifo->cur_packet = _saudio_ring_dequeue(&fifo->write_queue);
1352 }
1353 _saudio_mutex_unlock(&fifo->mutex);
1354 SOKOL_ASSERT(fifo->cur_offset == 0);
1355 }
1356 /* append data to current write packet */
1357 if (fifo->cur_packet != -1) {
1358 int to_copy = all_to_copy;
1359 const int max_copy = fifo->packet_size - fifo->cur_offset;
1360 if (to_copy > max_copy) {
1361 to_copy = max_copy;
1362 }
1363 uint8_t* dst = fifo->base_ptr + fifo->cur_packet * fifo->packet_size + fifo->cur_offset;
1364 memcpy(dst, ptr, (size_t)to_copy);
1365 ptr += to_copy;
1366 fifo->cur_offset += to_copy;
1367 all_to_copy -= to_copy;
1368 SOKOL_ASSERT(fifo->cur_offset <= fifo->packet_size);
1369 SOKOL_ASSERT(all_to_copy >= 0);
1370 }
1371 else {
1372 /* early out if we're starving */
1373 int bytes_copied = num_bytes - all_to_copy;
1374 SOKOL_ASSERT((bytes_copied >= 0) && (bytes_copied < num_bytes));
1375 return bytes_copied;
1376 }
1377 /* if write packet is full, push to read queue */
1378 if (fifo->cur_offset == fifo->packet_size) {
1379 _saudio_mutex_lock(&fifo->mutex);
1380 _saudio_ring_enqueue(&fifo->read_queue, fifo->cur_packet);
1381 _saudio_mutex_unlock(&fifo->mutex);
1382 fifo->cur_packet = -1;
1383 fifo->cur_offset = 0;
1384 }
1385 }
1386 SOKOL_ASSERT(all_to_copy == 0);
1387 return num_bytes;
1388 }
1389
1390 /* read queued data, this is called form the stream callback (maybe separate thread) */
1391 _SOKOL_PRIVATE int _saudio_fifo_read(_saudio_fifo_t* fifo, uint8_t* ptr, int num_bytes) {
1392 /* NOTE: fifo_read might be called before the fifo is properly initialized */
1393 _saudio_mutex_lock(&fifo->mutex);
1394 int num_bytes_copied = 0;
1395 if (fifo->valid) {
1396 SOKOL_ASSERT(0 == (num_bytes % fifo->packet_size));
1397 SOKOL_ASSERT(num_bytes <= (fifo->packet_size * fifo->num_packets));
1398 const int num_packets_needed = num_bytes / fifo->packet_size;
1399 uint8_t* dst = ptr;
1400 /* either pull a full buffer worth of data, or nothing */
1401 if (_saudio_ring_count(&fifo->read_queue) >= num_packets_needed) {
1402 for (int i = 0; i < num_packets_needed; i++) {
1403 int packet_index = _saudio_ring_dequeue(&fifo->read_queue);
1404 _saudio_ring_enqueue(&fifo->write_queue, packet_index);
1405 const uint8_t* src = fifo->base_ptr + packet_index * fifo->packet_size;
1406 memcpy(dst, src, (size_t)fifo->packet_size);
1407 dst += fifo->packet_size;
1408 num_bytes_copied += fifo->packet_size;
1409 }
1410 SOKOL_ASSERT(num_bytes == num_bytes_copied);
1411 }
1412 }
1413 _saudio_mutex_unlock(&fifo->mutex);
1414 return num_bytes_copied;
1415 }
1416
1417 // ██████ ██ ██ ███ ███ ███ ███ ██ ██
1418 // ██ ██ ██ ██ ████ ████ ████ ████ ██ ██
1419 // ██ ██ ██ ██ ██ ████ ██ ██ ████ ██ ████
1420 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1421 // ██████ ██████ ██ ██ ██ ██ ██
1422 //
1423 // >>dummy
1424 #if defined(SOKOL_DUMMY_BACKEND)
1425 _SOKOL_PRIVATE bool _saudio_dummy_backend_init(void) {
1426 _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
1427 return true;
1428 };
1429 _SOKOL_PRIVATE void _saudio_dummy_backend_shutdown(void) { };
1430
1431 // █████ ██ ███████ █████
1432 // ██ ██ ██ ██ ██ ██
1433 // ███████ ██ ███████ ███████
1434 // ██ ██ ██ ██ ██ ██
1435 // ██ ██ ███████ ███████ ██ ██
1436 //
1437 // >>alsa
1438 #elif defined(_SAUDIO_LINUX)
1439
1440 /* the streaming callback runs in a separate thread */
1441 _SOKOL_PRIVATE void* _saudio_alsa_cb(void* param) {
1442 _SOKOL_UNUSED(param);
1443 while (!_saudio.backend.thread_stop) {
1444 /* snd_pcm_writei() will be blocking until it needs data */
1445 int write_res = snd_pcm_writei(_saudio.backend.device, _saudio.backend.buffer, (snd_pcm_uframes_t)_saudio.backend.buffer_frames);
1446 if (write_res < 0) {
1447 /* underrun occurred */
1448 snd_pcm_prepare(_saudio.backend.device);
1449 }
1450 else {
1451 /* fill the streaming buffer with new data */
1452 if (_saudio_has_callback()) {
1453 _saudio_stream_callback(_saudio.backend.buffer, _saudio.backend.buffer_frames, _saudio.num_channels);
1454 }
1455 else {
1456 if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.buffer, _saudio.backend.buffer_byte_size)) {
1457 /* not enough read data available, fill the entire buffer with silence */
1458 _saudio_clear(_saudio.backend.buffer, (size_t)_saudio.backend.buffer_byte_size);
1459 }
1460 }
1461 }
1462 }
1463 return 0;
1464 }
1465
1466 _SOKOL_PRIVATE bool _saudio_alsa_backend_init(void) {
1467 int dir; uint32_t rate;
1468 int rc = snd_pcm_open(&_saudio.backend.device, "default", SND_PCM_STREAM_PLAYBACK, 0);
1469 if (rc < 0) {
1470 _SAUDIO_ERROR(ALSA_SND_PCM_OPEN_FAILED);
1471 return false;
1472 }
1473
1474 /* configuration works by restricting the 'configuration space' step
1475 by step, we require all parameters except the sample rate to
1476 match perfectly
1477 */
1478 snd_pcm_hw_params_t* params = 0;
1479 snd_pcm_hw_params_alloca(&params);
1480 snd_pcm_hw_params_any(_saudio.backend.device, params);
1481 snd_pcm_hw_params_set_access(_saudio.backend.device, params, SND_PCM_ACCESS_RW_INTERLEAVED);
1482 if (0 > snd_pcm_hw_params_set_format(_saudio.backend.device, params, SND_PCM_FORMAT_FLOAT_LE)) {
1483 _SAUDIO_ERROR(ALSA_FLOAT_SAMPLES_NOT_SUPPORTED);
1484 goto error;
1485 }
1486 if (0 > snd_pcm_hw_params_set_buffer_size(_saudio.backend.device, params, (snd_pcm_uframes_t)_saudio.buffer_frames)) {
1487 _SAUDIO_ERROR(ALSA_REQUESTED_BUFFER_SIZE_NOT_SUPPORTED);
1488 goto error;
1489 }
1490 if (0 > snd_pcm_hw_params_set_channels(_saudio.backend.device, params, (uint32_t)_saudio.num_channels)) {
1491 _SAUDIO_ERROR(ALSA_REQUESTED_CHANNEL_COUNT_NOT_SUPPORTED);
1492 goto error;
1493 }
1494 /* let ALSA pick a nearby sampling rate */
1495 rate = (uint32_t) _saudio.sample_rate;
1496 dir = 0;
1497 if (0 > snd_pcm_hw_params_set_rate_near(_saudio.backend.device, params, &rate, &dir)) {
1498 _SAUDIO_ERROR(ALSA_SND_PCM_HW_PARAMS_SET_RATE_NEAR_FAILED);
1499 goto error;
1500 }
1501 if (0 > snd_pcm_hw_params(_saudio.backend.device, params)) {
1502 _SAUDIO_ERROR(ALSA_SND_PCM_HW_PARAMS_FAILED);
1503 goto error;
1504 }
1505
1506 /* read back actual sample rate and channels */
1507 _saudio.sample_rate = (int)rate;
1508 _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
1509
1510 /* allocate the streaming buffer */
1511 _saudio.backend.buffer_byte_size = _saudio.buffer_frames * _saudio.bytes_per_frame;
1512 _saudio.backend.buffer_frames = _saudio.buffer_frames;
1513 _saudio.backend.buffer = (float*) _saudio_malloc_clear((size_t)_saudio.backend.buffer_byte_size);
1514
1515 /* create the buffer-streaming start thread */
1516 if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_alsa_cb, 0)) {
1517 _SAUDIO_ERROR(ALSA_PTHREAD_CREATE_FAILED);
1518 goto error;
1519 }
1520
1521 return true;
1522 error:
1523 if (_saudio.backend.device) {
1524 snd_pcm_close(_saudio.backend.device);
1525 _saudio.backend.device = 0;
1526 }
1527 return false;
1528 };
1529
1530 _SOKOL_PRIVATE void _saudio_alsa_backend_shutdown(void) {
1531 SOKOL_ASSERT(_saudio.backend.device);
1532 _saudio.backend.thread_stop = true;
1533 pthread_join(_saudio.backend.thread, 0);
1534 snd_pcm_drain(_saudio.backend.device);
1535 snd_pcm_close(_saudio.backend.device);
1536 _saudio_free(_saudio.backend.buffer);
1537 };
1538
1539 // ██ ██ █████ ███████ █████ ██████ ██
1540 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1541 // ██ █ ██ ███████ ███████ ███████ ██████ ██
1542 // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██
1543 // ███ ███ ██ ██ ███████ ██ ██ ██ ██
1544 //
1545 // >>wasapi
1546 #elif defined(_SAUDIO_WINDOWS)
1547
1548 /* fill intermediate buffer with new data and reset buffer_pos */
1549 _SOKOL_PRIVATE void _saudio_wasapi_fill_buffer(void) {
1550 if (_saudio_has_callback()) {
1551 _saudio_stream_callback(_saudio.backend.thread.src_buffer, _saudio.backend.thread.src_buffer_frames, _saudio.num_channels);
1552 }
1553 else {
1554 if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.thread.src_buffer, _saudio.backend.thread.src_buffer_byte_size)) {
1555 /* not enough read data available, fill the entire buffer with silence */
1556 _saudio_clear(_saudio.backend.thread.src_buffer, (size_t)_saudio.backend.thread.src_buffer_byte_size);
1557 }
1558 }
1559 }
1560
1561 _SOKOL_PRIVATE int _saudio_wasapi_min(int a, int b) {
1562 return (a < b) ? a : b;
1563 }
1564
1565 _SOKOL_PRIVATE void _saudio_wasapi_submit_buffer(int num_frames) {
1566 BYTE* wasapi_buffer = 0;
1567 if (FAILED(IAudioRenderClient_GetBuffer(_saudio.backend.render_client, num_frames, &wasapi_buffer))) {
1568 return;
1569 }
1570 SOKOL_ASSERT(wasapi_buffer);
1571
1572 /* copy samples to WASAPI buffer, refill source buffer if needed */
1573 int num_remaining_samples = num_frames * _saudio.num_channels;
1574 int buffer_pos = _saudio.backend.thread.src_buffer_pos;
1575 const int buffer_size_in_samples = _saudio.backend.thread.src_buffer_byte_size / (int)sizeof(float);
1576 float* dst = (float*)wasapi_buffer;
1577 const float* dst_end = dst + num_remaining_samples;
1578 _SOKOL_UNUSED(dst_end); // suppress unused warning in release mode
1579 const float* src = _saudio.backend.thread.src_buffer;
1580
1581 while (num_remaining_samples > 0) {
1582 if (0 == buffer_pos) {
1583 _saudio_wasapi_fill_buffer();
1584 }
1585 const int samples_to_copy = _saudio_wasapi_min(num_remaining_samples, buffer_size_in_samples - buffer_pos);
1586 SOKOL_ASSERT((buffer_pos + samples_to_copy) <= buffer_size_in_samples);
1587 SOKOL_ASSERT((dst + samples_to_copy) <= dst_end);
1588 memcpy(dst, &src[buffer_pos], (size_t)samples_to_copy * sizeof(float));
1589 num_remaining_samples -= samples_to_copy;
1590 SOKOL_ASSERT(num_remaining_samples >= 0);
1591 buffer_pos += samples_to_copy;
1592 dst += samples_to_copy;
1593
1594 SOKOL_ASSERT(buffer_pos <= buffer_size_in_samples);
1595 if (buffer_pos == buffer_size_in_samples) {
1596 buffer_pos = 0;
1597 }
1598 }
1599 _saudio.backend.thread.src_buffer_pos = buffer_pos;
1600 IAudioRenderClient_ReleaseBuffer(_saudio.backend.render_client, num_frames, 0);
1601 }
1602
1603 _SOKOL_PRIVATE DWORD WINAPI _saudio_wasapi_thread_fn(LPVOID param) {
1604 (void)param;
1605 _saudio_wasapi_submit_buffer(_saudio.backend.thread.src_buffer_frames);
1606 IAudioClient_Start(_saudio.backend.audio_client);
1607 while (!_saudio.backend.thread.stop) {
1608 WaitForSingleObject(_saudio.backend.thread.buffer_end_event, INFINITE);
1609 UINT32 padding = 0;
1610 if (FAILED(IAudioClient_GetCurrentPadding(_saudio.backend.audio_client, &padding))) {
1611 continue;
1612 }
1613 SOKOL_ASSERT(_saudio.backend.thread.dst_buffer_frames >= padding);
1614 int num_frames = (int)_saudio.backend.thread.dst_buffer_frames - (int)padding;
1615 if (num_frames > 0) {
1616 _saudio_wasapi_submit_buffer(num_frames);
1617 }
1618 }
1619 return 0;
1620 }
1621
1622 _SOKOL_PRIVATE void _saudio_wasapi_release(void) {
1623 if (_saudio.backend.thread.src_buffer) {
1624 _saudio_free(_saudio.backend.thread.src_buffer);
1625 _saudio.backend.thread.src_buffer = 0;
1626 }
1627 if (_saudio.backend.render_client) {
1628 IAudioRenderClient_Release(_saudio.backend.render_client);
1629 _saudio.backend.render_client = 0;
1630 }
1631 if (_saudio.backend.audio_client) {
1632 IAudioClient_Release(_saudio.backend.audio_client);
1633 _saudio.backend.audio_client = 0;
1634 }
1635 if (_saudio.backend.device) {
1636 IMMDevice_Release(_saudio.backend.device);
1637 _saudio.backend.device = 0;
1638 }
1639 if (_saudio.backend.device_enumerator) {
1640 IMMDeviceEnumerator_Release(_saudio.backend.device_enumerator);
1641 _saudio.backend.device_enumerator = 0;
1642 }
1643 if (0 != _saudio.backend.thread.buffer_end_event) {
1644 CloseHandle(_saudio.backend.thread.buffer_end_event);
1645 _saudio.backend.thread.buffer_end_event = 0;
1646 }
1647 }
1648
1649 _SOKOL_PRIVATE bool _saudio_wasapi_backend_init(void) {
1650 REFERENCE_TIME dur;
1651 /* CoInitializeEx could have been called elsewhere already, in which
1652 case the function returns with S_FALSE (thus it does not make much
1653 sense to check the result)
1654 */
1655 HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
1656 _SOKOL_UNUSED(hr);
1657 _saudio.backend.thread.buffer_end_event = CreateEvent(0, FALSE, FALSE, 0);
1658 if (0 == _saudio.backend.thread.buffer_end_event) {
1659 _SAUDIO_ERROR(WASAPI_CREATE_EVENT_FAILED);
1660 goto error;
1661 }
1662 if (FAILED(CoCreateInstance(_SOKOL_AUDIO_WIN32COM_ID(_saudio_CLSID_IMMDeviceEnumerator),
1663 0, CLSCTX_ALL,
1664 _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IMMDeviceEnumerator),
1665 (void**)&_saudio.backend.device_enumerator)))
1666 {
1667 _SAUDIO_ERROR(WASAPI_CREATE_DEVICE_ENUMERATOR_FAILED);
1668 goto error;
1669 }
1670 if (FAILED(IMMDeviceEnumerator_GetDefaultAudioEndpoint(_saudio.backend.device_enumerator,
1671 eRender, eConsole,
1672 &_saudio.backend.device)))
1673 {
1674 _SAUDIO_ERROR(WASAPI_GET_DEFAULT_AUDIO_ENDPOINT_FAILED);
1675 goto error;
1676 }
1677 if (FAILED(IMMDevice_Activate(_saudio.backend.device,
1678 _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioClient),
1679 CLSCTX_ALL, 0,
1680 (void**)&_saudio.backend.audio_client)))
1681 {
1682 _SAUDIO_ERROR(WASAPI_DEVICE_ACTIVATE_FAILED);
1683 goto error;
1684 }
1685
1686 WAVEFORMATEXTENSIBLE fmtex;
1687 _saudio_clear(&fmtex, sizeof(fmtex));
1688 fmtex.Format.nChannels = (WORD)_saudio.num_channels;
1689 fmtex.Format.nSamplesPerSec = (DWORD)_saudio.sample_rate;
1690 fmtex.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1691 fmtex.Format.wBitsPerSample = 32;
1692 fmtex.Format.nBlockAlign = (fmtex.Format.nChannels * fmtex.Format.wBitsPerSample) / 8;
1693 fmtex.Format.nAvgBytesPerSec = fmtex.Format.nSamplesPerSec * fmtex.Format.nBlockAlign;
1694 fmtex.Format.cbSize = 22; /* WORD + DWORD + GUID */
1695 fmtex.Samples.wValidBitsPerSample = 32;
1696 if (_saudio.num_channels == 1) {
1697 fmtex.dwChannelMask = SPEAKER_FRONT_CENTER;
1698 }
1699 else {
1700 fmtex.dwChannelMask = SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT;
1701 }
1702 fmtex.SubFormat = _saudio_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1703 dur = (REFERENCE_TIME)
1704 (((double)_saudio.buffer_frames) / (((double)_saudio.sample_rate) * (1.0/10000000.0)));
1705 if (FAILED(IAudioClient_Initialize(_saudio.backend.audio_client,
1706 AUDCLNT_SHAREMODE_SHARED,
1707 AUDCLNT_STREAMFLAGS_EVENTCALLBACK|AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM|AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
1708 dur, 0, (WAVEFORMATEX*)&fmtex, 0)))
1709 {
1710 _SAUDIO_ERROR(WASAPI_AUDIO_CLIENT_INITIALIZE_FAILED);
1711 goto error;
1712 }
1713 if (FAILED(IAudioClient_GetBufferSize(_saudio.backend.audio_client, &_saudio.backend.thread.dst_buffer_frames))) {
1714 _SAUDIO_ERROR(WASAPI_AUDIO_CLIENT_GET_BUFFER_SIZE_FAILED);
1715 goto error;
1716 }
1717 if (FAILED(IAudioClient_GetService(_saudio.backend.audio_client,
1718 _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioRenderClient),
1719 (void**)&_saudio.backend.render_client)))
1720 {
1721 _SAUDIO_ERROR(WASAPI_AUDIO_CLIENT_GET_SERVICE_FAILED);
1722 goto error;
1723 }
1724 if (FAILED(IAudioClient_SetEventHandle(_saudio.backend.audio_client, _saudio.backend.thread.buffer_end_event))) {
1725 _SAUDIO_ERROR(WASAPI_AUDIO_CLIENT_SET_EVENT_HANDLE_FAILED);
1726 goto error;
1727 }
1728 _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
1729 _saudio.backend.thread.src_buffer_frames = _saudio.buffer_frames;
1730 _saudio.backend.thread.src_buffer_byte_size = _saudio.backend.thread.src_buffer_frames * _saudio.bytes_per_frame;
1731
1732 /* allocate an intermediate buffer for sample format conversion */
1733 _saudio.backend.thread.src_buffer = (float*) _saudio_malloc((size_t)_saudio.backend.thread.src_buffer_byte_size);
1734
1735 /* create streaming thread */
1736 _saudio.backend.thread.thread_handle = CreateThread(NULL, 0, _saudio_wasapi_thread_fn, 0, 0, 0);
1737 if (0 == _saudio.backend.thread.thread_handle) {
1738 _SAUDIO_ERROR(WASAPI_CREATE_THREAD_FAILED);
1739 goto error;
1740 }
1741 return true;
1742 error:
1743 _saudio_wasapi_release();
1744 return false;
1745 }
1746
1747 _SOKOL_PRIVATE void _saudio_wasapi_backend_shutdown(void) {
1748 if (_saudio.backend.thread.thread_handle) {
1749 _saudio.backend.thread.stop = true;
1750 SetEvent(_saudio.backend.thread.buffer_end_event);
1751 WaitForSingleObject(_saudio.backend.thread.thread_handle, INFINITE);
1752 CloseHandle(_saudio.backend.thread.thread_handle);
1753 _saudio.backend.thread.thread_handle = 0;
1754 }
1755 if (_saudio.backend.audio_client) {
1756 IAudioClient_Stop(_saudio.backend.audio_client);
1757 }
1758 _saudio_wasapi_release();
1759 CoUninitialize();
1760 }
1761
1762 // ██ ██ ███████ ██████ █████ ██ ██ ██████ ██ ██████
1763 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1764 // ██ █ ██ █████ ██████ ███████ ██ ██ ██ ██ ██ ██ ██
1765 // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1766 // ███ ███ ███████ ██████ ██ ██ ██████ ██████ ██ ██████
1767 //
1768 // >>webaudio
1769 #elif defined(_SAUDIO_EMSCRIPTEN)
1770
1771 #ifdef __cplusplus
1772 extern "C" {
1773 #endif
1774
1775 EMSCRIPTEN_KEEPALIVE int _saudio_emsc_pull(int num_frames) {
1776 SOKOL_ASSERT(_saudio.backend.buffer);
1777 if (num_frames == _saudio.buffer_frames) {
1778 if (_saudio_has_callback()) {
1779 _saudio_stream_callback((float*)_saudio.backend.buffer, num_frames, _saudio.num_channels);
1780 }
1781 else {
1782 const int num_bytes = num_frames * _saudio.bytes_per_frame;
1783 if (0 == _saudio_fifo_read(&_saudio.fifo, _saudio.backend.buffer, num_bytes)) {
1784 /* not enough read data available, fill the entire buffer with silence */
1785 _saudio_clear(_saudio.backend.buffer, (size_t)num_bytes);
1786 }
1787 }
1788 int res = (int) _saudio.backend.buffer;
1789 return res;
1790 }
1791 else {
1792 return 0;
1793 }
1794 }
1795
1796 #ifdef __cplusplus
1797 } /* extern "C" */
1798 #endif
1799
1800 /* setup the WebAudio context and attach a ScriptProcessorNode */
1801 EM_JS(int, saudio_js_init, (int sample_rate, int num_channels, int buffer_size), {
1802 Module._saudio_context = null;
1803 Module._saudio_node = null;
1804 if (typeof AudioContext !== 'undefined') {
1805 Module._saudio_context = new AudioContext({
1806 sampleRate: sample_rate,
1807 latencyHint: 'interactive',
1808 });
1809 }
1810 else {
1811 Module._saudio_context = null;
1812 console.log('sokol_audio.h: no WebAudio support');
1813 }
1814 if (Module._saudio_context) {
1815 console.log('sokol_audio.h: sample rate ', Module._saudio_context.sampleRate);
1816 Module._saudio_node = Module._saudio_context.createScriptProcessor(buffer_size, 0, num_channels);
1817 Module._saudio_node.onaudioprocess = (event) => {
1818 const num_frames = event.outputBuffer.length;
1819 const ptr = __saudio_emsc_pull(num_frames);
1820 if (ptr) {
1821 const num_channels = event.outputBuffer.numberOfChannels;
1822 for (let chn = 0; chn < num_channels; chn++) {
1823 const chan = event.outputBuffer.getChannelData(chn);
1824 for (let i = 0; i < num_frames; i++) {
1825 chan[i] = HEAPF32[(ptr>>2) + ((num_channels*i)+chn)]
1826 }
1827 }
1828 }
1829 };
1830 Module._saudio_node.connect(Module._saudio_context.destination);
1831
1832 // in some browsers, WebAudio needs to be activated on a user action
1833 const resume_webaudio = () => {
1834 if (Module._saudio_context) {
1835 if (Module._saudio_context.state === 'suspended') {
1836 Module._saudio_context.resume();
1837 }
1838 }
1839 };
1840 document.addEventListener('click', resume_webaudio, {once:true});
1841 document.addEventListener('touchend', resume_webaudio, {once:true});
1842 document.addEventListener('keydown', resume_webaudio, {once:true});
1843 return 1;
1844 }
1845 else {
1846 return 0;
1847 }
1848 });
1849
1850 /* shutdown the WebAudioContext and ScriptProcessorNode */
1851 EM_JS(void, saudio_js_shutdown, (void), {
1852 \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
1853 const ctx = Module._saudio_context;
1854 if (ctx !== null) {
1855 if (Module._saudio_node) {
1856 Module._saudio_node.disconnect();
1857 }
1858 ctx.close();
1859 Module._saudio_context = null;
1860 Module._saudio_node = null;
1861 }
1862 });
1863
1864 /* get the actual sample rate back from the WebAudio context */
1865 EM_JS(int, saudio_js_sample_rate, (void), {
1866 if (Module._saudio_context) {
1867 return Module._saudio_context.sampleRate;
1868 }
1869 else {
1870 return 0;
1871 }
1872 });
1873
1874 /* get the actual buffer size in number of frames */
1875 EM_JS(int, saudio_js_buffer_frames, (void), {
1876 if (Module._saudio_node) {
1877 return Module._saudio_node.bufferSize;
1878 }
1879 else {
1880 return 0;
1881 }
1882 });
1883
1884 /* return 1 if the WebAudio context is currently suspended, else 0 */
1885 EM_JS(int, saudio_js_suspended, (void), {
1886 if (Module._saudio_context) {
1887 if (Module._saudio_context.state === 'suspended') {
1888 return 1;
1889 }
1890 else {
1891 return 0;
1892 }
1893 }
1894 });
1895
1896 _SOKOL_PRIVATE bool _saudio_webaudio_backend_init(void) {
1897 if (saudio_js_init(_saudio.sample_rate, _saudio.num_channels, _saudio.buffer_frames)) {
1898 _saudio.bytes_per_frame = (int)sizeof(float) * _saudio.num_channels;
1899 _saudio.sample_rate = saudio_js_sample_rate();
1900 _saudio.buffer_frames = saudio_js_buffer_frames();
1901 const size_t buf_size = (size_t) (_saudio.buffer_frames * _saudio.bytes_per_frame);
1902 _saudio.backend.buffer = (uint8_t*) _saudio_malloc(buf_size);
1903 return true;
1904 }
1905 else {
1906 return false;
1907 }
1908 }
1909
1910 _SOKOL_PRIVATE void _saudio_webaudio_backend_shutdown(void) {
1911 saudio_js_shutdown();
1912 if (_saudio.backend.buffer) {
1913 _saudio_free(_saudio.backend.buffer);
1914 _saudio.backend.buffer = 0;
1915 }
1916 }
1917
1918 // █████ █████ ██ ██ ██████ ██ ██████
1919 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1920 // ███████ ███████ ██ ██ ██ ██ ██ ██ ██
1921 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
1922 // ██ ██ ██ ██ ██████ ██████ ██ ██████
1923 //
1924 // >>aaudio
1925 #elif defined(SAUDIO_ANDROID_AAUDIO)
1926
1927 _SOKOL_PRIVATE aaudio_data_callback_result_t _saudio_aaudio_data_callback(AAudioStream* stream, void* user_data, void* audio_data, int32_t num_frames) {
1928 _SOKOL_UNUSED(user_data);
1929 _SOKOL_UNUSED(stream);
1930 if (_saudio_has_callback()) {
1931 _saudio_stream_callback((float*)audio_data, (int)num_frames, _saudio.num_channels);
1932 }
1933 else {
1934 uint8_t* ptr = (uint8_t*)audio_data;
1935 int num_bytes = _saudio.bytes_per_frame * num_frames;
1936 if (0 == _saudio_fifo_read(&_saudio.fifo, ptr, num_bytes)) {
1937 // not enough read data available, fill the entire buffer with silence
1938 memset(ptr, 0, (size_t)num_bytes);
1939 }
1940 }
1941 return AAUDIO_CALLBACK_RESULT_CONTINUE;
1942 }
1943
1944 _SOKOL_PRIVATE bool _saudio_aaudio_start_stream(void) {
1945 if (AAudioStreamBuilder_openStream(_saudio.backend.builder, &_saudio.backend.stream) != AAUDIO_OK) {
1946 _SAUDIO_ERROR(AAUDIO_STREAMBUILDER_OPEN_STREAM_FAILED);
1947 return false;
1948 }
1949 AAudioStream_requestStart(_saudio.backend.stream);
1950 return true;
1951 }
1952
1953 _SOKOL_PRIVATE void _saudio_aaudio_stop_stream(void) {
1954 if (_saudio.backend.stream) {
1955 AAudioStream_requestStop(_saudio.backend.stream);
1956 AAudioStream_close(_saudio.backend.stream);
1957 _saudio.backend.stream = 0;
1958 }
1959 }
1960
1961 _SOKOL_PRIVATE void* _saudio_aaudio_restart_stream_thread_fn(void* param) {
1962 _SOKOL_UNUSED(param);
1963 _SAUDIO_WARN(AAUDIO_RESTARTING_STREAM_AFTER_ERROR);
1964 pthread_mutex_lock(&_saudio.backend.mutex);
1965 _saudio_aaudio_stop_stream();
1966 _saudio_aaudio_start_stream();
1967 pthread_mutex_unlock(&_saudio.backend.mutex);
1968 return 0;
1969 }
1970
1971 _SOKOL_PRIVATE void _saudio_aaudio_error_callback(AAudioStream* stream, void* user_data, aaudio_result_t error) {
1972 _SOKOL_UNUSED(stream);
1973 _SOKOL_UNUSED(user_data);
1974 if (error == AAUDIO_ERROR_DISCONNECTED) {
1975 if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_aaudio_restart_stream_thread_fn, 0)) {
1976 _SAUDIO_ERROR(AAUDIO_PTHREAD_CREATE_FAILED);
1977 }
1978 }
1979 }
1980
1981 _SOKOL_PRIVATE void _saudio_aaudio_backend_shutdown(void) {
1982 pthread_mutex_lock(&_saudio.backend.mutex);
1983 _saudio_aaudio_stop_stream();
1984 pthread_mutex_unlock(&_saudio.backend.mutex);
1985 if (_saudio.backend.builder) {
1986 AAudioStreamBuilder_delete(_saudio.backend.builder);
1987 _saudio.backend.builder = 0;
1988 }
1989 pthread_mutex_destroy(&_saudio.backend.mutex);
1990 }
1991
1992 _SOKOL_PRIVATE bool _saudio_aaudio_backend_init(void) {
1993 _SAUDIO_INFO(USING_AAUDIO_BACKEND);
1994
1995 _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
1996
1997 pthread_mutexattr_t attr;
1998 pthread_mutexattr_init(&attr);
1999 pthread_mutex_init(&_saudio.backend.mutex, &attr);
2000
2001 if (AAudio_createStreamBuilder(&_saudio.backend.builder) != AAUDIO_OK) {
2002 _SAUDIO_ERROR(AAUDIO_CREATE_STREAMBUILDER_FAILED);
2003 _saudio_aaudio_backend_shutdown();
2004 return false;
2005 }
2006
2007 AAudioStreamBuilder_setFormat(_saudio.backend.builder, AAUDIO_FORMAT_PCM_FLOAT);
2008 AAudioStreamBuilder_setSampleRate(_saudio.backend.builder, _saudio.sample_rate);
2009 AAudioStreamBuilder_setChannelCount(_saudio.backend.builder, _saudio.num_channels);
2010 AAudioStreamBuilder_setBufferCapacityInFrames(_saudio.backend.builder, _saudio.buffer_frames * 2);
2011 AAudioStreamBuilder_setFramesPerDataCallback(_saudio.backend.builder, _saudio.buffer_frames);
2012 AAudioStreamBuilder_setDataCallback(_saudio.backend.builder, _saudio_aaudio_data_callback, 0);
2013 AAudioStreamBuilder_setErrorCallback(_saudio.backend.builder, _saudio_aaudio_error_callback, 0);
2014
2015 if (!_saudio_aaudio_start_stream()) {
2016 _saudio_aaudio_backend_shutdown();
2017 return false;
2018 }
2019
2020 return true;
2021 }
2022
2023 // ██████ ██████ ███████ ███ ██ ███████ ██ ███████ ███████
2024 // ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██
2025 // ██ ██ ██████ █████ ██ ██ ██ ███████ ██ █████ ███████
2026 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
2027 // ██████ ██ ███████ ██ ████ ███████ ███████ ███████ ███████
2028 //
2029 // >>opensles
2030 // >>sles
2031 #elif defined(SAUDIO_ANDROID_SLES)
2032
2033 _SOKOL_PRIVATE void _saudio_sles_semaphore_init(_saudio_sles_semaphore_t* sem) {
2034 sem->count = 0;
2035 int r = pthread_mutex_init(&sem->mutex, NULL);
2036 SOKOL_ASSERT(r == 0);
2037 r = pthread_cond_init(&sem->cond, NULL);
2038 SOKOL_ASSERT(r == 0);
2039 (void)(r);
2040 }
2041
2042 _SOKOL_PRIVATE void _saudio_sles_semaphore_destroy(_saudio_sles_semaphore_t* sem) {
2043 pthread_cond_destroy(&sem->cond);
2044 pthread_mutex_destroy(&sem->mutex);
2045 }
2046
2047 _SOKOL_PRIVATE void _saudio_sles_semaphore_post(_saudio_sles_semaphore_t* sem, int count) {
2048 int r = pthread_mutex_lock(&sem->mutex);
2049 SOKOL_ASSERT(r == 0);
2050 for (int ii = 0; ii < count; ii++) {
2051 r = pthread_cond_signal(&sem->cond);
2052 SOKOL_ASSERT(r == 0);
2053 }
2054 sem->count += count;
2055 r = pthread_mutex_unlock(&sem->mutex);
2056 SOKOL_ASSERT(r == 0);
2057 (void)(r);
2058 }
2059
2060 _SOKOL_PRIVATE bool _saudio_sles_semaphore_wait(_saudio_sles_semaphore_t* sem) {
2061 int r = pthread_mutex_lock(&sem->mutex);
2062 SOKOL_ASSERT(r == 0);
2063 while (r == 0 && sem->count <= 0) {
2064 r = pthread_cond_wait(&sem->cond, &sem->mutex);
2065 }
2066 bool ok = (r == 0);
2067 if (ok) {
2068 --sem->count;
2069 }
2070 r = pthread_mutex_unlock(&sem->mutex);
2071 (void)(r);
2072 return ok;
2073 }
2074
2075 /* fill intermediate buffer with new data and reset buffer_pos */
2076 _SOKOL_PRIVATE void _saudio_sles_fill_buffer(void) {
2077 int src_buffer_frames = _saudio.buffer_frames;
2078 if (_saudio_has_callback()) {
2079 _saudio_stream_callback(_saudio.backend.src_buffer, src_buffer_frames, _saudio.num_channels);
2080 }
2081 else {
2082 const int src_buffer_byte_size = src_buffer_frames * _saudio.num_channels * (int)sizeof(float);
2083 if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.src_buffer, src_buffer_byte_size)) {
2084 /* not enough read data available, fill the entire buffer with silence */
2085 _saudio_clear(_saudio.backend.src_buffer, (size_t)src_buffer_byte_size);
2086 }
2087 }
2088 }
2089
2090 _SOKOL_PRIVATE void SLAPIENTRY _saudio_sles_play_cb(SLPlayItf player, void *context, SLuint32 event) {
2091 _SOKOL_UNUSED(context);
2092 _SOKOL_UNUSED(player);
2093 if (event & SL_PLAYEVENT_HEADATEND) {
2094 _saudio_sles_semaphore_post(&_saudio.backend.buffer_sem, 1);
2095 }
2096 }
2097
2098 _SOKOL_PRIVATE void* _saudio_sles_thread_fn(void* param) {
2099 _SOKOL_UNUSED(param);
2100 while (!_saudio.backend.thread_stop) {
2101 /* get next output buffer, advance, next buffer. */
2102 int16_t* out_buffer = _saudio.backend.output_buffers[_saudio.backend.active_buffer];
2103 _saudio.backend.active_buffer = (_saudio.backend.active_buffer + 1) % SAUDIO_SLES_NUM_BUFFERS;
2104 int16_t* next_buffer = _saudio.backend.output_buffers[_saudio.backend.active_buffer];
2105
2106 /* queue this buffer */
2107 const int buffer_size_bytes = _saudio.buffer_frames * _saudio.num_channels * (int)sizeof(short);
2108 (*_saudio.backend.player_buffer_queue)->Enqueue(_saudio.backend.player_buffer_queue, out_buffer, (SLuint32)buffer_size_bytes);
2109
2110 /* fill the next buffer */
2111 _saudio_sles_fill_buffer();
2112 const int num_samples = _saudio.num_channels * _saudio.buffer_frames;
2113 for (int i = 0; i < num_samples; ++i) {
2114 next_buffer[i] = (int16_t) (_saudio.backend.src_buffer[i] * 0x7FFF);
2115 }
2116
2117 _saudio_sles_semaphore_wait(&_saudio.backend.buffer_sem);
2118 }
2119
2120 return 0;
2121 }
2122
2123 _SOKOL_PRIVATE void _saudio_sles_backend_shutdown(void) {
2124 _saudio.backend.thread_stop = 1;
2125 pthread_join(_saudio.backend.thread, 0);
2126
2127 if (_saudio.backend.player_obj) {
2128 (*_saudio.backend.player_obj)->Destroy(_saudio.backend.player_obj);
2129 }
2130
2131 if (_saudio.backend.output_mix_obj) {
2132 (*_saudio.backend.output_mix_obj)->Destroy(_saudio.backend.output_mix_obj);
2133 }
2134
2135 if (_saudio.backend.engine_obj) {
2136 (*_saudio.backend.engine_obj)->Destroy(_saudio.backend.engine_obj);
2137 }
2138
2139 for (int i = 0; i < SAUDIO_SLES_NUM_BUFFERS; i++) {
2140 _saudio_free(_saudio.backend.output_buffers[i]);
2141 }
2142 _saudio_free(_saudio.backend.src_buffer);
2143 }
2144
2145 _SOKOL_PRIVATE bool _saudio_sles_backend_init(void) {
2146 _SAUDIO_INFO(USING_SLES_BACKEND);
2147
2148 _saudio.bytes_per_frame = (int)sizeof(float) * _saudio.num_channels;
2149
2150 for (int i = 0; i < SAUDIO_SLES_NUM_BUFFERS; ++i) {
2151 const int buffer_size_bytes = (int)sizeof(int16_t) * _saudio.num_channels * _saudio.buffer_frames;
2152 _saudio.backend.output_buffers[i] = (int16_t*) _saudio_malloc_clear((size_t)buffer_size_bytes);
2153 }
2154
2155 {
2156 const int buffer_size_bytes = _saudio.bytes_per_frame * _saudio.buffer_frames;
2157 _saudio.backend.src_buffer = (float*) _saudio_malloc_clear((size_t)buffer_size_bytes);
2158 }
2159
2160 /* Create engine */
2161 const SLEngineOption opts[] = { { SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE } };
2162 if (slCreateEngine(&_saudio.backend.engine_obj, 1, opts, 0, NULL, NULL ) != SL_RESULT_SUCCESS) {
2163 _SAUDIO_ERROR(SLES_CREATE_ENGINE_FAILED);
2164 _saudio_sles_backend_shutdown();
2165 return false;
2166 }
2167
2168 (*_saudio.backend.engine_obj)->Realize(_saudio.backend.engine_obj, SL_BOOLEAN_FALSE);
2169 if ((*_saudio.backend.engine_obj)->GetInterface(_saudio.backend.engine_obj, SL_IID_ENGINE, &_saudio.backend.engine) != SL_RESULT_SUCCESS) {
2170 _SAUDIO_ERROR(SLES_ENGINE_GET_ENGINE_INTERFACE_FAILED);
2171 _saudio_sles_backend_shutdown();
2172 return false;
2173 }
2174
2175 /* Create output mix. */
2176 {
2177 const SLInterfaceID ids[] = { SL_IID_VOLUME };
2178 const SLboolean req[] = { SL_BOOLEAN_FALSE };
2179
2180 if ((*_saudio.backend.engine)->CreateOutputMix(_saudio.backend.engine, &_saudio.backend.output_mix_obj, 1, ids, req) != SL_RESULT_SUCCESS) {
2181 _SAUDIO_ERROR(SLES_CREATE_OUTPUT_MIX_FAILED);
2182 _saudio_sles_backend_shutdown();
2183 return false;
2184 }
2185 (*_saudio.backend.output_mix_obj)->Realize(_saudio.backend.output_mix_obj, SL_BOOLEAN_FALSE);
2186
2187 if ((*_saudio.backend.output_mix_obj)->GetInterface(_saudio.backend.output_mix_obj, SL_IID_VOLUME, &_saudio.backend.output_mix_vol) != SL_RESULT_SUCCESS) {
2188 _SAUDIO_WARN(SLES_MIXER_GET_VOLUME_INTERFACE_FAILED);
2189 }
2190 }
2191
2192 /* android buffer queue */
2193 _saudio.backend.in_locator.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
2194 _saudio.backend.in_locator.numBuffers = SAUDIO_SLES_NUM_BUFFERS;
2195
2196 /* data format */
2197 SLDataFormat_PCM format;
2198 format.formatType = SL_DATAFORMAT_PCM;
2199 format.numChannels = (SLuint32)_saudio.num_channels;
2200 format.samplesPerSec = (SLuint32) (_saudio.sample_rate * 1000);
2201 format.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
2202 format.containerSize = 16;
2203 format.endianness = SL_BYTEORDER_LITTLEENDIAN;
2204
2205 if (_saudio.num_channels == 2) {
2206 format.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
2207 } else {
2208 format.channelMask = SL_SPEAKER_FRONT_CENTER;
2209 }
2210
2211 SLDataSource src;
2212 src.pLocator = &_saudio.backend.in_locator;
2213 src.pFormat = &format;
2214
2215 /* Output mix. */
2216 _saudio.backend.out_locator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
2217 _saudio.backend.out_locator.outputMix = _saudio.backend.output_mix_obj;
2218
2219 _saudio.backend.dst_data_sink.pLocator = &_saudio.backend.out_locator;
2220 _saudio.backend.dst_data_sink.pFormat = NULL;
2221
2222 /* setup player */
2223 {
2224 const SLInterfaceID ids[] = { SL_IID_VOLUME, SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
2225 const SLboolean req[] = { SL_BOOLEAN_FALSE, SL_BOOLEAN_TRUE };
2226
2227 if ((*_saudio.backend.engine)->CreateAudioPlayer(_saudio.backend.engine, &_saudio.backend.player_obj, &src, &_saudio.backend.dst_data_sink, sizeof(ids) / sizeof(ids[0]), ids, req) != SL_RESULT_SUCCESS)
2228 {
2229 _SAUDIO_ERROR(SLES_ENGINE_CREATE_AUDIO_PLAYER_FAILED);
2230 _saudio_sles_backend_shutdown();
2231 return false;
2232 }
2233 (*_saudio.backend.player_obj)->Realize(_saudio.backend.player_obj, SL_BOOLEAN_FALSE);
2234
2235 if ((*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_PLAY, &_saudio.backend.player) != SL_RESULT_SUCCESS) {
2236 _SAUDIO_ERROR(SLES_PLAYER_GET_PLAY_INTERFACE_FAILED);
2237 _saudio_sles_backend_shutdown();
2238 return false;
2239 }
2240 if ((*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_VOLUME, &_saudio.backend.player_vol) != SL_RESULT_SUCCESS) {
2241 _SAUDIO_ERROR(SLES_PLAYER_GET_VOLUME_INTERFACE_FAILED);
2242 }
2243 if ((*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &_saudio.backend.player_buffer_queue) != SL_RESULT_SUCCESS) {
2244 _SAUDIO_ERROR(SLES_PLAYER_GET_BUFFERQUEUE_INTERFACE_FAILED);
2245 _saudio_sles_backend_shutdown();
2246 return false;
2247 }
2248 }
2249
2250 /* begin */
2251 {
2252 const int buffer_size_bytes = (int)sizeof(int16_t) * _saudio.num_channels * _saudio.buffer_frames;
2253 (*_saudio.backend.player_buffer_queue)->Enqueue(_saudio.backend.player_buffer_queue, _saudio.backend.output_buffers[0], (SLuint32)buffer_size_bytes);
2254 _saudio.backend.active_buffer = (_saudio.backend.active_buffer + 1) % SAUDIO_SLES_NUM_BUFFERS;
2255
2256 (*_saudio.backend.player)->RegisterCallback(_saudio.backend.player, _saudio_sles_play_cb, NULL);
2257 (*_saudio.backend.player)->SetCallbackEventsMask(_saudio.backend.player, SL_PLAYEVENT_HEADATEND);
2258 (*_saudio.backend.player)->SetPlayState(_saudio.backend.player, SL_PLAYSTATE_PLAYING);
2259 }
2260
2261 /* create the buffer-streaming start thread */
2262 if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_sles_thread_fn, 0)) {
2263 _saudio_sles_backend_shutdown();
2264 return false;
2265 }
2266
2267 return true;
2268 }
2269
2270 // ██████ ██████ ██████ ███████ █████ ██ ██ ██████ ██ ██████
2271 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
2272 // ██ ██ ██ ██████ █████ ███████ ██ ██ ██ ██ ██ ██ ██
2273 // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
2274 // ██████ ██████ ██ ██ ███████ ██ ██ ██████ ██████ ██ ██████
2275 //
2276 // >>coreaudio
2277 #elif defined(_SAUDIO_APPLE)
2278
2279 #if defined(_SAUDIO_IOS)
2280 #if __has_feature(objc_arc)
2281 #define _SAUDIO_OBJC_RELEASE(obj) { obj = nil; }
2282 #else
2283 #define _SAUDIO_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
2284 #endif
2285
2286 @interface _saudio_interruption_handler : NSObject { }
2287 @end
2288
2289 @implementation _saudio_interruption_handler
2290 -(id)init {
2291 self = [super init];
2292 AVAudioSession* session = [AVAudioSession sharedInstance];
2293 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_interruption:) name:AVAudioSessionInterruptionNotification object:session];
2294 return self;
2295 }
2296
2297 -(void)dealloc {
2298 [self remove_handler];
2299 #if !__has_feature(objc_arc)
2300 [super dealloc];
2301 #endif
2302 }
2303
2304 -(void)remove_handler {
2305 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVAudioSessionInterruptionNotification" object:nil];
2306 }
2307
2308 -(void)handle_interruption:(NSNotification*)notification {
2309 AVAudioSession* session = [AVAudioSession sharedInstance];
2310 SOKOL_ASSERT(session);
2311 NSDictionary* dict = notification.userInfo;
2312 SOKOL_ASSERT(dict);
2313 NSInteger type = [[dict valueForKey:AVAudioSessionInterruptionTypeKey] integerValue];
2314 switch (type) {
2315 case AVAudioSessionInterruptionTypeBegan:
2316 if (_saudio.backend.ca_audio_queue) {
2317 AudioQueuePause(_saudio.backend.ca_audio_queue);
2318 }
2319 [session setActive:false error:nil];
2320 break;
2321 case AVAudioSessionInterruptionTypeEnded:
2322 [session setActive:true error:nil];
2323 if (_saudio.backend.ca_audio_queue) {
2324 AudioQueueStart(_saudio.backend.ca_audio_queue, NULL);
2325 }
2326 break;
2327 default:
2328 break;
2329 }
2330 }
2331 @end
2332 #endif // _SAUDIO_IOS
2333
2334 /* NOTE: the buffer data callback is called on a separate thread! */
2335 _SOKOL_PRIVATE void _saudio_coreaudio_callback(void* user_data, _saudio_AudioQueueRef queue, _saudio_AudioQueueBufferRef buffer) {
2336 _SOKOL_UNUSED(user_data);
2337 if (_saudio_has_callback()) {
2338 const int num_frames = (int)buffer->mAudioDataByteSize / _saudio.bytes_per_frame;
2339 const int num_channels = _saudio.num_channels;
2340 _saudio_stream_callback((float*)buffer->mAudioData, num_frames, num_channels);
2341 }
2342 else {
2343 uint8_t* ptr = (uint8_t*)buffer->mAudioData;
2344 int num_bytes = (int) buffer->mAudioDataByteSize;
2345 if (0 == _saudio_fifo_read(&_saudio.fifo, ptr, num_bytes)) {
2346 /* not enough read data available, fill the entire buffer with silence */
2347 _saudio_clear(ptr, (size_t)num_bytes);
2348 }
2349 }
2350 AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);
2351 }
2352
2353 _SOKOL_PRIVATE void _saudio_coreaudio_backend_shutdown(void) {
2354 if (_saudio.backend.ca_audio_queue) {
2355 AudioQueueStop(_saudio.backend.ca_audio_queue, true);
2356 AudioQueueDispose(_saudio.backend.ca_audio_queue, false);
2357 _saudio.backend.ca_audio_queue = 0;
2358 }
2359 #if defined(_SAUDIO_IOS)
2360 /* remove interruption handler */
2361 if (_saudio.backend.ca_interruption_handler != nil) {
2362 [_saudio.backend.ca_interruption_handler remove_handler];
2363 _SAUDIO_OBJC_RELEASE(_saudio.backend.ca_interruption_handler);
2364 }
2365 /* deactivate audio session */
2366 AVAudioSession* session = [AVAudioSession sharedInstance];
2367 SOKOL_ASSERT(session);
2368 [session setActive:false error:nil];;
2369 #endif // _SAUDIO_IOS
2370 }
2371
2372 _SOKOL_PRIVATE bool _saudio_coreaudio_backend_init(void) {
2373 SOKOL_ASSERT(0 == _saudio.backend.ca_audio_queue);
2374
2375 #if defined(_SAUDIO_IOS)
2376 /* activate audio session */
2377 AVAudioSession* session = [AVAudioSession sharedInstance];
2378 SOKOL_ASSERT(session != nil);
2379 [session setCategory: AVAudioSessionCategoryPlayback error:nil];
2380 [session setActive:true error:nil];
2381
2382 /* create interruption handler */
2383 _saudio.backend.ca_interruption_handler = [[_saudio_interruption_handler alloc] init];
2384 #endif
2385
2386 /* create an audio queue with fp32 samples */
2387 _saudio_AudioStreamBasicDescription fmt;
2388 _saudio_clear(&fmt, sizeof(fmt));
2389 fmt.mSampleRate = (double) _saudio.sample_rate;
2390 fmt.mFormatID = _saudio_kAudioFormatLinearPCM;
2391 fmt.mFormatFlags = _saudio_kLinearPCMFormatFlagIsFloat | _saudio_kAudioFormatFlagIsPacked;
2392 fmt.mFramesPerPacket = 1;
2393 fmt.mChannelsPerFrame = (uint32_t) _saudio.num_channels;
2394 fmt.mBytesPerFrame = (uint32_t)sizeof(float) * (uint32_t)_saudio.num_channels;
2395 fmt.mBytesPerPacket = fmt.mBytesPerFrame;
2396 fmt.mBitsPerChannel = 32;
2397 _saudio_OSStatus res = AudioQueueNewOutput(&fmt, _saudio_coreaudio_callback, 0, NULL, NULL, 0, &_saudio.backend.ca_audio_queue);
2398 if (0 != res) {
2399 _SAUDIO_ERROR(COREAUDIO_NEW_OUTPUT_FAILED);
2400 return false;
2401 }
2402 SOKOL_ASSERT(_saudio.backend.ca_audio_queue);
2403
2404 /* create 2 audio buffers */
2405 for (int i = 0; i < 2; i++) {
2406 _saudio_AudioQueueBufferRef buf = NULL;
2407 const uint32_t buf_byte_size = (uint32_t)_saudio.buffer_frames * fmt.mBytesPerFrame;
2408 res = AudioQueueAllocateBuffer(_saudio.backend.ca_audio_queue, buf_byte_size, &buf);
2409 if (0 != res) {
2410 _SAUDIO_ERROR(COREAUDIO_ALLOCATE_BUFFER_FAILED);
2411 _saudio_coreaudio_backend_shutdown();
2412 return false;
2413 }
2414 buf->mAudioDataByteSize = buf_byte_size;
2415 _saudio_clear(buf->mAudioData, buf->mAudioDataByteSize);
2416 AudioQueueEnqueueBuffer(_saudio.backend.ca_audio_queue, buf, 0, NULL);
2417 }
2418
2419 /* init or modify actual playback parameters */
2420 _saudio.bytes_per_frame = (int)fmt.mBytesPerFrame;
2421
2422 /* ...and start playback */
2423 res = AudioQueueStart(_saudio.backend.ca_audio_queue, NULL);
2424 if (0 != res) {
2425 _SAUDIO_ERROR(COREAUDIO_START_FAILED);
2426 _saudio_coreaudio_backend_shutdown();
2427 return false;
2428 }
2429 return true;
2430 }
2431
2432 #else
2433 #error "unsupported platform"
2434 #endif
2435
2436 bool _saudio_backend_init(void) {
2437 #if defined(SOKOL_DUMMY_BACKEND)
2438 return _saudio_dummy_backend_init();
2439 #elif defined(_SAUDIO_LINUX)
2440 return _saudio_alsa_backend_init();
2441 #elif defined(_SAUDIO_WINDOWS)
2442 return _saudio_wasapi_backend_init();
2443 #elif defined(_SAUDIO_EMSCRIPTEN)
2444 return _saudio_webaudio_backend_init();
2445 #elif defined(SAUDIO_ANDROID_AAUDIO)
2446 return _saudio_aaudio_backend_init();
2447 #elif defined(SAUDIO_ANDROID_SLES)
2448 return _saudio_sles_backend_init();
2449 #elif defined(_SAUDIO_APPLE)
2450 return _saudio_coreaudio_backend_init();
2451 #else
2452 #error "unknown platform"
2453 #endif
2454 }
2455
2456 void _saudio_backend_shutdown(void) {
2457 #if defined(SOKOL_DUMMY_BACKEND)
2458 _saudio_dummy_backend_shutdown();
2459 #elif defined(_SAUDIO_LINUX)
2460 _saudio_alsa_backend_shutdown();
2461 #elif defined(_SAUDIO_WINDOWS)
2462 _saudio_wasapi_backend_shutdown();
2463 #elif defined(_SAUDIO_EMSCRIPTEN)
2464 _saudio_webaudio_backend_shutdown();
2465 #elif defined(SAUDIO_ANDROID_AAUDIO)
2466 _saudio_aaudio_backend_shutdown();
2467 #elif defined(SAUDIO_ANDROID_SLES)
2468 _saudio_sles_backend_shutdown();
2469 #elif defined(_SAUDIO_APPLE)
2470 return _saudio_coreaudio_backend_shutdown();
2471 #else
2472 #error "unknown platform"
2473 #endif
2474 }
2475
2476 // ██████ ██ ██ ██████ ██ ██ ██████
2477 // ██ ██ ██ ██ ██ ██ ██ ██ ██
2478 // ██████ ██ ██ ██████ ██ ██ ██
2479 // ██ ██ ██ ██ ██ ██ ██ ██
2480 // ██ ██████ ██████ ███████ ██ ██████
2481 //
2482 // >>public
2483 SOKOL_API_IMPL void saudio_setup(const saudio_desc* desc) {
2484 SOKOL_ASSERT(!_saudio.valid);
2485 SOKOL_ASSERT(desc);
2486 SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
2487 _saudio_clear(&_saudio, sizeof(_saudio));
2488 _saudio.desc = *desc;
2489 _saudio.stream_cb = desc->stream_cb;
2490 _saudio.stream_userdata_cb = desc->stream_userdata_cb;
2491 _saudio.user_data = desc->user_data;
2492 _saudio.sample_rate = _saudio_def(_saudio.desc.sample_rate, _SAUDIO_DEFAULT_SAMPLE_RATE);
2493 _saudio.buffer_frames = _saudio_def(_saudio.desc.buffer_frames, _SAUDIO_DEFAULT_BUFFER_FRAMES);
2494 _saudio.packet_frames = _saudio_def(_saudio.desc.packet_frames, _SAUDIO_DEFAULT_PACKET_FRAMES);
2495 _saudio.num_packets = _saudio_def(_saudio.desc.num_packets, _SAUDIO_DEFAULT_NUM_PACKETS);
2496 _saudio.num_channels = _saudio_def(_saudio.desc.num_channels, 1);
2497 _saudio_fifo_init_mutex(&_saudio.fifo);
2498 if (_saudio_backend_init()) {
2499 /* the backend might not support the requested exact buffer size,
2500 make sure the actual buffer size is still a multiple of
2501 the requested packet size
2502 */
2503 if (0 != (_saudio.buffer_frames % _saudio.packet_frames)) {
2504 _SAUDIO_ERROR(BACKEND_BUFFER_SIZE_ISNT_MULTIPLE_OF_PACKET_SIZE);
2505 _saudio_backend_shutdown();
2506 return;
2507 }
2508 SOKOL_ASSERT(_saudio.bytes_per_frame > 0);
2509 _saudio_fifo_init(&_saudio.fifo, _saudio.packet_frames * _saudio.bytes_per_frame, _saudio.num_packets);
2510 _saudio.valid = true;
2511 }
2512 else {
2513 _saudio_fifo_destroy_mutex(&_saudio.fifo);
2514 }
2515 }
2516
2517 SOKOL_API_IMPL void saudio_shutdown(void) {
2518 if (_saudio.valid) {
2519 _saudio_backend_shutdown();
2520 _saudio_fifo_shutdown(&_saudio.fifo);
2521 _saudio_fifo_destroy_mutex(&_saudio.fifo);
2522 _saudio.valid = false;
2523 }
2524 }
2525
2526 SOKOL_API_IMPL bool saudio_isvalid(void) {
2527 return _saudio.valid;
2528 }
2529
2530 SOKOL_API_IMPL void* saudio_userdata(void) {
2531 return _saudio.desc.user_data;
2532 }
2533
2534 SOKOL_API_IMPL saudio_desc saudio_query_desc(void) {
2535 return _saudio.desc;
2536 }
2537
2538 SOKOL_API_IMPL int saudio_sample_rate(void) {
2539 return _saudio.sample_rate;
2540 }
2541
2542 SOKOL_API_IMPL int saudio_buffer_frames(void) {
2543 return _saudio.buffer_frames;
2544 }
2545
2546 SOKOL_API_IMPL int saudio_channels(void) {
2547 return _saudio.num_channels;
2548 }
2549
2550 SOKOL_API_IMPL bool saudio_suspended(void) {
2551 #if defined(_SAUDIO_EMSCRIPTEN)
2552 if (_saudio.valid) {
2553 return 1 == saudio_js_suspended();
2554 }
2555 else {
2556 return false;
2557 }
2558 #else
2559 return false;
2560 #endif
2561 }
2562
2563 SOKOL_API_IMPL int saudio_expect(void) {
2564 if (_saudio.valid) {
2565 const int num_frames = _saudio_fifo_writable_bytes(&_saudio.fifo) / _saudio.bytes_per_frame;
2566 return num_frames;
2567 }
2568 else {
2569 return 0;
2570 }
2571 }
2572
2573 SOKOL_API_IMPL int saudio_push(const float* frames, int num_frames) {
2574 SOKOL_ASSERT(frames && (num_frames > 0));
2575 if (_saudio.valid) {
2576 const int num_bytes = num_frames * _saudio.bytes_per_frame;
2577 const int num_written = _saudio_fifo_write(&_saudio.fifo, (const uint8_t*)frames, num_bytes);
2578 return num_written / _saudio.bytes_per_frame;
2579 }
2580 else {
2581 return 0;
2582 }
2583 }
2584
2585 #undef _saudio_def
2586 #undef _saudio_def_flt
2587
2588 #if defined(_SAUDIO_WINDOWS)
2589 #ifdef _MSC_VER
2590 #pragma warning(pop)
2591 #endif
2592 #endif
2593
2594 #endif /* SOKOL_AUDIO_IMPL */