forked from floooh/sokol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sokol_audio.h
2596 lines (2253 loc) · 102 KB
/
sokol_audio.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if defined(SOKOL_IMPL) && !defined(SOKOL_AUDIO_IMPL)
#define SOKOL_AUDIO_IMPL
#endif
#ifndef SOKOL_AUDIO_INCLUDED
/*
sokol_audio.h -- cross-platform audio-streaming API
Project URL: https://github.com/floooh/sokol
Do this:
#define SOKOL_IMPL or
#define SOKOL_AUDIO_IMPL
before you include this file in *one* C or C++ file to create the
implementation.
Optionally provide the following defines with your own implementations:
SOKOL_DUMMY_BACKEND - use a dummy backend
SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
SOKOL_AUDIO_API_DECL- public function declaration prefix (default: extern)
SOKOL_API_DECL - same as SOKOL_AUDIO_API_DECL
SOKOL_API_IMPL - public function implementation prefix (default: -)
SAUDIO_RING_MAX_SLOTS - max number of slots in the push-audio ring buffer (default 1024)
SAUDIO_OSX_USE_SYSTEM_HEADERS - define this to force inclusion of system headers on
macOS instead of using embedded CoreAudio declarations
SAUDIO_ANDROID_AAUDIO - on Android, select the AAudio backend (default)
SAUDIO_ANDROID_SLES - on Android, select the OpenSLES backend
If sokol_audio.h is compiled as a DLL, define the following before
including the declaration or implementation:
SOKOL_DLL
On Windows, SOKOL_DLL will define SOKOL_AUDIO_API_DECL as __declspec(dllexport)
or __declspec(dllimport) as needed.
Link with the following libraries:
- on macOS: AudioToolbox
- on iOS: AudioToolbox, AVFoundation
- on Linux: asound
- on Android: link with OpenSLES or aaudio
- on Windows with MSVC or Clang toolchain: no action needed, libs are defined in-source via pragma-comment-lib
- on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' and link with -lole32
FEATURE OVERVIEW
================
You provide a mono- or stereo-stream of 32-bit float samples, which
Sokol Audio feeds into platform-specific audio backends:
- Windows: WASAPI
- Linux: ALSA
- macOS: CoreAudio
- iOS: CoreAudio+AVAudioSession
- emscripten: WebAudio with ScriptProcessorNode
- Android: AAudio (default) or OpenSLES, select at build time
Sokol Audio will not do any buffer mixing or volume control, if you have
multiple independent input streams of sample data you need to perform the
mixing yourself before forwarding the data to Sokol Audio.
There are two mutually exclusive ways to provide the sample data:
1. Callback model: You provide a callback function, which will be called
when Sokol Audio needs new samples. On all platforms except emscripten,
this function is called from a separate thread.
2. Push model: Your code pushes small blocks of sample data from your
main loop or a thread you created. The pushed data is stored in
a ring buffer where it is pulled by the backend code when
needed.
The callback model is preferred because it is the most direct way to
feed sample data into the audio backends and also has less moving parts
(there is no ring buffer between your code and the audio backend).
Sometimes it is not possible to generate the audio stream directly in a
callback function running in a separate thread, for such cases Sokol Audio
provides the push-model as a convenience.
SOKOL AUDIO, SOLOUD AND MINIAUDIO
=================================
The WASAPI, ALSA, OpenSLES and CoreAudio backend code has been taken from the
SoLoud library (with some modifications, so any bugs in there are most
likely my fault). If you need a more fully-featured audio solution, check
out SoLoud, it's excellent:
https://github.com/jarikomppa/soloud
Another alternative which feature-wise is somewhere inbetween SoLoud and
sokol-audio might be MiniAudio:
https://github.com/mackron/miniaudio
GLOSSARY
========
- stream buffer:
The internal audio data buffer, usually provided by the backend API. The
size of the stream buffer defines the base latency, smaller buffers have
lower latency but may cause audio glitches. Bigger buffers reduce or
eliminate glitches, but have a higher base latency.
- stream callback:
Optional callback function which is called by Sokol Audio when it
needs new samples. On Windows, macOS/iOS and Linux, this is called in
a separate thread, on WebAudio, this is called per-frame in the
browser thread.
- channel:
A discrete track of audio data, currently 1-channel (mono) and
2-channel (stereo) is supported and tested.
- sample:
The magnitude of an audio signal on one channel at a given time. In
Sokol Audio, samples are 32-bit float numbers in the range -1.0 to
+1.0.
- frame:
The tightly packed set of samples for all channels at a given time.
For mono 1 frame is 1 sample. For stereo, 1 frame is 2 samples.
- packet:
In Sokol Audio, a small chunk of audio data that is moved from the
main thread to the audio streaming thread in order to decouple the
rate at which the main thread provides new audio data, and the
streaming thread consuming audio data.
WORKING WITH SOKOL AUDIO
========================
First call saudio_setup() with your preferred audio playback options.
In most cases you can stick with the default values, these provide
a good balance between low-latency and glitch-free playback
on all audio backends.
You should always provide a logging callback to be aware of any
warnings and errors. The easiest way is to use sokol_log.h for this:
#include "sokol_log.h"
// ...
saudio_setup(&(saudio_desc){
.logger = {
.func = slog_func,
}
});
If you want to use the callback-model, you need to provide a stream
callback function either in saudio_desc.stream_cb or saudio_desc.stream_userdata_cb,
otherwise keep both function pointers zero-initialized.
Use push model and default playback parameters:
saudio_setup(&(saudio_desc){ .logger.func = slog_func });
Use stream callback model and default playback parameters:
saudio_setup(&(saudio_desc){
.stream_cb = my_stream_callback
.logger.func = slog_func,
});
The standard stream callback doesn't have a user data argument, if you want
that, use the alternative stream_userdata_cb and also set the user_data pointer:
saudio_setup(&(saudio_desc){
.stream_userdata_cb = my_stream_callback,
.user_data = &my_data
.logger.func = slog_func,
});
The following playback parameters can be provided through the
saudio_desc struct:
General parameters (both for stream-callback and push-model):
int sample_rate -- the sample rate in Hz, default: 44100
int num_channels -- number of channels, default: 1 (mono)
int buffer_frames -- number of frames in streaming buffer, default: 2048
The stream callback prototype (either with or without userdata):
void (*stream_cb)(float* buffer, int num_frames, int num_channels)
void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data)
Function pointer to the user-provide stream callback.
Push-model parameters:
int packet_frames -- number of frames in a packet, default: 128
int num_packets -- number of packets in ring buffer, default: 64
The sample_rate and num_channels parameters are only hints for the audio
backend, it isn't guaranteed that those are the values used for actual
playback.
To get the actual parameters, call the following functions after
saudio_setup():
int saudio_sample_rate(void)
int saudio_channels(void);
It's unlikely that the number of channels will be different than requested,
but a different sample rate isn't uncommon.
(NOTE: there's an yet unsolved issue when an audio backend might switch
to a different sample rate when switching output devices, for instance
plugging in a bluetooth headset, this case is currently not handled in
Sokol Audio).
You can check if audio initialization was successful with
saudio_isvalid(). If backend initialization failed for some reason
(for instance when there's no audio device in the machine), this
will return false. Not checking for success won't do any harm, all
Sokol Audio function will silently fail when called after initialization
has failed, so apart from missing audio output, nothing bad will happen.
Before your application exits, you should call
saudio_shutdown();
This stops the audio thread (on Linux, Windows and macOS/iOS) and
properly shuts down the audio backend.
THE STREAM CALLBACK MODEL
=========================
To use Sokol Audio in stream-callback-mode, provide a callback function
like this in the saudio_desc struct when calling saudio_setup():
void stream_cb(float* buffer, int num_frames, int num_channels) {
...
}
Or the alternative version with a user-data argument:
void stream_userdata_cb(float* buffer, int num_frames, int num_channels, void* user_data) {
my_data_t* my_data = (my_data_t*) user_data;
...
}
The job of the callback function is to fill the *buffer* with 32-bit
float sample values.
To output silence, fill the buffer with zeros:
void stream_cb(float* buffer, int num_frames, int num_channels) {
const int num_samples = num_frames * num_channels;
for (int i = 0; i < num_samples; i++) {
buffer[i] = 0.0f;
}
}
For stereo output (num_channels == 2), the samples for the left
and right channel are interleaved:
void stream_cb(float* buffer, int num_frames, int num_channels) {
assert(2 == num_channels);
for (int i = 0; i < num_frames; i++) {
buffer[2*i + 0] = ...; // left channel
buffer[2*i + 1] = ...; // right channel
}
}
Please keep in mind that the stream callback function is running in a
separate thread, if you need to share data with the main thread you need
to take care yourself to make the access to the shared data thread-safe!
THE PUSH MODEL
==============
To use the push-model for providing audio data, simply don't set (keep
zero-initialized) the stream_cb field in the saudio_desc struct when
calling saudio_setup().
To provide sample data with the push model, call the saudio_push()
function at regular intervals (for instance once per frame). You can
call the saudio_expect() function to ask Sokol Audio how much room is
in the ring buffer, but if you provide a continuous stream of data
at the right sample rate, saudio_expect() isn't required (it's a simple
way to sync/throttle your sample generation code with the playback
rate though).
With saudio_push() you may need to maintain your own intermediate sample
buffer, since pushing individual sample values isn't very efficient.
The following example is from the MOD player sample in
sokol-samples (https://github.com/floooh/sokol-samples):
const int num_frames = saudio_expect();
if (num_frames > 0) {
const int num_samples = num_frames * saudio_channels();
read_samples(flt_buf, num_samples);
saudio_push(flt_buf, num_frames);
}
Another option is to ignore saudio_expect(), and just push samples as they
are generated in small batches. In this case you *need* to generate the
samples at the right sample rate:
The following example is taken from the Tiny Emulators project
(https://github.com/floooh/chips-test), this is for mono playback,
so (num_samples == num_frames):
// tick the sound generator
if (ay38910_tick(&sys->psg)) {
// new sample is ready
sys->sample_buffer[sys->sample_pos++] = sys->psg.sample;
if (sys->sample_pos == sys->num_samples) {
// new sample packet is ready
saudio_push(sys->sample_buffer, sys->num_samples);
sys->sample_pos = 0;
}
}
THE WEBAUDIO BACKEND
====================
The WebAudio backend is currently using a ScriptProcessorNode callback to
feed the sample data into WebAudio. ScriptProcessorNode has been
deprecated for a while because it is running from the main thread, with
the default initialization parameters it works 'pretty well' though.
Ultimately Sokol Audio will use Audio Worklets, but this requires a few
more things to fall into place (Audio Worklets implemented everywhere,
SharedArrayBuffers enabled again, and I need to figure out a 'low-cost'
solution in terms of implementation effort, since Audio Worklets are
a lot more complex than ScriptProcessorNode if the audio data needs to come
from the main thread).
The WebAudio backend is automatically selected when compiling for
emscripten (__EMSCRIPTEN__ define exists).
https://developers.google.com/web/updates/2017/12/audio-worklet
https://developers.google.com/web/updates/2018/06/audio-worklet-design-pattern
"Blob URLs": https://www.html5rocks.com/en/tutorials/workers/basics/
Also see: https://blog.paul.cx/post/a-wait-free-spsc-ringbuffer-for-the-web/
THE COREAUDIO BACKEND
=====================
The CoreAudio backend is selected on macOS and iOS (__APPLE__ is defined).
Since the CoreAudio API is implemented in C (not Objective-C) on macOS the
implementation part of Sokol Audio can be included into a C source file.
However on iOS, Sokol Audio must be compiled as Objective-C due to it's
reliance on the AVAudioSession object. The iOS code path support both
being compiled with or without ARC (Automatic Reference Counting).
For thread synchronisation, the CoreAudio backend will use the
pthread_mutex_* functions.
The incoming floating point samples will be directly forwarded to
CoreAudio without further conversion.
macOS and iOS applications that use Sokol Audio need to link with
the AudioToolbox framework.
THE WASAPI BACKEND
==================
The WASAPI backend is automatically selected when compiling on Windows
(_WIN32 is defined).
For thread synchronisation a Win32 critical section is used.
WASAPI may use a different size for its own streaming buffer then requested,
so the base latency may be slightly bigger. The current backend implementation
converts the incoming floating point sample values to signed 16-bit
integers.
The required Windows system DLLs are linked with #pragma comment(lib, ...),
so you shouldn't need to add additional linker libs in the build process
(otherwise this is a bug which should be fixed in sokol_audio.h).
THE ALSA BACKEND
================
The ALSA backend is automatically selected when compiling on Linux
('linux' is defined).
For thread synchronisation, the pthread_mutex_* functions are used.
Samples are directly forwarded to ALSA in 32-bit float format, no
further conversion is taking place.
You need to link with the 'asound' library, and the <alsa/asoundlib.h>
header must be present (usually both are installed with some sort
of ALSA development package).
MEMORY ALLOCATION OVERRIDE
==========================
You can override the memory allocation functions at initialization time
like this:
void* my_alloc(size_t size, void* user_data) {
return malloc(size);
}
void my_free(void* ptr, void* user_data) {
free(ptr);
}
...
saudio_setup(&(saudio_desc){
// ...
.allocator = {
.alloc = my_alloc,
.free = my_free,
.user_data = ...,
}
});
...
If no overrides are provided, malloc and free will be used.
This only affects memory allocation calls done by sokol_audio.h
itself though, not any allocations in OS libraries.
Memory allocation will only happen on the same thread where saudio_setup()
was called, so you don't need to worry about thread-safety.
ERROR REPORTING AND LOGGING
===========================
To get any logging information at all you need to provide a logging callback in the setup call
the easiest way is to use sokol_log.h:
#include "sokol_log.h"
saudio_setup(&(saudio_desc){ .logger.func = slog_func });
To override logging with your own callback, first write a logging function like this:
void my_log(const char* tag, // e.g. 'saudio'
uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
uint32_t log_item_id, // SAUDIO_LOGITEM_*
const char* message_or_null, // a message string, may be nullptr in release mode
uint32_t line_nr, // line number in sokol_audio.h
const char* filename_or_null, // source filename, may be nullptr in release mode
void* user_data)
{
...
}
...and then setup sokol-audio like this:
saudio_setup(&(saudio_desc){
.logger = {
.func = my_log,
.user_data = my_user_data,
}
});
The provided logging function must be reentrant (e.g. be callable from
different threads).
If you don't want to provide your own custom logger it is highly recommended to use
the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
errors.
LICENSE
=======
zlib/libpng license
Copyright (c) 2018 Andre Weissflog
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#define SOKOL_AUDIO_INCLUDED (1)
#include <stddef.h> // size_t
#include <stdint.h>
#include <stdbool.h>
#if defined(SOKOL_API_DECL) && !defined(SOKOL_AUDIO_API_DECL)
#define SOKOL_AUDIO_API_DECL SOKOL_API_DECL
#endif
#ifndef SOKOL_AUDIO_API_DECL
#if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_AUDIO_IMPL)
#define SOKOL_AUDIO_API_DECL __declspec(dllexport)
#elif defined(_WIN32) && defined(SOKOL_DLL)
#define SOKOL_AUDIO_API_DECL __declspec(dllimport)
#else
#define SOKOL_AUDIO_API_DECL extern
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
saudio_log_item
Log items are defined via X-Macros, and expanded to an
enum 'saudio_log_item', and in debug mode only,
corresponding strings.
Used as parameter in the logging callback.
*/
#define _SAUDIO_LOG_ITEMS \
_SAUDIO_LOGITEM_XMACRO(OK, "Ok") \
_SAUDIO_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
_SAUDIO_LOGITEM_XMACRO(ALSA_SND_PCM_OPEN_FAILED, "snd_pcm_open() failed") \
_SAUDIO_LOGITEM_XMACRO(ALSA_FLOAT_SAMPLES_NOT_SUPPORTED, "floating point sample format not supported") \
_SAUDIO_LOGITEM_XMACRO(ALSA_REQUESTED_BUFFER_SIZE_NOT_SUPPORTED, "requested buffer size not supported") \
_SAUDIO_LOGITEM_XMACRO(ALSA_REQUESTED_CHANNEL_COUNT_NOT_SUPPORTED, "requested channel count not supported") \
_SAUDIO_LOGITEM_XMACRO(ALSA_SND_PCM_HW_PARAMS_SET_RATE_NEAR_FAILED, "snd_pcm_hw_params_set_rate_near() failed") \
_SAUDIO_LOGITEM_XMACRO(ALSA_SND_PCM_HW_PARAMS_FAILED, "snd_pcm_hw_params() failed") \
_SAUDIO_LOGITEM_XMACRO(ALSA_PTHREAD_CREATE_FAILED, "pthread_create() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_CREATE_EVENT_FAILED, "CreateEvent() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_CREATE_DEVICE_ENUMERATOR_FAILED, "CoCreateInstance() for IMMDeviceEnumerator failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_GET_DEFAULT_AUDIO_ENDPOINT_FAILED, "IMMDeviceEnumerator.GetDefaultAudioEndpoint() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_DEVICE_ACTIVATE_FAILED, "IMMDevice.Activate() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_INITIALIZE_FAILED, "IAudioClient.Initialize() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_GET_BUFFER_SIZE_FAILED, "IAudioClient.GetBufferSize() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_GET_SERVICE_FAILED, "IAudioClient.GetService() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_AUDIO_CLIENT_SET_EVENT_HANDLE_FAILED, "IAudioClient.SetEventHandle() failed") \
_SAUDIO_LOGITEM_XMACRO(WASAPI_CREATE_THREAD_FAILED, "CreateThread() failed") \
_SAUDIO_LOGITEM_XMACRO(AAUDIO_STREAMBUILDER_OPEN_STREAM_FAILED, "AAudioStreamBuilder_openStream() failed") \
_SAUDIO_LOGITEM_XMACRO(AAUDIO_PTHREAD_CREATE_FAILED, "pthread_create() failed after AAUDIO_ERROR_DISCONNECTED") \
_SAUDIO_LOGITEM_XMACRO(AAUDIO_RESTARTING_STREAM_AFTER_ERROR, "restarting AAudio stream after error") \
_SAUDIO_LOGITEM_XMACRO(USING_AAUDIO_BACKEND, "using AAudio backend") \
_SAUDIO_LOGITEM_XMACRO(AAUDIO_CREATE_STREAMBUILDER_FAILED, "AAudio_createStreamBuilder() failed") \
_SAUDIO_LOGITEM_XMACRO(USING_SLES_BACKEND, "using OpenSLES backend") \
_SAUDIO_LOGITEM_XMACRO(SLES_CREATE_ENGINE_FAILED, "slCreateEngine() failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_ENGINE_GET_ENGINE_INTERFACE_FAILED, "GetInterface() for SL_IID_ENGINE failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_CREATE_OUTPUT_MIX_FAILED, "CreateOutputMix() failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_MIXER_GET_VOLUME_INTERFACE_FAILED, "GetInterface() for SL_IID_VOLUME failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_ENGINE_CREATE_AUDIO_PLAYER_FAILED, "CreateAudioPlayer() failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_PLAYER_GET_PLAY_INTERFACE_FAILED, "GetInterface() for SL_IID_PLAY failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_PLAYER_GET_VOLUME_INTERFACE_FAILED, "GetInterface() for SL_IID_VOLUME failed") \
_SAUDIO_LOGITEM_XMACRO(SLES_PLAYER_GET_BUFFERQUEUE_INTERFACE_FAILED, "GetInterface() for SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed") \
_SAUDIO_LOGITEM_XMACRO(COREAUDIO_NEW_OUTPUT_FAILED, "AudioQueueNewOutput() failed") \
_SAUDIO_LOGITEM_XMACRO(COREAUDIO_ALLOCATE_BUFFER_FAILED, "AudioQueueAllocateBuffer() failed") \
_SAUDIO_LOGITEM_XMACRO(COREAUDIO_START_FAILED, "AudioQueueStart() failed") \
_SAUDIO_LOGITEM_XMACRO(BACKEND_BUFFER_SIZE_ISNT_MULTIPLE_OF_PACKET_SIZE, "backend buffer size isn't multiple of packet size") \
#define _SAUDIO_LOGITEM_XMACRO(item,msg) SAUDIO_LOGITEM_##item,
typedef enum saudio_log_item {
_SAUDIO_LOG_ITEMS
} saudio_log_item;
#undef _SAUDIO_LOGITEM_XMACRO
/*
saudio_logger
Used in saudio_desc to provide a custom logging and error reporting
callback to sokol-audio.
*/
typedef struct saudio_logger {
void (*func)(
const char* tag, // always "saudio"
uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
uint32_t log_item_id, // SAUDIO_LOGITEM_*
const char* message_or_null, // a message string, may be nullptr in release mode
uint32_t line_nr, // line number in sokol_audio.h
const char* filename_or_null, // source filename, may be nullptr in release mode
void* user_data);
void* user_data;
} saudio_logger;
/*
saudio_allocator
Used in saudio_desc to provide custom memory-alloc and -free functions
to sokol_audio.h. If memory management should be overridden, both the
alloc and free function must be provided (e.g. it's not valid to
override one function but not the other).
*/
typedef struct saudio_allocator {
void* (*alloc)(size_t size, void* user_data);
void (*free)(void* ptr, void* user_data);
void* user_data;
} saudio_allocator;
typedef struct saudio_desc {
int sample_rate; // requested sample rate
int num_channels; // number of channels, default: 1 (mono)
int buffer_frames; // number of frames in streaming buffer
int packet_frames; // number of frames in a packet
int num_packets; // number of packets in packet queue
void (*stream_cb)(float* buffer, int num_frames, int num_channels); // optional streaming callback (no user data)
void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data); //... and with user data
void* user_data; // optional user data argument for stream_userdata_cb
saudio_allocator allocator; // optional allocation override functions
saudio_logger logger; // optional logging function (default: NO LOGGING!)
} saudio_desc;
/* setup sokol-audio */
SOKOL_AUDIO_API_DECL void saudio_setup(const saudio_desc* desc);
/* shutdown sokol-audio */
SOKOL_AUDIO_API_DECL void saudio_shutdown(void);
/* true after setup if audio backend was successfully initialized */
SOKOL_AUDIO_API_DECL bool saudio_isvalid(void);
/* return the saudio_desc.user_data pointer */
SOKOL_AUDIO_API_DECL void* saudio_userdata(void);
/* return a copy of the original saudio_desc struct */
SOKOL_AUDIO_API_DECL saudio_desc saudio_query_desc(void);
/* actual sample rate */
SOKOL_AUDIO_API_DECL int saudio_sample_rate(void);
/* return actual backend buffer size in number of frames */
SOKOL_AUDIO_API_DECL int saudio_buffer_frames(void);
/* actual number of channels */
SOKOL_AUDIO_API_DECL int saudio_channels(void);
/* return true if audio context is currently suspended (only in WebAudio backend, all other backends return false) */
SOKOL_AUDIO_API_DECL bool saudio_suspended(void);
/* get current number of frames to fill packet queue */
SOKOL_AUDIO_API_DECL int saudio_expect(void);
/* push sample frames from main thread, returns number of frames actually pushed */
SOKOL_AUDIO_API_DECL int saudio_push(const float* frames, int num_frames);
#ifdef __cplusplus
} /* extern "C" */
/* reference-based equivalents for c++ */
inline void saudio_setup(const saudio_desc& desc) { return saudio_setup(&desc); }
#endif
#endif // SOKOL_AUDIO_INCLUDED
// ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
// ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
// ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
// ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
//
// >>implementation
#ifdef SOKOL_AUDIO_IMPL
#define SOKOL_AUDIO_IMPL_INCLUDED (1)
#if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
#error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use saudio_desc.allocator to override memory allocation functions"
#endif
#include <stdlib.h> // alloc, free
#include <string.h> // memset, memcpy
#include <stddef.h> // size_t
#ifndef SOKOL_API_IMPL
#define SOKOL_API_IMPL
#endif
#ifndef SOKOL_DEBUG
#ifndef NDEBUG
#define SOKOL_DEBUG
#endif
#endif
#ifndef SOKOL_ASSERT
#include <assert.h>
#define SOKOL_ASSERT(c) assert(c)
#endif
#ifndef _SOKOL_PRIVATE
#if defined(__GNUC__) || defined(__clang__)
#define _SOKOL_PRIVATE __attribute__((unused)) static
#else
#define _SOKOL_PRIVATE static
#endif
#endif
#ifndef _SOKOL_UNUSED
#define _SOKOL_UNUSED(x) (void)(x)
#endif
// platform detection defines
#if defined(SOKOL_DUMMY_BACKEND)
// nothing
#elif defined(__APPLE__)
#define _SAUDIO_APPLE (1)
#include <TargetConditionals.h>
#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#define _SAUDIO_IOS (1)
#else
#define _SAUDIO_MACOS (1)
#endif
#elif defined(__EMSCRIPTEN__)
#define _SAUDIO_EMSCRIPTEN (1)
#elif defined(_WIN32)
#define _SAUDIO_WINDOWS (1)
#include <winapifamily.h>
#if (defined(WINAPI_FAMILY_PARTITION) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
#error "sokol_audio.h no longer supports UWP"
#endif
#elif defined(__ANDROID__)
#define _SAUDIO_ANDROID (1)
#if !defined(SAUDIO_ANDROID_SLES) && !defined(SAUDIO_ANDROID_AAUDIO)
#define SAUDIO_ANDROID_AAUDIO (1)
#endif
#elif defined(__linux__) || defined(__unix__)
#define _SAUDIO_LINUX (1)
#else
#error "sokol_audio.h: Unknown platform"
#endif
// platform-specific headers and definitions
#if defined(SOKOL_DUMMY_BACKEND)
#define _SAUDIO_NOTHREADS (1)
#elif defined(_SAUDIO_WINDOWS)
#define _SAUDIO_WINTHREADS (1)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <synchapi.h>
#pragma comment (lib, "kernel32")
#pragma comment (lib, "ole32")
#ifndef CINTERFACE
#define CINTERFACE
#endif
#ifndef COBJMACROS
#define COBJMACROS
#endif
#ifndef CONST_VTABLE
#define CONST_VTABLE
#endif
#include <mmdeviceapi.h>
#include <audioclient.h>
static const IID _saudio_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, {0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2} };
static const IID _saudio_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, {0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6} };
static const CLSID _saudio_CLSID_IMMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e} };
static const IID _saudio_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, {0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2} };
static const IID _saudio_IID_Devinterface_Audio_Render = { 0xe6327cad, 0xdcec, 0x4949, {0xae, 0x8a, 0x99, 0x1e, 0x97, 0x6a, 0x79, 0xd2} };
static const IID _saudio_IID_IActivateAudioInterface_Completion_Handler = { 0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90} };
static const GUID _saudio_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71} };
#if defined(__cplusplus)
#define _SOKOL_AUDIO_WIN32COM_ID(x) (x)
#else
#define _SOKOL_AUDIO_WIN32COM_ID(x) (&x)
#endif
/* fix for Visual Studio 2015 SDKs */
#ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
#define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
#endif
#ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
#define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4505) /* unreferenced local function has been removed */
#endif
#elif defined(_SAUDIO_APPLE)
#define _SAUDIO_PTHREADS (1)
#include <pthread.h>
#if defined(_SAUDIO_IOS)
// always use system headers on iOS (for now at least)
#if !defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
#define SAUDIO_OSX_USE_SYSTEM_HEADERS (1)
#endif
#if !defined(__cplusplus)
#if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
#error "sokol_audio.h on iOS requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
#endif
#endif
#include <AudioToolbox/AudioToolbox.h>
#include <AVFoundation/AVFoundation.h>
#else
#if defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
#include <AudioToolbox/AudioToolbox.h>
#endif
#endif
#elif defined(_SAUDIO_ANDROID)
#define _SAUDIO_PTHREADS (1)
#include <pthread.h>
#if defined(SAUDIO_ANDROID_SLES)
#include "SLES/OpenSLES_Android.h"
#elif defined(SAUDIO_ANDROID_AAUDIO)
#include "aaudio/AAudio.h"
#endif
#elif defined(_SAUDIO_LINUX)
#include <alloca.h>
#define _SAUDIO_PTHREADS (1)
#include <pthread.h>
#define ALSA_PCM_NEW_HW_PARAMS_API
#include <alsa/asoundlib.h>
#elif defined(__EMSCRIPTEN__)
#define _SAUDIO_NOTHREADS (1)
#include <emscripten/emscripten.h>
#endif
#define _saudio_def(val, def) (((val) == 0) ? (def) : (val))
#define _saudio_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
#define _SAUDIO_DEFAULT_SAMPLE_RATE (44100)
#define _SAUDIO_DEFAULT_BUFFER_FRAMES (2048)
#define _SAUDIO_DEFAULT_PACKET_FRAMES (128)
#define _SAUDIO_DEFAULT_NUM_PACKETS ((_SAUDIO_DEFAULT_BUFFER_FRAMES/_SAUDIO_DEFAULT_PACKET_FRAMES)*4)
#ifndef SAUDIO_RING_MAX_SLOTS
#define SAUDIO_RING_MAX_SLOTS (1024)
#endif
// ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
// ██ ██ ██ ██ ██ ██ ██ ██ ██
// ███████ ██ ██████ ██ ██ ██ ██ ███████
// ██ ██ ██ ██ ██ ██ ██ ██ ██
// ███████ ██ ██ ██ ██████ ██████ ██ ███████
//
// >>structs
#if defined(_SAUDIO_PTHREADS)
typedef struct {
pthread_mutex_t mutex;
} _saudio_mutex_t;
#elif defined(_SAUDIO_WINTHREADS)
typedef struct {
CRITICAL_SECTION critsec;
} _saudio_mutex_t;
#elif defined(_SAUDIO_NOTHREADS)
typedef struct {
int dummy_mutex;
} _saudio_mutex_t;
#endif
#if defined(SOKOL_DUMMY_BACKEND)
typedef struct {
int dummy;
} _saudio_dummy_backend_t;
#elif defined(_SAUDIO_APPLE)
#if defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
typedef AudioQueueRef _saudio_AudioQueueRef;
typedef AudioQueueBufferRef _saudio_AudioQueueBufferRef;
typedef AudioStreamBasicDescription _saudio_AudioStreamBasicDescription;
typedef OSStatus _saudio_OSStatus;
#define _saudio_kAudioFormatLinearPCM (kAudioFormatLinearPCM)
#define _saudio_kLinearPCMFormatFlagIsFloat (kLinearPCMFormatFlagIsFloat)
#define _saudio_kAudioFormatFlagIsPacked (kAudioFormatFlagIsPacked)
#else
#ifdef __cplusplus
extern "C" {
#endif
// embedded AudioToolbox declarations
typedef uint32_t _saudio_AudioFormatID;
typedef uint32_t _saudio_AudioFormatFlags;
typedef int32_t _saudio_OSStatus;
typedef uint32_t _saudio_SMPTETimeType;
typedef uint32_t _saudio_SMPTETimeFlags;
typedef uint32_t _saudio_AudioTimeStampFlags;
typedef void* _saudio_CFRunLoopRef;
typedef void* _saudio_CFStringRef;
typedef void* _saudio_AudioQueueRef;
#define _saudio_kAudioFormatLinearPCM ('lpcm')
#define _saudio_kLinearPCMFormatFlagIsFloat (1U << 0)
#define _saudio_kAudioFormatFlagIsPacked (1U << 3)
typedef struct _saudio_AudioStreamBasicDescription {
double mSampleRate;
_saudio_AudioFormatID mFormatID;
_saudio_AudioFormatFlags mFormatFlags;
uint32_t mBytesPerPacket;
uint32_t mFramesPerPacket;
uint32_t mBytesPerFrame;
uint32_t mChannelsPerFrame;
uint32_t mBitsPerChannel;
uint32_t mReserved;
} _saudio_AudioStreamBasicDescription;
typedef struct _saudio_AudioStreamPacketDescription {
int64_t mStartOffset;
uint32_t mVariableFramesInPacket;
uint32_t mDataByteSize;
} _saudio_AudioStreamPacketDescription;
typedef struct _saudio_SMPTETime {
int16_t mSubframes;
int16_t mSubframeDivisor;
uint32_t mCounter;
_saudio_SMPTETimeType mType;
_saudio_SMPTETimeFlags mFlags;
int16_t mHours;
int16_t mMinutes;
int16_t mSeconds;
int16_t mFrames;
} _saudio_SMPTETime;
typedef struct _saudio_AudioTimeStamp {
double mSampleTime;
uint64_t mHostTime;
double mRateScalar;
uint64_t mWordClockTime;
_saudio_SMPTETime mSMPTETime;
_saudio_AudioTimeStampFlags mFlags;
uint32_t mReserved;
} _saudio_AudioTimeStamp;
typedef struct _saudio_AudioQueueBuffer {
const uint32_t mAudioDataBytesCapacity;
void* const mAudioData;
uint32_t mAudioDataByteSize;
void * mUserData;
const uint32_t mPacketDescriptionCapacity;
_saudio_AudioStreamPacketDescription* const mPacketDescriptions;
uint32_t mPacketDescriptionCount;
} _saudio_AudioQueueBuffer;
typedef _saudio_AudioQueueBuffer* _saudio_AudioQueueBufferRef;
typedef void (*_saudio_AudioQueueOutputCallback)(void* user_data, _saudio_AudioQueueRef inAQ, _saudio_AudioQueueBufferRef inBuffer);
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);
extern _saudio_OSStatus AudioQueueDispose(_saudio_AudioQueueRef inAQ, bool inImmediate);
extern _saudio_OSStatus AudioQueueAllocateBuffer(_saudio_AudioQueueRef inAQ, uint32_t inBufferByteSize, _saudio_AudioQueueBufferRef* outBuffer);
extern _saudio_OSStatus AudioQueueEnqueueBuffer(_saudio_AudioQueueRef inAQ, _saudio_AudioQueueBufferRef inBuffer, uint32_t inNumPacketDescs, const _saudio_AudioStreamPacketDescription* inPacketDescs);
extern _saudio_OSStatus AudioQueueStart(_saudio_AudioQueueRef inAQ, const _saudio_AudioTimeStamp * inStartTime);
extern _saudio_OSStatus AudioQueueStop(_saudio_AudioQueueRef inAQ, bool inImmediate);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // SAUDIO_OSX_USE_SYSTEM_HEADERS
typedef struct {
_saudio_AudioQueueRef ca_audio_queue;
#if defined(_SAUDIO_IOS)
id ca_interruption_handler;
#endif
} _saudio_apple_backend_t;
#elif defined(_SAUDIO_LINUX)
typedef struct {
snd_pcm_t* device;
float* buffer;
int buffer_byte_size;
int buffer_frames;
pthread_t thread;
bool thread_stop;
} _saudio_alsa_backend_t;
#elif defined(SAUDIO_ANDROID_SLES)
#define SAUDIO_SLES_NUM_BUFFERS (2)
typedef struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
} _saudio_sles_semaphore_t;
typedef struct {
SLObjectItf engine_obj;
SLEngineItf engine;
SLObjectItf output_mix_obj;
SLVolumeItf output_mix_vol;
SLDataLocator_OutputMix out_locator;
SLDataSink dst_data_sink;
SLObjectItf player_obj;
SLPlayItf player;
SLVolumeItf player_vol;
SLAndroidSimpleBufferQueueItf player_buffer_queue;
int16_t* output_buffers[SAUDIO_SLES_NUM_BUFFERS];
float* src_buffer;
int active_buffer;
_saudio_sles_semaphore_t buffer_sem;
pthread_t thread;
volatile int thread_stop;
SLDataLocator_AndroidSimpleBufferQueue in_locator;
} _saudio_sles_backend_t;
#elif defined(SAUDIO_ANDROID_AAUDIO)
typedef struct {
AAudioStreamBuilder* builder;
AAudioStream* stream;
pthread_t thread;
pthread_mutex_t mutex;
} _saudio_aaudio_backend_t;
#elif defined(_SAUDIO_WINDOWS)
typedef struct {
HANDLE thread_handle;
HANDLE buffer_end_event;
bool stop;