sokol_audio.h 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  1. #ifndef SOKOL_AUDIO_INCLUDED
  2. /*
  3. sokol_audio.h -- cross-platform audio-streaming API
  4. Project URL: https://github.com/floooh/sokol
  5. Do this:
  6. #define SOKOL_IMPL
  7. before you include this file in *one* C or C++ file to create the
  8. implementation.
  9. Optionally provide the following defines with your own implementations:
  10. SOKOL_DUMMY_BACKEND - use a dummy backend
  11. SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
  12. SOKOL_LOG(msg) - your own logging function (default: puts(msg))
  13. SOKOL_MALLOC(s) - your own malloc() implementation (default: malloc(s))
  14. SOKOL_FREE(p) - your own free() implementation (default: free(p))
  15. SOKOL_API_DECL - public function declaration prefix (default: extern)
  16. SOKOL_API_IMPL - public function implementation prefix (default: -)
  17. SAUDIO_RING_MAX_SLOTS - max number of slots in the push-audio ring buffer (default 1024)
  18. If sokol_audio.h is compiled as a DLL, define the following before
  19. including the declaration or implementation:
  20. SOKOL_DLL
  21. On Windows, SOKOL_DLL will define SOKOL_API_DECL as __declspec(dllexport)
  22. or __declspec(dllimport) as needed.
  23. FEATURE OVERVIEW
  24. ================
  25. You provide a mono- or stereo-stream of 32-bit float samples, which
  26. Sokol Audio feeds into platform-specific audio backends:
  27. - Windows: WASAPI
  28. - Linux: ALSA (link with asound)
  29. - macOS/iOS: CoreAudio (link with AudioToolbox)
  30. - emscripten: WebAudio with ScriptProcessorNode
  31. - Android: OpenSLES (link with OpenSLES)
  32. Sokol Audio will not do any buffer mixing or volume control, if you have
  33. multiple independent input streams of sample data you need to perform the
  34. mixing yourself before forwarding the data to Sokol Audio.
  35. There are two mutually exclusive ways to provide the sample data:
  36. 1. Callback model: You provide a callback function, which will be called
  37. when Sokol Audio needs new samples. On all platforms except emscripten,
  38. this function is called from a separate thread.
  39. 2. Push model: Your code pushes small blocks of sample data from your
  40. main loop or a thread you created. The pushed data is stored in
  41. a ring buffer where it is pulled by the backend code when
  42. needed.
  43. The callback model is preferred because it is the most direct way to
  44. feed sample data into the audio backends and also has less moving parts
  45. (there is no ring buffer between your code and the audio backend).
  46. Sometimes it is not possible to generate the audio stream directly in a
  47. callback function running in a separate thread, for such cases Sokol Audio
  48. provides the push-model as a convenience.
  49. SOKOL AUDIO AND SOLOUD
  50. ======================
  51. The WASAPI, ALSA, OpenSLES and CoreAudio backend code has been taken from the
  52. SoLoud library (with some modifications, so any bugs in there are most
  53. likely my fault). If you need a more fully-featured audio solution, check
  54. out SoLoud, it's excellent:
  55. https://github.com/jarikomppa/soloud
  56. GLOSSARY
  57. ========
  58. - stream buffer:
  59. The internal audio data buffer, usually provided by the backend API. The
  60. size of the stream buffer defines the base latency, smaller buffers have
  61. lower latency but may cause audio glitches. Bigger buffers reduce or
  62. eliminate glitches, but have a higher base latency.
  63. - stream callback:
  64. Optional callback function which is called by Sokol Audio when it
  65. needs new samples. On Windows, macOS/iOS and Linux, this is called in
  66. a separate thread, on WebAudio, this is called per-frame in the
  67. browser thread.
  68. - channel:
  69. A discrete track of audio data, currently 1-channel (mono) and
  70. 2-channel (stereo) is supported and tested.
  71. - sample:
  72. The magnitude of an audio signal on one channel at a given time. In
  73. Sokol Audio, samples are 32-bit float numbers in the range -1.0 to
  74. +1.0.
  75. - frame:
  76. The tightly packed set of samples for all channels at a given time.
  77. For mono 1 frame is 1 sample. For stereo, 1 frame is 2 samples.
  78. - packet:
  79. In Sokol Audio, a small chunk of audio data that is moved from the
  80. main thread to the audio streaming thread in order to decouple the
  81. rate at which the main thread provides new audio data, and the
  82. streaming thread consuming audio data.
  83. WORKING WITH SOKOL AUDIO
  84. ========================
  85. First call saudio_setup() with your preferred audio playback options.
  86. In most cases you can stick with the default values, these provide
  87. a good balance between low-latency and glitch-free playback
  88. on all audio backends.
  89. If you want to use the callback-model, you need to provide a stream
  90. callback function either in saudio_desc.stream_cb or saudio_desc.stream_userdata_cb,
  91. otherwise keep both function pointers zero-initialized.
  92. Use push model and default playback parameters:
  93. saudio_setup(&(saudio_desc){0});
  94. Use stream callback model and default playback parameters:
  95. saudio_setup(&(saudio_desc){
  96. .stream_cb = my_stream_callback
  97. });
  98. The standard stream callback doesn't have a user data argument, if you want
  99. that, use the alternative stream_userdata_cb and also set the user_data pointer:
  100. saudio_setup(&(saudio_desc){
  101. .stream_userdata_cb = my_stream_callback,
  102. .user_data = &my_data
  103. });
  104. The following playback parameters can be provided through the
  105. saudio_desc struct:
  106. General parameters (both for stream-callback and push-model):
  107. int sample_rate -- the sample rate in Hz, default: 44100
  108. int num_channels -- number of channels, default: 1 (mono)
  109. int buffer_frames -- number of frames in streaming buffer, default: 2048
  110. The stream callback prototype (either with or without userdata):
  111. void (*stream_cb)(float* buffer, int num_frames, int num_channels)
  112. void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data)
  113. Function pointer to the user-provide stream callback.
  114. Push-model parameters:
  115. int packet_frames -- number of frames in a packet, default: 128
  116. int num_packets -- number of packets in ring buffer, default: 64
  117. The sample_rate and num_channels parameters are only hints for the audio
  118. backend, it isn't guaranteed that those are the values used for actual
  119. playback.
  120. To get the actual parameters, call the following functions after
  121. saudio_setup():
  122. int saudio_sample_rate(void)
  123. int saudio_channels(void);
  124. It's unlikely that the number of channels will be different than requested,
  125. but a different sample rate isn't uncommon.
  126. (NOTE: there's an yet unsolved issue when an audio backend might switch
  127. to a different sample rate when switching output devices, for instance
  128. plugging in a bluetooth headset, this case is currently not handled in
  129. Sokol Audio).
  130. You can check if audio initialization was successful with
  131. saudio_isvalid(). If backend initialization failed for some reason
  132. (for instance when there's no audio device in the machine), this
  133. will return false. Not checking for success won't do any harm, all
  134. Sokol Audio function will silently fail when called after initialization
  135. has failed, so apart from missing audio output, nothing bad will happen.
  136. Before your application exits, you should call
  137. saudio_shutdown();
  138. This stops the audio thread (on Linux, Windows and macOS/iOS) and
  139. properly shuts down the audio backend.
  140. THE STREAM CALLBACK MODEL
  141. =========================
  142. To use Sokol Audio in stream-callback-mode, provide a callback function
  143. like this in the saudio_desc struct when calling saudio_setup():
  144. void stream_cb(float* buffer, int num_frames, int num_channels) {
  145. ...
  146. }
  147. Or the alternative version with a user-data argument:
  148. void stream_userdata_cb(float* buffer, int num_frames, int num_channels, void* user_data) {
  149. my_data_t* my_data = (my_data_t*) user_data;
  150. ...
  151. }
  152. The job of the callback function is to fill the *buffer* with 32-bit
  153. float sample values.
  154. To output silence, fill the buffer with zeros:
  155. void stream_cb(float* buffer, int num_frames, int num_channels) {
  156. const int num_samples = num_frames * num_channels;
  157. for (int i = 0; i < num_samples; i++) {
  158. buffer[i] = 0.0f;
  159. }
  160. }
  161. For stereo output (num_channels == 2), the samples for the left
  162. and right channel are interleaved:
  163. void stream_cb(float* buffer, int num_frames, int num_channels) {
  164. assert(2 == num_channels);
  165. for (int i = 0; i < num_frames; i++) {
  166. buffer[2*i + 0] = ...; // left channel
  167. buffer[2*i + 1] = ...; // right channel
  168. }
  169. }
  170. Please keep in mind that the stream callback function is running in a
  171. separate thread, if you need to share data with the main thread you need
  172. to take care yourself to make the access to the shared data thread-safe!
  173. THE PUSH MODEL
  174. ==============
  175. To use the push-model for providing audio data, simply don't set (keep
  176. zero-initialized) the stream_cb field in the saudio_desc struct when
  177. calling saudio_setup().
  178. To provide sample data with the push model, call the saudio_push()
  179. function at regular intervals (for instance once per frame). You can
  180. call the saudio_expect() function to ask Sokol Audio how much room is
  181. in the ring buffer, but if you provide a continuous stream of data
  182. at the right sample rate, saudio_expect() isn't required (it's a simple
  183. way to sync/throttle your sample generation code with the playback
  184. rate though).
  185. With saudio_push() you may need to maintain your own intermediate sample
  186. buffer, since pushing individual sample values isn't very efficient.
  187. The following example is from the MOD player sample in
  188. sokol-samples (https://github.com/floooh/sokol-samples):
  189. const int num_frames = saudio_expect();
  190. if (num_frames > 0) {
  191. const int num_samples = num_frames * saudio_channels();
  192. read_samples(flt_buf, num_samples);
  193. saudio_push(flt_buf, num_frames);
  194. }
  195. Another option is to ignore saudio_expect(), and just push samples as they
  196. are generated in small batches. In this case you *need* to generate the
  197. samples at the right sample rate:
  198. The following example is taken from the Tiny Emulators project
  199. (https://github.com/floooh/chips-test), this is for mono playback,
  200. so (num_samples == num_frames):
  201. // tick the sound generator
  202. if (ay38910_tick(&sys->psg)) {
  203. // new sample is ready
  204. sys->sample_buffer[sys->sample_pos++] = sys->psg.sample;
  205. if (sys->sample_pos == sys->num_samples) {
  206. // new sample packet is ready
  207. saudio_push(sys->sample_buffer, sys->num_samples);
  208. sys->sample_pos = 0;
  209. }
  210. }
  211. THE WEBAUDIO BACKEND
  212. ====================
  213. The WebAudio backend is currently using a ScriptProcessorNode callback to
  214. feed the sample data into WebAudio. ScriptProcessorNode has been
  215. deprecated for a while because it is running from the main thread, with
  216. the default initialization parameters it works 'pretty well' though.
  217. Ultimately Sokol Audio will use Audio Worklets, but this requires a few
  218. more things to fall into place (Audio Worklets implemented everywhere,
  219. SharedArrayBuffers enabled again, and I need to figure out a 'low-cost'
  220. solution in terms of implementation effort, since Audio Worklets are
  221. a lot more complex than ScriptProcessorNode if the audio data needs to come
  222. from the main thread).
  223. The WebAudio backend is automatically selected when compiling for
  224. emscripten (__EMSCRIPTEN__ define exists).
  225. https://developers.google.com/web/updates/2017/12/audio-worklet
  226. https://developers.google.com/web/updates/2018/06/audio-worklet-design-pattern
  227. "Blob URLs": https://www.html5rocks.com/en/tutorials/workers/basics/
  228. THE COREAUDIO BACKEND
  229. =====================
  230. The CoreAudio backend is selected on macOS and iOS (__APPLE__ is defined).
  231. Since the CoreAudio API is implemented in C (not Objective-C) the
  232. implementation part of Sokol Audio can be included into a C source file.
  233. For thread synchronisation, the CoreAudio backend will use the
  234. pthread_mutex_* functions.
  235. The incoming floating point samples will be directly forwarded to
  236. CoreAudio without further conversion.
  237. macOS and iOS applications that use Sokol Audio need to link with
  238. the AudioToolbox framework.
  239. THE WASAPI BACKEND
  240. ==================
  241. The WASAPI backend is automatically selected when compiling on Windows
  242. (_WIN32 is defined).
  243. For thread synchronisation a Win32 critical section is used.
  244. WASAPI may use a different size for its own streaming buffer then requested,
  245. so the base latency may be slightly bigger. The current backend implementation
  246. converts the incoming floating point sample values to signed 16-bit
  247. integers.
  248. The required Windows system DLLs are linked with #pragma comment(lib, ...),
  249. so you shouldn't need to add additional linker libs in the build process
  250. (otherwise this is a bug which should be fixed in sokol_audio.h).
  251. THE ALSA BACKEND
  252. ================
  253. The ALSA backend is automatically selected when compiling on Linux
  254. ('linux' is defined).
  255. For thread synchronisation, the pthread_mutex_* functions are used.
  256. Samples are directly forwarded to ALSA in 32-bit float format, no
  257. further conversion is taking place.
  258. You need to link with the 'asound' library, and the <alsa/asoundlib.h>
  259. header must be present (usually both are installed with some sort
  260. of ALSA development package).
  261. LICENSE
  262. =======
  263. zlib/libpng license
  264. Copyright (c) 2018 Andre Weissflog
  265. This software is provided 'as-is', without any express or implied warranty.
  266. In no event will the authors be held liable for any damages arising from the
  267. use of this software.
  268. Permission is granted to anyone to use this software for any purpose,
  269. including commercial applications, and to alter it and redistribute it
  270. freely, subject to the following restrictions:
  271. 1. The origin of this software must not be misrepresented; you must not
  272. claim that you wrote the original software. If you use this software in a
  273. product, an acknowledgment in the product documentation would be
  274. appreciated but is not required.
  275. 2. Altered source versions must be plainly marked as such, and must not
  276. be misrepresented as being the original software.
  277. 3. This notice may not be removed or altered from any source
  278. distribution.
  279. */
  280. #define SOKOL_AUDIO_INCLUDED (1)
  281. #include <stdint.h>
  282. #include <stdbool.h>
  283. #ifndef SOKOL_API_DECL
  284. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_IMPL)
  285. #define SOKOL_API_DECL __declspec(dllexport)
  286. #elif defined(_WIN32) && defined(SOKOL_DLL)
  287. #define SOKOL_API_DECL __declspec(dllimport)
  288. #else
  289. #define SOKOL_API_DECL extern
  290. #endif
  291. #endif
  292. #ifdef __cplusplus
  293. extern "C" {
  294. #endif
  295. typedef struct saudio_desc {
  296. int sample_rate; /* requested sample rate */
  297. int num_channels; /* number of channels, default: 1 (mono) */
  298. int buffer_frames; /* number of frames in streaming buffer */
  299. int packet_frames; /* number of frames in a packet */
  300. int num_packets; /* number of packets in packet queue */
  301. void (*stream_cb)(float* buffer, int num_frames, int num_channels); /* optional streaming callback (no user data) */
  302. void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data); /*... and with user data */
  303. void* user_data; /* optional user data argument for stream_userdata_cb */
  304. } saudio_desc;
  305. /* setup sokol-audio */
  306. SOKOL_API_DECL void saudio_setup(const saudio_desc* desc);
  307. /* shutdown sokol-audio */
  308. SOKOL_API_DECL void saudio_shutdown(void);
  309. /* true after setup if audio backend was successfully initialized */
  310. SOKOL_API_DECL bool saudio_isvalid(void);
  311. /* return the saudio_desc.user_data pointer */
  312. SOKOL_API_DECL void* saudio_userdata(void);
  313. /* return a copy of the original saudio_desc struct */
  314. SOKOL_API_DECL saudio_desc saudio_query_desc(void);
  315. /* actual sample rate */
  316. SOKOL_API_DECL int saudio_sample_rate(void);
  317. /* return actual backend buffer size in number of frames */
  318. SOKOL_API_DECL int saudio_buffer_frames(void);
  319. /* actual number of channels */
  320. SOKOL_API_DECL int saudio_channels(void);
  321. /* get current number of frames to fill packet queue */
  322. SOKOL_API_DECL int saudio_expect(void);
  323. /* push sample frames from main thread, returns number of frames actually pushed */
  324. SOKOL_API_DECL int saudio_push(const float* frames, int num_frames);
  325. #ifdef __cplusplus
  326. } /* extern "C" */
  327. #endif
  328. #endif // SOKOL_AUDIO_INCLUDED
  329. /*=== IMPLEMENTATION =========================================================*/
  330. #ifdef SOKOL_IMPL
  331. #define SOKOL_AUDIO_IMPL_INCLUDED (1)
  332. #include <string.h> /* memset, memcpy */
  333. #ifndef SOKOL_API_IMPL
  334. #define SOKOL_API_IMPL
  335. #endif
  336. #ifndef SOKOL_DEBUG
  337. #ifndef NDEBUG
  338. #define SOKOL_DEBUG (1)
  339. #endif
  340. #endif
  341. #ifndef SOKOL_ASSERT
  342. #include <assert.h>
  343. #define SOKOL_ASSERT(c) assert(c)
  344. #endif
  345. #ifndef SOKOL_MALLOC
  346. #include <stdlib.h>
  347. #define SOKOL_MALLOC(s) malloc(s)
  348. #define SOKOL_FREE(p) free(p)
  349. #endif
  350. #ifndef SOKOL_LOG
  351. #ifdef SOKOL_DEBUG
  352. #include <stdio.h>
  353. #define SOKOL_LOG(s) { SOKOL_ASSERT(s); puts(s); }
  354. #else
  355. #define SOKOL_LOG(s)
  356. #endif
  357. #endif
  358. #ifndef _SOKOL_PRIVATE
  359. #if defined(__GNUC__)
  360. #define _SOKOL_PRIVATE __attribute__((unused)) static
  361. #else
  362. #define _SOKOL_PRIVATE static
  363. #endif
  364. #endif
  365. #if (defined(__APPLE__) || defined(__linux__) || defined(__unix__)) && !defined(__EMSCRIPTEN__)
  366. #include <pthread.h>
  367. #elif defined(_WIN32)
  368. #ifndef WIN32_LEAN_AND_MEAN
  369. #define WIN32_LEAN_AND_MEAN
  370. #endif
  371. #include <windows.h>
  372. #include <synchapi.h>
  373. #pragma comment (lib, "kernel32.lib")
  374. #pragma comment (lib, "ole32.lib")
  375. #endif
  376. #if defined(__APPLE__)
  377. #include <AudioToolbox/AudioToolbox.h>
  378. #elif (defined(__linux__) || defined(__unix__)) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
  379. #define ALSA_PCM_NEW_HW_PARAMS_API
  380. #include <alsa/asoundlib.h>
  381. #elif defined(__ANDROID__)
  382. #include "SLES/OpenSLES_Android.h"
  383. #elif defined(_WIN32)
  384. #ifndef CINTERFACE
  385. #define CINTERFACE
  386. #endif
  387. #ifndef COBJMACROS
  388. #define COBJMACROS
  389. #endif
  390. #ifndef CONST_VTABLE
  391. #define CONST_VTABLE
  392. #endif
  393. #include <mmdeviceapi.h>
  394. #include <audioclient.h>
  395. static const IID _saudio_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, { 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
  396. static const IID _saudio_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, { 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
  397. static const CLSID _saudio_CLSID_IMMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, { 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
  398. static const IID _saudio_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
  399. #if defined(__cplusplus)
  400. #define _SOKOL_AUDIO_WIN32COM_ID(x) (x)
  401. #else
  402. #define _SOKOL_AUDIO_WIN32COM_ID(x) (&x)
  403. #endif
  404. /* fix for Visual Studio 2015 SDKs */
  405. #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
  406. #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  407. #endif
  408. #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
  409. #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  410. #endif
  411. #elif defined(__EMSCRIPTEN__)
  412. #include <emscripten/emscripten.h>
  413. #endif
  414. #ifdef _MSC_VER
  415. #pragma warning(push)
  416. #pragma warning(disable:4505) /* unreferenced local function has been removed */
  417. #endif
  418. #define _saudio_def(val, def) (((val) == 0) ? (def) : (val))
  419. #define _saudio_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
  420. #define _SAUDIO_DEFAULT_SAMPLE_RATE (44100)
  421. #define _SAUDIO_DEFAULT_BUFFER_FRAMES (2048)
  422. #define _SAUDIO_DEFAULT_PACKET_FRAMES (128)
  423. #define _SAUDIO_DEFAULT_NUM_PACKETS ((_SAUDIO_DEFAULT_BUFFER_FRAMES/_SAUDIO_DEFAULT_PACKET_FRAMES)*4)
  424. #ifndef SAUDIO_RING_MAX_SLOTS
  425. #define SAUDIO_RING_MAX_SLOTS (1024)
  426. #endif
  427. /*=== MUTEX WRAPPER DECLARATIONS =============================================*/
  428. #if (defined(__APPLE__) || defined(__linux__) || defined(__unix__)) && !defined(__EMSCRIPTEN__)
  429. typedef struct {
  430. pthread_mutex_t mutex;
  431. } _saudio_mutex_t;
  432. #elif defined(_WIN32)
  433. typedef struct {
  434. CRITICAL_SECTION critsec;
  435. } _saudio_mutex_t;
  436. #else
  437. typedef struct { } _saudio_mutex_t;
  438. #endif
  439. /*=== COREAUDIO BACKEND DECLARATIONS =========================================*/
  440. #if defined(__APPLE__)
  441. typedef struct {
  442. AudioQueueRef ca_audio_queue;
  443. } _saudio_backend_t;
  444. /*=== ALSA BACKEND DECLARATIONS ==============================================*/
  445. #elif (defined(__linux__) || defined(__unix__)) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
  446. typedef struct {
  447. snd_pcm_t* device;
  448. float* buffer;
  449. int buffer_byte_size;
  450. int buffer_frames;
  451. pthread_t thread;
  452. bool thread_stop;
  453. } _saudio_backend_t;
  454. /*=== OpenSLES BACKEND DECLARATIONS ==============================================*/
  455. #elif defined(__ANDROID__)
  456. #define SAUDIO_NUM_BUFFERS 2
  457. typedef struct {
  458. pthread_mutex_t mutex;
  459. pthread_cond_t cond;
  460. int count;
  461. } _saudio_semaphore_t;
  462. typedef struct {
  463. SLObjectItf engine_obj;
  464. SLEngineItf engine;
  465. SLObjectItf output_mix_obj;
  466. SLVolumeItf output_mix_vol;
  467. SLDataLocator_OutputMix out_locator;
  468. SLDataSink dst_data_sink;
  469. SLObjectItf player_obj;
  470. SLPlayItf player;
  471. SLVolumeItf player_vol;
  472. SLAndroidSimpleBufferQueueItf player_buffer_queue;
  473. int16_t* output_buffers[SAUDIO_NUM_BUFFERS];
  474. float* src_buffer;
  475. int active_buffer;
  476. _saudio_semaphore_t buffer_sem;
  477. pthread_t thread;
  478. volatile int thread_stop;
  479. SLDataLocator_AndroidSimpleBufferQueue in_locator;
  480. } _saudio_backend_t;
  481. /*=== WASAPI BACKEND DECLARATIONS ============================================*/
  482. #elif defined(_WIN32)
  483. typedef struct {
  484. HANDLE thread_handle;
  485. HANDLE buffer_end_event;
  486. bool stop;
  487. UINT32 dst_buffer_frames;
  488. int src_buffer_frames;
  489. int src_buffer_byte_size;
  490. int src_buffer_pos;
  491. float* src_buffer;
  492. } _saudio_wasapi_thread_data_t;
  493. typedef struct {
  494. IMMDeviceEnumerator* device_enumerator;
  495. IMMDevice* device;
  496. IAudioClient* audio_client;
  497. IAudioRenderClient* render_client;
  498. int si16_bytes_per_frame;
  499. _saudio_wasapi_thread_data_t thread;
  500. } _saudio_backend_t;
  501. /*=== WEBAUDIO BACKEND DECLARATIONS ==========================================*/
  502. #elif defined(__EMSCRIPTEN__)
  503. typedef struct {
  504. uint8_t* buffer;
  505. } _saudio_backend_t;
  506. /*=== DUMMY BACKEND DECLARATIONS =============================================*/
  507. #else
  508. typedef struct { } _saudio_backend_t;
  509. #endif
  510. /*=== GENERAL DECLARATIONS ===================================================*/
  511. /* a ringbuffer structure */
  512. typedef struct {
  513. uint32_t head; /* next slot to write to */
  514. uint32_t tail; /* next slot to read from */
  515. uint32_t num; /* number of slots in queue */
  516. uint32_t queue[SAUDIO_RING_MAX_SLOTS];
  517. } _saudio_ring_t;
  518. /* a packet FIFO structure */
  519. typedef struct {
  520. bool valid;
  521. int packet_size; /* size of a single packets in bytes(!) */
  522. int num_packets; /* number of packet in fifo */
  523. uint8_t* base_ptr; /* packet memory chunk base pointer (dynamically allocated) */
  524. int cur_packet; /* current write-packet */
  525. int cur_offset; /* current byte-offset into current write packet */
  526. _saudio_mutex_t mutex; /* mutex for thread-safe access */
  527. _saudio_ring_t read_queue; /* buffers with data, ready to be streamed */
  528. _saudio_ring_t write_queue; /* empty buffers, ready to be pushed to */
  529. } _saudio_fifo_t;
  530. /* sokol-audio state */
  531. typedef struct {
  532. bool valid;
  533. void (*stream_cb)(float* buffer, int num_frames, int num_channels);
  534. void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data);
  535. void* user_data;
  536. int sample_rate; /* sample rate */
  537. int buffer_frames; /* number of frames in streaming buffer */
  538. int bytes_per_frame; /* filled by backend */
  539. int packet_frames; /* number of frames in a packet */
  540. int num_packets; /* number of packets in packet queue */
  541. int num_channels; /* actual number of channels */
  542. saudio_desc desc;
  543. _saudio_fifo_t fifo;
  544. _saudio_backend_t backend;
  545. } _saudio_state_t;
  546. static _saudio_state_t _saudio;
  547. _SOKOL_PRIVATE bool _saudio_has_callback(void) {
  548. return (_saudio.stream_cb || _saudio.stream_userdata_cb);
  549. }
  550. _SOKOL_PRIVATE void _saudio_stream_callback(float* buffer, int num_frames, int num_channels) {
  551. if (_saudio.stream_cb) {
  552. _saudio.stream_cb(buffer, num_frames, num_channels);
  553. }
  554. else if (_saudio.stream_userdata_cb) {
  555. _saudio.stream_userdata_cb(buffer, num_frames, num_channels, _saudio.user_data);
  556. }
  557. }
  558. /*=== MUTEX IMPLEMENTATION ===================================================*/
  559. #if (defined(__APPLE__) || defined(__linux__) || defined(__unix__)) && !defined(__EMSCRIPTEN__)
  560. _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) {
  561. pthread_mutexattr_t attr;
  562. pthread_mutexattr_init(&attr);
  563. pthread_mutex_init(&m->mutex, &attr);
  564. }
  565. _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) {
  566. pthread_mutex_destroy(&m->mutex);
  567. }
  568. _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) {
  569. pthread_mutex_lock(&m->mutex);
  570. }
  571. _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) {
  572. pthread_mutex_unlock(&m->mutex);
  573. }
  574. #elif defined(_WIN32)
  575. _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) {
  576. InitializeCriticalSection(&m->critsec);
  577. }
  578. _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) {
  579. DeleteCriticalSection(&m->critsec);
  580. }
  581. _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) {
  582. EnterCriticalSection(&m->critsec);
  583. }
  584. _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) {
  585. LeaveCriticalSection(&m->critsec);
  586. }
  587. #else
  588. _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) { (void)m; }
  589. _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) { (void)m; }
  590. _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) { (void)m; }
  591. _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) { (void)m; }
  592. #endif
  593. /*=== RING-BUFFER QUEUE IMPLEMENTATION =======================================*/
  594. _SOKOL_PRIVATE uint16_t _saudio_ring_idx(_saudio_ring_t* ring, uint32_t i) {
  595. return (uint16_t) (i % ring->num);
  596. }
  597. _SOKOL_PRIVATE void _saudio_ring_init(_saudio_ring_t* ring, uint32_t num_slots) {
  598. SOKOL_ASSERT((num_slots + 1) <= SAUDIO_RING_MAX_SLOTS);
  599. ring->head = 0;
  600. ring->tail = 0;
  601. /* one slot reserved to detect 'full' vs 'empty' */
  602. ring->num = num_slots + 1;
  603. }
  604. _SOKOL_PRIVATE bool _saudio_ring_full(_saudio_ring_t* ring) {
  605. return _saudio_ring_idx(ring, ring->head + 1) == ring->tail;
  606. }
  607. _SOKOL_PRIVATE bool _saudio_ring_empty(_saudio_ring_t* ring) {
  608. return ring->head == ring->tail;
  609. }
  610. _SOKOL_PRIVATE int _saudio_ring_count(_saudio_ring_t* ring) {
  611. uint32_t count;
  612. if (ring->head >= ring->tail) {
  613. count = ring->head - ring->tail;
  614. }
  615. else {
  616. count = (ring->head + ring->num) - ring->tail;
  617. }
  618. SOKOL_ASSERT(count < ring->num);
  619. return count;
  620. }
  621. _SOKOL_PRIVATE void _saudio_ring_enqueue(_saudio_ring_t* ring, uint32_t val) {
  622. SOKOL_ASSERT(!_saudio_ring_full(ring));
  623. ring->queue[ring->head] = val;
  624. ring->head = _saudio_ring_idx(ring, ring->head + 1);
  625. }
  626. _SOKOL_PRIVATE uint32_t _saudio_ring_dequeue(_saudio_ring_t* ring) {
  627. SOKOL_ASSERT(!_saudio_ring_empty(ring));
  628. uint32_t val = ring->queue[ring->tail];
  629. ring->tail = _saudio_ring_idx(ring, ring->tail + 1);
  630. return val;
  631. }
  632. /*--- a packet fifo for queueing audio data from main thread ----------------*/
  633. _SOKOL_PRIVATE void _saudio_fifo_init_mutex(_saudio_fifo_t* fifo) {
  634. /* this must be called before initializing both the backend and the fifo itself! */
  635. _saudio_mutex_init(&fifo->mutex);
  636. }
  637. _SOKOL_PRIVATE void _saudio_fifo_init(_saudio_fifo_t* fifo, int packet_size, int num_packets) {
  638. /* NOTE: there's a chicken-egg situation during the init phase where the
  639. streaming thread must be started before the fifo is actually initialized,
  640. thus the fifo init must already be protected from access by the fifo_read() func.
  641. */
  642. _saudio_mutex_lock(&fifo->mutex);
  643. SOKOL_ASSERT((packet_size > 0) && (num_packets > 0));
  644. fifo->packet_size = packet_size;
  645. fifo->num_packets = num_packets;
  646. fifo->base_ptr = (uint8_t*) SOKOL_MALLOC(packet_size * num_packets);
  647. SOKOL_ASSERT(fifo->base_ptr);
  648. fifo->cur_packet = -1;
  649. fifo->cur_offset = 0;
  650. _saudio_ring_init(&fifo->read_queue, num_packets);
  651. _saudio_ring_init(&fifo->write_queue, num_packets);
  652. for (int i = 0; i < num_packets; i++) {
  653. _saudio_ring_enqueue(&fifo->write_queue, i);
  654. }
  655. SOKOL_ASSERT(_saudio_ring_full(&fifo->write_queue));
  656. SOKOL_ASSERT(_saudio_ring_count(&fifo->write_queue) == num_packets);
  657. SOKOL_ASSERT(_saudio_ring_empty(&fifo->read_queue));
  658. SOKOL_ASSERT(_saudio_ring_count(&fifo->read_queue) == 0);
  659. fifo->valid = true;
  660. _saudio_mutex_unlock(&fifo->mutex);
  661. }
  662. _SOKOL_PRIVATE void _saudio_fifo_shutdown(_saudio_fifo_t* fifo) {
  663. SOKOL_ASSERT(fifo->base_ptr);
  664. SOKOL_FREE(fifo->base_ptr);
  665. fifo->base_ptr = 0;
  666. fifo->valid = false;
  667. _saudio_mutex_destroy(&fifo->mutex);
  668. }
  669. _SOKOL_PRIVATE int _saudio_fifo_writable_bytes(_saudio_fifo_t* fifo) {
  670. _saudio_mutex_lock(&fifo->mutex);
  671. int num_bytes = (_saudio_ring_count(&fifo->write_queue) * fifo->packet_size);
  672. if (fifo->cur_packet != -1) {
  673. num_bytes += fifo->packet_size - fifo->cur_offset;
  674. }
  675. _saudio_mutex_unlock(&fifo->mutex);
  676. SOKOL_ASSERT((num_bytes >= 0) && (num_bytes <= (fifo->num_packets * fifo->packet_size)));
  677. return num_bytes;
  678. }
  679. /* write new data to the write queue, this is called from main thread */
  680. _SOKOL_PRIVATE int _saudio_fifo_write(_saudio_fifo_t* fifo, const uint8_t* ptr, int num_bytes) {
  681. /* returns the number of bytes written, this will be smaller then requested
  682. if the write queue runs full
  683. */
  684. int all_to_copy = num_bytes;
  685. while (all_to_copy > 0) {
  686. /* need to grab a new packet? */
  687. if (fifo->cur_packet == -1) {
  688. _saudio_mutex_lock(&fifo->mutex);
  689. if (!_saudio_ring_empty(&fifo->write_queue)) {
  690. fifo->cur_packet = _saudio_ring_dequeue(&fifo->write_queue);
  691. }
  692. _saudio_mutex_unlock(&fifo->mutex);
  693. SOKOL_ASSERT(fifo->cur_offset == 0);
  694. }
  695. /* append data to current write packet */
  696. if (fifo->cur_packet != -1) {
  697. int to_copy = all_to_copy;
  698. const int max_copy = fifo->packet_size - fifo->cur_offset;
  699. if (to_copy > max_copy) {
  700. to_copy = max_copy;
  701. }
  702. uint8_t* dst = fifo->base_ptr + fifo->cur_packet * fifo->packet_size + fifo->cur_offset;
  703. memcpy(dst, ptr, to_copy);
  704. ptr += to_copy;
  705. fifo->cur_offset += to_copy;
  706. all_to_copy -= to_copy;
  707. SOKOL_ASSERT(fifo->cur_offset <= fifo->packet_size);
  708. SOKOL_ASSERT(all_to_copy >= 0);
  709. }
  710. else {
  711. /* early out if we're starving */
  712. int bytes_copied = num_bytes - all_to_copy;
  713. SOKOL_ASSERT((bytes_copied >= 0) && (bytes_copied < num_bytes));
  714. return bytes_copied;
  715. }
  716. /* if write packet is full, push to read queue */
  717. if (fifo->cur_offset == fifo->packet_size) {
  718. _saudio_mutex_lock(&fifo->mutex);
  719. _saudio_ring_enqueue(&fifo->read_queue, fifo->cur_packet);
  720. _saudio_mutex_unlock(&fifo->mutex);
  721. fifo->cur_packet = -1;
  722. fifo->cur_offset = 0;
  723. }
  724. }
  725. SOKOL_ASSERT(all_to_copy == 0);
  726. return num_bytes;
  727. }
  728. /* read queued data, this is called form the stream callback (maybe separate thread) */
  729. _SOKOL_PRIVATE int _saudio_fifo_read(_saudio_fifo_t* fifo, uint8_t* ptr, int num_bytes) {
  730. /* NOTE: fifo_read might be called before the fifo is properly initialized */
  731. _saudio_mutex_lock(&fifo->mutex);
  732. int num_bytes_copied = 0;
  733. if (fifo->valid) {
  734. SOKOL_ASSERT(0 == (num_bytes % fifo->packet_size));
  735. SOKOL_ASSERT(num_bytes <= (fifo->packet_size * fifo->num_packets));
  736. const int num_packets_needed = num_bytes / fifo->packet_size;
  737. uint8_t* dst = ptr;
  738. /* either pull a full buffer worth of data, or nothing */
  739. if (_saudio_ring_count(&fifo->read_queue) >= num_packets_needed) {
  740. for (int i = 0; i < num_packets_needed; i++) {
  741. int packet_index = _saudio_ring_dequeue(&fifo->read_queue);
  742. _saudio_ring_enqueue(&fifo->write_queue, packet_index);
  743. const uint8_t* src = fifo->base_ptr + packet_index * fifo->packet_size;
  744. memcpy(dst, src, fifo->packet_size);
  745. dst += fifo->packet_size;
  746. num_bytes_copied += fifo->packet_size;
  747. }
  748. SOKOL_ASSERT(num_bytes == num_bytes_copied);
  749. }
  750. }
  751. _saudio_mutex_unlock(&fifo->mutex);
  752. return num_bytes_copied;
  753. }
  754. /*=== DUMMY BACKEND IMPLEMENTATION ===========================================*/
  755. #if defined(SOKOL_DUMMY_BACKEND)
  756. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  757. _saudio.bytes_per_frame = _saudio.num_channels * sizeof(float);
  758. return true;
  759. };
  760. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) { };
  761. /*=== COREAUDIO BACKEND IMPLEMENTATION =======================================*/
  762. #elif defined(__APPLE__)
  763. /* NOTE: the buffer data callback is called on a separate thread! */
  764. _SOKOL_PRIVATE void _sapp_ca_callback(void* user_data, AudioQueueRef queue, AudioQueueBufferRef buffer) {
  765. if (_saudio_has_callback()) {
  766. const int num_frames = buffer->mAudioDataByteSize / _saudio.bytes_per_frame;
  767. const int num_channels = _saudio.num_channels;
  768. _saudio_stream_callback((float*)buffer->mAudioData, num_frames, num_channels);
  769. }
  770. else {
  771. uint8_t* ptr = (uint8_t*)buffer->mAudioData;
  772. int num_bytes = (int) buffer->mAudioDataByteSize;
  773. if (0 == _saudio_fifo_read(&_saudio.fifo, ptr, num_bytes)) {
  774. /* not enough read data available, fill the entire buffer with silence */
  775. memset(ptr, 0, num_bytes);
  776. }
  777. }
  778. AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);
  779. }
  780. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  781. SOKOL_ASSERT(0 == _saudio.backend.ca_audio_queue);
  782. /* create an audio queue with fp32 samples */
  783. AudioStreamBasicDescription fmt;
  784. memset(&fmt, 0, sizeof(fmt));
  785. fmt.mSampleRate = (Float64) _saudio.sample_rate;
  786. fmt.mFormatID = kAudioFormatLinearPCM;
  787. fmt.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagIsPacked;
  788. fmt.mFramesPerPacket = 1;
  789. fmt.mChannelsPerFrame = _saudio.num_channels;
  790. fmt.mBytesPerFrame = sizeof(float) * _saudio.num_channels;
  791. fmt.mBytesPerPacket = fmt.mBytesPerFrame;
  792. fmt.mBitsPerChannel = 32;
  793. OSStatus res = AudioQueueNewOutput(&fmt, _sapp_ca_callback, 0, NULL, NULL, 0, &_saudio.backend.ca_audio_queue);
  794. SOKOL_ASSERT((res == 0) && _saudio.backend.ca_audio_queue);
  795. /* create 2 audio buffers */
  796. for (int i = 0; i < 2; i++) {
  797. AudioQueueBufferRef buf = NULL;
  798. const uint32_t buf_byte_size = _saudio.buffer_frames * fmt.mBytesPerFrame;
  799. res = AudioQueueAllocateBuffer(_saudio.backend.ca_audio_queue, buf_byte_size, &buf);
  800. SOKOL_ASSERT((res == 0) && buf);
  801. buf->mAudioDataByteSize = buf_byte_size;
  802. memset(buf->mAudioData, 0, buf->mAudioDataByteSize);
  803. AudioQueueEnqueueBuffer(_saudio.backend.ca_audio_queue, buf, 0, NULL);
  804. }
  805. /* init or modify actual playback parameters */
  806. _saudio.bytes_per_frame = fmt.mBytesPerFrame;
  807. /* ...and start playback */
  808. res = AudioQueueStart(_saudio.backend.ca_audio_queue, NULL);
  809. SOKOL_ASSERT(0 == res);
  810. return true;
  811. }
  812. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  813. AudioQueueStop(_saudio.backend.ca_audio_queue, true);
  814. AudioQueueDispose(_saudio.backend.ca_audio_queue, false);
  815. _saudio.backend.ca_audio_queue = NULL;
  816. }
  817. /*=== ALSA BACKEND IMPLEMENTATION ============================================*/
  818. #elif (defined(__linux__) || defined(__unix__)) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
  819. /* the streaming callback runs in a separate thread */
  820. _SOKOL_PRIVATE void* _saudio_alsa_cb(void* param) {
  821. while (!_saudio.backend.thread_stop) {
  822. /* snd_pcm_writei() will be blocking until it needs data */
  823. int write_res = snd_pcm_writei(_saudio.backend.device, _saudio.backend.buffer, _saudio.backend.buffer_frames);
  824. if (write_res < 0) {
  825. /* underrun occurred */
  826. snd_pcm_prepare(_saudio.backend.device);
  827. }
  828. else {
  829. /* fill the streaming buffer with new data */
  830. if (_saudio_has_callback()) {
  831. _saudio_stream_callback(_saudio.backend.buffer, _saudio.backend.buffer_frames, _saudio.num_channels);
  832. }
  833. else {
  834. if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.buffer, _saudio.backend.buffer_byte_size)) {
  835. /* not enough read data available, fill the entire buffer with silence */
  836. memset(_saudio.backend.buffer, 0, _saudio.backend.buffer_byte_size);
  837. }
  838. }
  839. }
  840. }
  841. return 0;
  842. }
  843. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  844. int dir; unsigned int val;
  845. int rc = snd_pcm_open(&_saudio.backend.device, "default", SND_PCM_STREAM_PLAYBACK, 0);
  846. if (rc < 0) {
  847. return false;
  848. }
  849. snd_pcm_hw_params_t* params = 0;
  850. snd_pcm_hw_params_alloca(&params);
  851. snd_pcm_hw_params_any(_saudio.backend.device, params);
  852. snd_pcm_hw_params_set_access(_saudio.backend.device, params, SND_PCM_ACCESS_RW_INTERLEAVED);
  853. snd_pcm_hw_params_set_channels(_saudio.backend.device, params, _saudio.num_channels);
  854. snd_pcm_hw_params_set_buffer_size(_saudio.backend.device, params, _saudio.buffer_frames);
  855. if (0 > snd_pcm_hw_params_test_format(_saudio.backend.device, params, SND_PCM_FORMAT_FLOAT_LE)) {
  856. goto error;
  857. }
  858. else {
  859. snd_pcm_hw_params_set_format(_saudio.backend.device, params, SND_PCM_FORMAT_FLOAT_LE);
  860. }
  861. val = _saudio.sample_rate;
  862. dir = 0;
  863. if (0 > snd_pcm_hw_params_set_rate_near(_saudio.backend.device, params, &val, &dir)) {
  864. goto error;
  865. }
  866. if (0 > snd_pcm_hw_params(_saudio.backend.device, params)) {
  867. goto error;
  868. }
  869. /* read back actual sample rate and channels */
  870. snd_pcm_hw_params_get_rate(params, &val, &dir);
  871. _saudio.sample_rate = val;
  872. snd_pcm_hw_params_get_channels(params, &val);
  873. SOKOL_ASSERT((int)val == _saudio.num_channels);
  874. _saudio.bytes_per_frame = _saudio.num_channels * sizeof(float);
  875. /* allocate the streaming buffer */
  876. _saudio.backend.buffer_byte_size = _saudio.buffer_frames * _saudio.bytes_per_frame;
  877. _saudio.backend.buffer_frames = _saudio.buffer_frames;
  878. _saudio.backend.buffer = (float*) SOKOL_MALLOC(_saudio.backend.buffer_byte_size);
  879. memset(_saudio.backend.buffer, 0, _saudio.backend.buffer_byte_size);
  880. /* create the buffer-streaming start thread */
  881. if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_alsa_cb, 0)) {
  882. goto error;
  883. }
  884. return true;
  885. error:
  886. if (_saudio.backend.device) {
  887. snd_pcm_close(_saudio.backend.device);
  888. _saudio.backend.device = 0;
  889. }
  890. return false;
  891. };
  892. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  893. SOKOL_ASSERT(_saudio.backend.device);
  894. _saudio.backend.thread_stop = true;
  895. pthread_join(_saudio.backend.thread, 0);
  896. snd_pcm_drain(_saudio.backend.device);
  897. snd_pcm_close(_saudio.backend.device);
  898. SOKOL_FREE(_saudio.backend.buffer);
  899. };
  900. /*=== WASAPI BACKEND IMPLEMENTATION ==========================================*/
  901. #elif defined(_WIN32)
  902. /* fill intermediate buffer with new data and reset buffer_pos */
  903. _SOKOL_PRIVATE void _saudio_wasapi_fill_buffer(void) {
  904. if (_saudio_has_callback()) {
  905. _saudio_stream_callback(_saudio.backend.thread.src_buffer, _saudio.backend.thread.src_buffer_frames, _saudio.num_channels);
  906. }
  907. else {
  908. if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.thread.src_buffer, _saudio.backend.thread.src_buffer_byte_size)) {
  909. /* not enough read data available, fill the entire buffer with silence */
  910. memset(_saudio.backend.thread.src_buffer, 0, _saudio.backend.thread.src_buffer_byte_size);
  911. }
  912. }
  913. }
  914. _SOKOL_PRIVATE void _saudio_wasapi_submit_buffer(UINT32 num_frames) {
  915. BYTE* wasapi_buffer = 0;
  916. if (FAILED(IAudioRenderClient_GetBuffer(_saudio.backend.render_client, num_frames, &wasapi_buffer))) {
  917. return;
  918. }
  919. SOKOL_ASSERT(wasapi_buffer);
  920. /* convert float samples to int16_t, refill float buffer if needed */
  921. const int num_samples = num_frames * _saudio.num_channels;
  922. int16_t* dst = (int16_t*) wasapi_buffer;
  923. uint32_t buffer_pos = _saudio.backend.thread.src_buffer_pos;
  924. const uint32_t buffer_float_size = _saudio.backend.thread.src_buffer_byte_size / sizeof(float);
  925. float* src = _saudio.backend.thread.src_buffer;
  926. for (int i = 0; i < num_samples; i++) {
  927. if (0 == buffer_pos) {
  928. _saudio_wasapi_fill_buffer();
  929. }
  930. dst[i] = (int16_t) (src[buffer_pos] * 0x7FFF);
  931. buffer_pos += 1;
  932. if (buffer_pos == buffer_float_size) {
  933. buffer_pos = 0;
  934. }
  935. }
  936. _saudio.backend.thread.src_buffer_pos = buffer_pos;
  937. IAudioRenderClient_ReleaseBuffer(_saudio.backend.render_client, num_frames, 0);
  938. }
  939. _SOKOL_PRIVATE DWORD WINAPI _saudio_wasapi_thread_fn(LPVOID param) {
  940. (void)param;
  941. _saudio_wasapi_submit_buffer(_saudio.backend.thread.src_buffer_frames);
  942. IAudioClient_Start(_saudio.backend.audio_client);
  943. while (!_saudio.backend.thread.stop) {
  944. WaitForSingleObject(_saudio.backend.thread.buffer_end_event, INFINITE);
  945. UINT32 padding = 0;
  946. if (FAILED(IAudioClient_GetCurrentPadding(_saudio.backend.audio_client, &padding))) {
  947. continue;
  948. }
  949. SOKOL_ASSERT(_saudio.backend.thread.dst_buffer_frames >= (int)padding);
  950. UINT32 num_frames = _saudio.backend.thread.dst_buffer_frames - padding;
  951. if (num_frames > 0) {
  952. _saudio_wasapi_submit_buffer(num_frames);
  953. }
  954. }
  955. return 0;
  956. }
  957. _SOKOL_PRIVATE void _saudio_wasapi_release(void) {
  958. if (_saudio.backend.thread.src_buffer) {
  959. SOKOL_FREE(_saudio.backend.thread.src_buffer);
  960. _saudio.backend.thread.src_buffer = 0;
  961. }
  962. if (_saudio.backend.render_client) {
  963. IAudioRenderClient_Release(_saudio.backend.render_client);
  964. _saudio.backend.render_client = 0;
  965. }
  966. if (_saudio.backend.audio_client) {
  967. IAudioClient_Release(_saudio.backend.audio_client);
  968. _saudio.backend.audio_client = 0;
  969. }
  970. if (_saudio.backend.device) {
  971. IMMDevice_Release(_saudio.backend.device);
  972. _saudio.backend.device = 0;
  973. }
  974. if (_saudio.backend.device_enumerator) {
  975. IMMDeviceEnumerator_Release(_saudio.backend.device_enumerator);
  976. _saudio.backend.device_enumerator = 0;
  977. }
  978. if (0 != _saudio.backend.thread.buffer_end_event) {
  979. CloseHandle(_saudio.backend.thread.buffer_end_event);
  980. _saudio.backend.thread.buffer_end_event = 0;
  981. }
  982. }
  983. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  984. REFERENCE_TIME dur;
  985. if (FAILED(CoInitializeEx(0, COINIT_MULTITHREADED))) {
  986. SOKOL_LOG("sokol_audio wasapi: CoInitializeEx failed");
  987. return false;
  988. }
  989. _saudio.backend.thread.buffer_end_event = CreateEvent(0, FALSE, FALSE, 0);
  990. if (0 == _saudio.backend.thread.buffer_end_event) {
  991. SOKOL_LOG("sokol_audio wasapi: failed to create buffer_end_event");
  992. goto error;
  993. }
  994. if (FAILED(CoCreateInstance(_SOKOL_AUDIO_WIN32COM_ID(_saudio_CLSID_IMMDeviceEnumerator),
  995. 0, CLSCTX_ALL,
  996. _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IMMDeviceEnumerator),
  997. (void**)&_saudio.backend.device_enumerator)))
  998. {
  999. SOKOL_LOG("sokol_audio wasapi: failed to create device enumerator");
  1000. goto error;
  1001. }
  1002. if (FAILED(IMMDeviceEnumerator_GetDefaultAudioEndpoint(_saudio.backend.device_enumerator,
  1003. eRender, eConsole,
  1004. &_saudio.backend.device)))
  1005. {
  1006. SOKOL_LOG("sokol_audio wasapi: GetDefaultAudioEndPoint failed");
  1007. goto error;
  1008. }
  1009. if (FAILED(IMMDevice_Activate(_saudio.backend.device,
  1010. _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioClient),
  1011. CLSCTX_ALL, 0,
  1012. (void**)&_saudio.backend.audio_client)))
  1013. {
  1014. SOKOL_LOG("sokol_audio wasapi: device activate failed");
  1015. goto error;
  1016. }
  1017. WAVEFORMATEX fmt;
  1018. memset(&fmt, 0, sizeof(fmt));
  1019. fmt.nChannels = (WORD) _saudio.num_channels;
  1020. fmt.nSamplesPerSec = _saudio.sample_rate;
  1021. fmt.wFormatTag = WAVE_FORMAT_PCM;
  1022. fmt.wBitsPerSample = 16;
  1023. fmt.nBlockAlign = (fmt.nChannels * fmt.wBitsPerSample) / 8;
  1024. fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign;
  1025. dur = (REFERENCE_TIME)
  1026. (((double)_saudio.buffer_frames) / (((double)_saudio.sample_rate) * (1.0/10000000.0)));
  1027. if (FAILED(IAudioClient_Initialize(_saudio.backend.audio_client,
  1028. AUDCLNT_SHAREMODE_SHARED,
  1029. AUDCLNT_STREAMFLAGS_EVENTCALLBACK|AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM|AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
  1030. dur, 0, &fmt, 0)))
  1031. {
  1032. SOKOL_LOG("sokol_audio wasapi: audio client initialize failed");
  1033. goto error;
  1034. }
  1035. if (FAILED(IAudioClient_GetBufferSize(_saudio.backend.audio_client, &_saudio.backend.thread.dst_buffer_frames))) {
  1036. SOKOL_LOG("sokol_audio wasapi: audio client get buffer size failed");
  1037. goto error;
  1038. }
  1039. if (FAILED(IAudioClient_GetService(_saudio.backend.audio_client,
  1040. _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioRenderClient),
  1041. (void**)&_saudio.backend.render_client)))
  1042. {
  1043. SOKOL_LOG("sokol_audio wasapi: audio client GetService failed");
  1044. goto error;
  1045. }
  1046. if (FAILED(IAudioClient_SetEventHandle(_saudio.backend.audio_client, _saudio.backend.thread.buffer_end_event))) {
  1047. SOKOL_LOG("sokol_audio wasapi: audio client SetEventHandle failed");
  1048. goto error;
  1049. }
  1050. _saudio.backend.si16_bytes_per_frame = _saudio.num_channels * sizeof(int16_t);
  1051. _saudio.bytes_per_frame = _saudio.num_channels * sizeof(float);
  1052. _saudio.backend.thread.src_buffer_frames = _saudio.buffer_frames;
  1053. _saudio.backend.thread.src_buffer_byte_size = _saudio.backend.thread.src_buffer_frames * _saudio.bytes_per_frame;
  1054. /* allocate an intermediate buffer for sample format conversion */
  1055. _saudio.backend.thread.src_buffer = (float*) SOKOL_MALLOC(_saudio.backend.thread.src_buffer_byte_size);
  1056. SOKOL_ASSERT(_saudio.backend.thread.src_buffer);
  1057. /* create streaming thread */
  1058. _saudio.backend.thread.thread_handle = CreateThread(NULL, 0, _saudio_wasapi_thread_fn, 0, 0, 0);
  1059. if (0 == _saudio.backend.thread.thread_handle) {
  1060. SOKOL_LOG("sokol_audio wasapi: CreateThread failed");
  1061. goto error;
  1062. }
  1063. return true;
  1064. error:
  1065. _saudio_wasapi_release();
  1066. return false;
  1067. }
  1068. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1069. if (_saudio.backend.thread.thread_handle) {
  1070. _saudio.backend.thread.stop = true;
  1071. SetEvent(_saudio.backend.thread.buffer_end_event);
  1072. WaitForSingleObject(_saudio.backend.thread.thread_handle, INFINITE);
  1073. CloseHandle(_saudio.backend.thread.thread_handle);
  1074. _saudio.backend.thread.thread_handle = 0;
  1075. }
  1076. if (_saudio.backend.audio_client) {
  1077. IAudioClient_Stop(_saudio.backend.audio_client);
  1078. }
  1079. _saudio_wasapi_release();
  1080. CoUninitialize();
  1081. }
  1082. /*=== EMSCRIPTEN BACKEND IMPLEMENTATION ======================================*/
  1083. #elif defined(__EMSCRIPTEN__)
  1084. #ifdef __cplusplus
  1085. extern "C" {
  1086. #endif
  1087. EMSCRIPTEN_KEEPALIVE int _saudio_emsc_pull(int num_frames) {
  1088. SOKOL_ASSERT(_saudio.backend.buffer);
  1089. if (num_frames == _saudio.buffer_frames) {
  1090. if (_saudio_has_callback()) {
  1091. _saudio_stream_callback((float*)_saudio.backend.buffer, num_frames, _saudio.num_channels);
  1092. }
  1093. else {
  1094. const int num_bytes = num_frames * _saudio.bytes_per_frame;
  1095. if (0 == _saudio_fifo_read(&_saudio.fifo, _saudio.backend.buffer, num_bytes)) {
  1096. /* not enough read data available, fill the entire buffer with silence */
  1097. memset(_saudio.backend.buffer, 0, num_bytes);
  1098. }
  1099. }
  1100. int res = (int) _saudio.backend.buffer;
  1101. return res;
  1102. }
  1103. else {
  1104. return 0;
  1105. }
  1106. }
  1107. #ifdef __cplusplus
  1108. } /* extern "C" */
  1109. #endif
  1110. /* setup the WebAudio context and attach a ScriptProcessorNode */
  1111. EM_JS(int, saudio_js_init, (int sample_rate, int num_channels, int buffer_size), {
  1112. Module._saudio_context = null;
  1113. Module._saudio_node = null;
  1114. if (typeof AudioContext !== 'undefined') {
  1115. Module._saudio_context = new AudioContext({
  1116. sampleRate: sample_rate,
  1117. latencyHint: 'interactive',
  1118. });
  1119. console.log('sokol_audio.h: created AudioContext');
  1120. }
  1121. else if (typeof webkitAudioContext !== 'undefined') {
  1122. Module._saudio_context = new webkitAudioContext({
  1123. sampleRate: sample_rate,
  1124. latencyHint: 'interactive',
  1125. });
  1126. console.log('sokol_audio.h: created webkitAudioContext');
  1127. }
  1128. else {
  1129. Module._saudio_context = null;
  1130. console.log('sokol_audio.h: no WebAudio support');
  1131. }
  1132. if (Module._saudio_context) {
  1133. console.log('sokol_audio.h: sample rate ', Module._saudio_context.sampleRate);
  1134. Module._saudio_node = Module._saudio_context.createScriptProcessor(buffer_size, 0, num_channels);
  1135. Module._saudio_node.onaudioprocess = function pump_audio(event) {
  1136. var num_frames = event.outputBuffer.length;
  1137. var ptr = __saudio_emsc_pull(num_frames);
  1138. if (ptr) {
  1139. var num_channels = event.outputBuffer.numberOfChannels;
  1140. for (var chn = 0; chn < num_channels; chn++) {
  1141. var chan = event.outputBuffer.getChannelData(chn);
  1142. for (var i = 0; i < num_frames; i++) {
  1143. chan[i] = HEAPF32[(ptr>>2) + ((num_channels*i)+chn)]
  1144. }
  1145. }
  1146. }
  1147. };
  1148. Module._saudio_node.connect(Module._saudio_context.destination);
  1149. // in some browsers, WebAudio needs to be activated on a user action
  1150. var resume_webaudio = function() {
  1151. if (Module._saudio_context) {
  1152. if (Module._saudio_context.state === 'suspended') {
  1153. Module._saudio_context.resume();
  1154. }
  1155. }
  1156. };
  1157. document.addEventListener('click', resume_webaudio, {once:true});
  1158. document.addEventListener('touchstart', resume_webaudio, {once:true});
  1159. document.addEventListener('keydown', resume_webaudio, {once:true});
  1160. return 1;
  1161. }
  1162. else {
  1163. return 0;
  1164. }
  1165. });
  1166. /* get the actual sample rate back from the WebAudio context */
  1167. EM_JS(int, saudio_js_sample_rate, (void), {
  1168. if (Module._saudio_context) {
  1169. return Module._saudio_context.sampleRate;
  1170. }
  1171. else {
  1172. return 0;
  1173. }
  1174. });
  1175. /* get the actual buffer size in number of frames */
  1176. EM_JS(int, saudio_js_buffer_frames, (void), {
  1177. if (Module._saudio_node) {
  1178. return Module._saudio_node.bufferSize;
  1179. }
  1180. else {
  1181. return 0;
  1182. }
  1183. });
  1184. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1185. if (saudio_js_init(_saudio.sample_rate, _saudio.num_channels, _saudio.buffer_frames)) {
  1186. _saudio.bytes_per_frame = sizeof(float) * _saudio.num_channels;
  1187. _saudio.sample_rate = saudio_js_sample_rate();
  1188. _saudio.buffer_frames = saudio_js_buffer_frames();
  1189. const int buf_size = _saudio.buffer_frames * _saudio.bytes_per_frame;
  1190. _saudio.backend.buffer = (uint8_t*) SOKOL_MALLOC(buf_size);
  1191. return true;
  1192. }
  1193. else {
  1194. return false;
  1195. }
  1196. }
  1197. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1198. /* on HTML5, there's always a 'hard exit' without warning,
  1199. so nothing useful to do here
  1200. */
  1201. }
  1202. /*=== ANDROID BACKEND IMPLEMENTATION ======================================*/
  1203. #elif defined(__ANDROID__)
  1204. #ifdef __cplusplus
  1205. extern "C" {
  1206. #endif
  1207. _SOKOL_PRIVATE void _saudio_semaphore_init(_saudio_semaphore_t* sem) {
  1208. sem->count = 0;
  1209. int r = pthread_mutex_init(&sem->mutex, NULL);
  1210. SOKOL_ASSERT(r == 0);
  1211. r = pthread_cond_init(&sem->cond, NULL);
  1212. SOKOL_ASSERT(r == 0);
  1213. (void)(r);
  1214. }
  1215. _SOKOL_PRIVATE void _saudio_semaphore_destroy(_saudio_semaphore_t* sem)
  1216. {
  1217. pthread_cond_destroy(&sem->cond);
  1218. pthread_mutex_destroy(&sem->mutex);
  1219. }
  1220. _SOKOL_PRIVATE void _saudio_semaphore_post(_saudio_semaphore_t* sem, int count)
  1221. {
  1222. int r = pthread_mutex_lock(&sem->mutex);
  1223. SOKOL_ASSERT(r == 0);
  1224. for (int ii = 0; ii < count; ii++) {
  1225. r = pthread_cond_signal(&sem->cond);
  1226. SOKOL_ASSERT(r == 0);
  1227. }
  1228. sem->count += count;
  1229. r = pthread_mutex_unlock(&sem->mutex);
  1230. SOKOL_ASSERT(r == 0);
  1231. (void)(r);
  1232. }
  1233. _SOKOL_PRIVATE bool _saudio_semaphore_wait(_saudio_semaphore_t* sem)
  1234. {
  1235. int r = pthread_mutex_lock(&sem->mutex);
  1236. SOKOL_ASSERT(r == 0);
  1237. while (r == 0 && sem->count <= 0) {
  1238. r = pthread_cond_wait(&sem->cond, &sem->mutex);
  1239. }
  1240. bool ok = (r == 0);
  1241. if (ok) {
  1242. --sem->count;
  1243. }
  1244. r = pthread_mutex_unlock(&sem->mutex);
  1245. (void)(r);
  1246. return ok;
  1247. }
  1248. /* fill intermediate buffer with new data and reset buffer_pos */
  1249. _SOKOL_PRIVATE void _saudio_opensles_fill_buffer(void) {
  1250. int src_buffer_frames = _saudio.buffer_frames;
  1251. if (_saudio_has_callback()) {
  1252. _saudio_stream_callback(_saudio.backend.src_buffer, src_buffer_frames, _saudio.num_channels);
  1253. }
  1254. else {
  1255. const int src_buffer_byte_size = src_buffer_frames * _saudio.num_channels * sizeof(float);
  1256. if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.src_buffer, src_buffer_byte_size)) {
  1257. /* not enough read data available, fill the entire buffer with silence */
  1258. memset(_saudio.backend.src_buffer, 0x0, src_buffer_byte_size);
  1259. }
  1260. }
  1261. }
  1262. _SOKOL_PRIVATE void SLAPIENTRY _saudio_opensles_play_cb(SLPlayItf player, void *context, SLuint32 event) {
  1263. (void)(context);
  1264. (void)(player);
  1265. if (event & SL_PLAYEVENT_HEADATEND) {
  1266. _saudio_semaphore_post(&_saudio.backend.buffer_sem, 1);
  1267. }
  1268. }
  1269. _SOKOL_PRIVATE void* _saudio_opensles_thread_fn(void* param) {
  1270. while (!_saudio.backend.thread_stop) {
  1271. /* get next output buffer, advance, next buffer. */
  1272. int16_t* out_buffer = _saudio.backend.output_buffers[_saudio.backend.active_buffer];
  1273. _saudio.backend.active_buffer = (_saudio.backend.active_buffer + 1) % SAUDIO_NUM_BUFFERS;
  1274. int16_t* next_buffer = _saudio.backend.output_buffers[_saudio.backend.active_buffer];
  1275. /* queue this buffer */
  1276. const int buffer_size_bytes = _saudio.buffer_frames * _saudio.num_channels * sizeof(short);
  1277. (*_saudio.backend.player_buffer_queue)->Enqueue(_saudio.backend.player_buffer_queue, out_buffer, buffer_size_bytes);
  1278. /* fill the next buffer */
  1279. _saudio_opensles_fill_buffer();
  1280. const int num_samples = _saudio.num_channels * _saudio.buffer_frames;
  1281. for (int i = 0; i < num_samples; ++i) {
  1282. next_buffer[i] = (int16_t) (_saudio.backend.src_buffer[i] * 0x7FFF);
  1283. }
  1284. _saudio_semaphore_wait(&_saudio.backend.buffer_sem);
  1285. }
  1286. return 0;
  1287. }
  1288. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1289. _saudio.backend.thread_stop = 1;
  1290. pthread_join(_saudio.backend.thread, 0);
  1291. if (_saudio.backend.player_obj) {
  1292. (*_saudio.backend.player_obj)->Destroy(_saudio.backend.player_obj);
  1293. }
  1294. if (_saudio.backend.output_mix_obj) {
  1295. (*_saudio.backend.output_mix_obj)->Destroy(_saudio.backend.output_mix_obj);
  1296. }
  1297. if (_saudio.backend.engine_obj) {
  1298. (*_saudio.backend.engine_obj)->Destroy(_saudio.backend.engine_obj);
  1299. }
  1300. for (int i = 0; i < SAUDIO_NUM_BUFFERS; i++) {
  1301. SOKOL_FREE(_saudio.backend.output_buffers[i]);
  1302. }
  1303. SOKOL_FREE(_saudio.backend.src_buffer);
  1304. }
  1305. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1306. _saudio.bytes_per_frame = sizeof(float) * _saudio.num_channels;
  1307. for (int i = 0; i < SAUDIO_NUM_BUFFERS; ++i) {
  1308. const int buffer_size_bytes = sizeof(int16_t) * _saudio.num_channels * _saudio.buffer_frames;
  1309. _saudio.backend.output_buffers[i] = (int16_t*) SOKOL_MALLOC(buffer_size_bytes);
  1310. SOKOL_ASSERT(_saudio.backend.output_buffers[i]);
  1311. memset(_saudio.backend.output_buffers[i], 0x0, buffer_size_bytes);
  1312. }
  1313. {
  1314. const int buffer_size_bytes = _saudio.bytes_per_frame * _saudio.buffer_frames;
  1315. _saudio.backend.src_buffer = (float*) SOKOL_MALLOC(buffer_size_bytes);
  1316. SOKOL_ASSERT(_saudio.backend.src_buffer);
  1317. memset(_saudio.backend.src_buffer, 0x0, buffer_size_bytes);
  1318. }
  1319. /* Create engine */
  1320. const SLEngineOption opts[] = { SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE };
  1321. if (slCreateEngine(&_saudio.backend.engine_obj, 1, opts, 0, NULL, NULL ) != SL_RESULT_SUCCESS) {
  1322. SOKOL_LOG("sokol_audio opensles: slCreateEngine failed");
  1323. _saudio_backend_shutdown();
  1324. return false;
  1325. }
  1326. (*_saudio.backend.engine_obj)->Realize(_saudio.backend.engine_obj, SL_BOOLEAN_FALSE);
  1327. if ((*_saudio.backend.engine_obj)->GetInterface(_saudio.backend.engine_obj, SL_IID_ENGINE, &_saudio.backend.engine) != SL_RESULT_SUCCESS) {
  1328. SOKOL_LOG("sokol_audio opensles: GetInterface->Engine failed");
  1329. _saudio_backend_shutdown();
  1330. return false;
  1331. }
  1332. /* Create output mix. */
  1333. {
  1334. const SLInterfaceID ids[] = { SL_IID_VOLUME };
  1335. const SLboolean req[] = { SL_BOOLEAN_FALSE };
  1336. if( (*_saudio.backend.engine)->CreateOutputMix(_saudio.backend.engine, &_saudio.backend.output_mix_obj, 1, ids, req) != SL_RESULT_SUCCESS)
  1337. {
  1338. SOKOL_LOG("sokol_audio opensles: CreateOutputMix failed");
  1339. _saudio_backend_shutdown();
  1340. return false;
  1341. }
  1342. (*_saudio.backend.output_mix_obj)->Realize(_saudio.backend.output_mix_obj, SL_BOOLEAN_FALSE);
  1343. if((*_saudio.backend.output_mix_obj)->GetInterface(_saudio.backend.output_mix_obj, SL_IID_VOLUME, &_saudio.backend.output_mix_vol) != SL_RESULT_SUCCESS) {
  1344. SOKOL_LOG("sokol_audio opensles: GetInterface->OutputMixVol failed");
  1345. }
  1346. }
  1347. /* android buffer queue */
  1348. _saudio.backend.in_locator.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  1349. _saudio.backend.in_locator.numBuffers = SAUDIO_NUM_BUFFERS;
  1350. /* data format */
  1351. SLDataFormat_PCM format;
  1352. format.formatType = SL_DATAFORMAT_PCM;
  1353. format.numChannels = _saudio.num_channels;
  1354. format.samplesPerSec = _saudio.sample_rate * 1000;
  1355. format.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
  1356. format.containerSize = 16;
  1357. format.endianness = SL_BYTEORDER_LITTLEENDIAN;
  1358. if (_saudio.num_channels == 2) {
  1359. format.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  1360. } else {
  1361. format.channelMask = SL_SPEAKER_FRONT_CENTER;
  1362. }
  1363. SLDataSource src;
  1364. src.pLocator = &_saudio.backend.in_locator;
  1365. src.pFormat = &format;
  1366. /* Output mix. */
  1367. _saudio.backend.out_locator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  1368. _saudio.backend.out_locator.outputMix = _saudio.backend.output_mix_obj;
  1369. _saudio.backend.dst_data_sink.pLocator = &_saudio.backend.out_locator;
  1370. _saudio.backend.dst_data_sink.pFormat = NULL;
  1371. /* setup player */
  1372. {
  1373. const SLInterfaceID ids[] = { SL_IID_VOLUME, SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
  1374. const SLboolean req[] = { SL_BOOLEAN_FALSE, SL_BOOLEAN_TRUE };
  1375. (*_saudio.backend.engine)->CreateAudioPlayer(_saudio.backend.engine, &_saudio.backend.player_obj, &src, &_saudio.backend.dst_data_sink, sizeof(ids) / sizeof(ids[0]), ids, req);
  1376. (*_saudio.backend.player_obj)->Realize(_saudio.backend.player_obj, SL_BOOLEAN_FALSE);
  1377. (*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_PLAY, &_saudio.backend.player);
  1378. (*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_VOLUME, &_saudio.backend.player_vol);
  1379. (*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &_saudio.backend.player_buffer_queue);
  1380. }
  1381. /* begin */
  1382. {
  1383. const int buffer_size_bytes = sizeof(int16_t) * _saudio.num_channels * _saudio.buffer_frames;
  1384. (*_saudio.backend.player_buffer_queue)->Enqueue(_saudio.backend.player_buffer_queue, _saudio.backend.output_buffers[0], buffer_size_bytes);
  1385. _saudio.backend.active_buffer = (_saudio.backend.active_buffer + 1) % SAUDIO_NUM_BUFFERS;
  1386. (*_saudio.backend.player)->RegisterCallback(_saudio.backend.player, _saudio_opensles_play_cb, NULL);
  1387. (*_saudio.backend.player)->SetCallbackEventsMask(_saudio.backend.player, SL_PLAYEVENT_HEADATEND);
  1388. (*_saudio.backend.player)->SetPlayState(_saudio.backend.player, SL_PLAYSTATE_PLAYING);
  1389. }
  1390. /* create the buffer-streaming start thread */
  1391. if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_opensles_thread_fn, 0)) {
  1392. _saudio_backend_shutdown();
  1393. return false;
  1394. }
  1395. return true;
  1396. }
  1397. #ifdef __cplusplus
  1398. } /* extern "C" */
  1399. #endif
  1400. #else /* dummy backend */
  1401. _SOKOL_PRIVATE bool _saudio_backend_init(void) { return false; };
  1402. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) { };
  1403. #endif
  1404. /*=== PUBLIC API FUNCTIONS ===================================================*/
  1405. SOKOL_API_IMPL void saudio_setup(const saudio_desc* desc) {
  1406. SOKOL_ASSERT(!_saudio.valid);
  1407. SOKOL_ASSERT(desc);
  1408. memset(&_saudio, 0, sizeof(_saudio));
  1409. _saudio.desc = *desc;
  1410. _saudio.stream_cb = desc->stream_cb;
  1411. _saudio.stream_userdata_cb = desc->stream_userdata_cb;
  1412. _saudio.user_data = desc->user_data;
  1413. _saudio.sample_rate = _saudio_def(_saudio.desc.sample_rate, _SAUDIO_DEFAULT_SAMPLE_RATE);
  1414. _saudio.buffer_frames = _saudio_def(_saudio.desc.buffer_frames, _SAUDIO_DEFAULT_BUFFER_FRAMES);
  1415. _saudio.packet_frames = _saudio_def(_saudio.desc.packet_frames, _SAUDIO_DEFAULT_PACKET_FRAMES);
  1416. _saudio.num_packets = _saudio_def(_saudio.desc.num_packets, _SAUDIO_DEFAULT_NUM_PACKETS);
  1417. _saudio.num_channels = _saudio_def(_saudio.desc.num_channels, 1);
  1418. _saudio_fifo_init_mutex(&_saudio.fifo);
  1419. if (_saudio_backend_init()) {
  1420. SOKOL_ASSERT(0 == (_saudio.buffer_frames % _saudio.packet_frames));
  1421. SOKOL_ASSERT(_saudio.bytes_per_frame > 0);
  1422. _saudio_fifo_init(&_saudio.fifo, _saudio.packet_frames * _saudio.bytes_per_frame, _saudio.num_packets);
  1423. _saudio.valid = true;
  1424. }
  1425. }
  1426. SOKOL_API_IMPL void saudio_shutdown(void) {
  1427. if (_saudio.valid) {
  1428. _saudio_backend_shutdown();
  1429. _saudio_fifo_shutdown(&_saudio.fifo);
  1430. _saudio.valid = false;
  1431. }
  1432. }
  1433. SOKOL_API_IMPL bool saudio_isvalid(void) {
  1434. return _saudio.valid;
  1435. }
  1436. SOKOL_API_IMPL void* saudio_userdata(void) {
  1437. return _saudio.desc.user_data;
  1438. }
  1439. SOKOL_API_IMPL saudio_desc saudio_query_desc(void) {
  1440. return _saudio.desc;
  1441. }
  1442. SOKOL_API_IMPL int saudio_sample_rate(void) {
  1443. return _saudio.sample_rate;
  1444. }
  1445. SOKOL_API_IMPL int saudio_buffer_frames(void) {
  1446. return _saudio.buffer_frames;
  1447. }
  1448. SOKOL_API_IMPL int saudio_channels(void) {
  1449. return _saudio.num_channels;
  1450. }
  1451. SOKOL_API_IMPL int saudio_expect(void) {
  1452. if (_saudio.valid) {
  1453. const int num_frames = _saudio_fifo_writable_bytes(&_saudio.fifo) / _saudio.bytes_per_frame;
  1454. return num_frames;
  1455. }
  1456. else {
  1457. return 0;
  1458. }
  1459. }
  1460. SOKOL_API_IMPL int saudio_push(const float* frames, int num_frames) {
  1461. SOKOL_ASSERT(frames && (num_frames > 0));
  1462. if (_saudio.valid) {
  1463. const int num_bytes = num_frames * _saudio.bytes_per_frame;
  1464. const int num_written = _saudio_fifo_write(&_saudio.fifo, (const uint8_t*)frames, num_bytes);
  1465. return num_written / _saudio.bytes_per_frame;
  1466. }
  1467. else {
  1468. return 0;
  1469. }
  1470. }
  1471. #undef _saudio_def
  1472. #undef _saudio_def_flt
  1473. #ifdef _MSC_VER
  1474. #pragma warning(pop)
  1475. #endif
  1476. #endif /* SOKOL_IMPL */