sokol_audio.h 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. #if defined(SOKOL_IMPL) && !defined(SOKOL_AUDIO_IMPL)
  2. #define SOKOL_AUDIO_IMPL
  3. #endif
  4. #ifndef SOKOL_AUDIO_INCLUDED
  5. /*
  6. sokol_audio.h -- cross-platform audio-streaming API
  7. Project URL: https://github.com/floooh/sokol
  8. Do this:
  9. #define SOKOL_IMPL or
  10. #define SOKOL_AUDIO_IMPL
  11. before you include this file in *one* C or C++ file to create the
  12. implementation.
  13. Optionally provide the following defines with your own implementations:
  14. SOKOL_DUMMY_BACKEND - use a dummy backend
  15. SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
  16. SOKOL_LOG(msg) - your own logging function (default: puts(msg))
  17. SOKOL_MALLOC(s) - your own malloc() implementation (default: malloc(s))
  18. SOKOL_FREE(p) - your own free() implementation (default: free(p))
  19. SOKOL_AUDIO_API_DECL- public function declaration prefix (default: extern)
  20. SOKOL_API_DECL - same as SOKOL_AUDIO_API_DECL
  21. SOKOL_API_IMPL - public function implementation prefix (default: -)
  22. SAUDIO_RING_MAX_SLOTS - max number of slots in the push-audio ring buffer (default 1024)
  23. SAUDIO_OSX_USE_SYSTEM_HEADERS - define this to force inclusion of system headers on
  24. macOS instead of using embedded CoreAudio declarations
  25. If sokol_audio.h is compiled as a DLL, define the following before
  26. including the declaration or implementation:
  27. SOKOL_DLL
  28. On Windows, SOKOL_DLL will define SOKOL_AUDIO_API_DECL as __declspec(dllexport)
  29. or __declspec(dllimport) as needed.
  30. Link with the following libraries:
  31. - on macOS: AudioToolbox
  32. - on iOS: AudioToolbox, AVFoundation
  33. - on Linux: asound
  34. - on Android: link with OpenSLES
  35. - on Windows with MSVC or Clang toolchain: no action needed, libs are defined in-source via pragma-comment-lib
  36. - on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' and link with -lole32
  37. FEATURE OVERVIEW
  38. ================
  39. You provide a mono- or stereo-stream of 32-bit float samples, which
  40. Sokol Audio feeds into platform-specific audio backends:
  41. - Windows: WASAPI
  42. - Linux: ALSA
  43. - macOS: CoreAudio
  44. - iOS: CoreAudio+AVAudioSession
  45. - emscripten: WebAudio with ScriptProcessorNode
  46. - Android: OpenSLES
  47. Sokol Audio will not do any buffer mixing or volume control, if you have
  48. multiple independent input streams of sample data you need to perform the
  49. mixing yourself before forwarding the data to Sokol Audio.
  50. There are two mutually exclusive ways to provide the sample data:
  51. 1. Callback model: You provide a callback function, which will be called
  52. when Sokol Audio needs new samples. On all platforms except emscripten,
  53. this function is called from a separate thread.
  54. 2. Push model: Your code pushes small blocks of sample data from your
  55. main loop or a thread you created. The pushed data is stored in
  56. a ring buffer where it is pulled by the backend code when
  57. needed.
  58. The callback model is preferred because it is the most direct way to
  59. feed sample data into the audio backends and also has less moving parts
  60. (there is no ring buffer between your code and the audio backend).
  61. Sometimes it is not possible to generate the audio stream directly in a
  62. callback function running in a separate thread, for such cases Sokol Audio
  63. provides the push-model as a convenience.
  64. SOKOL AUDIO, SOLOUD AND MINIAUDIO
  65. =================================
  66. The WASAPI, ALSA, OpenSLES and CoreAudio backend code has been taken from the
  67. SoLoud library (with some modifications, so any bugs in there are most
  68. likely my fault). If you need a more fully-featured audio solution, check
  69. out SoLoud, it's excellent:
  70. https://github.com/jarikomppa/soloud
  71. Another alternative which feature-wise is somewhere inbetween SoLoud and
  72. sokol-audio might be MiniAudio:
  73. https://github.com/mackron/miniaudio
  74. GLOSSARY
  75. ========
  76. - stream buffer:
  77. The internal audio data buffer, usually provided by the backend API. The
  78. size of the stream buffer defines the base latency, smaller buffers have
  79. lower latency but may cause audio glitches. Bigger buffers reduce or
  80. eliminate glitches, but have a higher base latency.
  81. - stream callback:
  82. Optional callback function which is called by Sokol Audio when it
  83. needs new samples. On Windows, macOS/iOS and Linux, this is called in
  84. a separate thread, on WebAudio, this is called per-frame in the
  85. browser thread.
  86. - channel:
  87. A discrete track of audio data, currently 1-channel (mono) and
  88. 2-channel (stereo) is supported and tested.
  89. - sample:
  90. The magnitude of an audio signal on one channel at a given time. In
  91. Sokol Audio, samples are 32-bit float numbers in the range -1.0 to
  92. +1.0.
  93. - frame:
  94. The tightly packed set of samples for all channels at a given time.
  95. For mono 1 frame is 1 sample. For stereo, 1 frame is 2 samples.
  96. - packet:
  97. In Sokol Audio, a small chunk of audio data that is moved from the
  98. main thread to the audio streaming thread in order to decouple the
  99. rate at which the main thread provides new audio data, and the
  100. streaming thread consuming audio data.
  101. WORKING WITH SOKOL AUDIO
  102. ========================
  103. First call saudio_setup() with your preferred audio playback options.
  104. In most cases you can stick with the default values, these provide
  105. a good balance between low-latency and glitch-free playback
  106. on all audio backends.
  107. If you want to use the callback-model, you need to provide a stream
  108. callback function either in saudio_desc.stream_cb or saudio_desc.stream_userdata_cb,
  109. otherwise keep both function pointers zero-initialized.
  110. Use push model and default playback parameters:
  111. saudio_setup(&(saudio_desc){0});
  112. Use stream callback model and default playback parameters:
  113. saudio_setup(&(saudio_desc){
  114. .stream_cb = my_stream_callback
  115. });
  116. The standard stream callback doesn't have a user data argument, if you want
  117. that, use the alternative stream_userdata_cb and also set the user_data pointer:
  118. saudio_setup(&(saudio_desc){
  119. .stream_userdata_cb = my_stream_callback,
  120. .user_data = &my_data
  121. });
  122. The following playback parameters can be provided through the
  123. saudio_desc struct:
  124. General parameters (both for stream-callback and push-model):
  125. int sample_rate -- the sample rate in Hz, default: 44100
  126. int num_channels -- number of channels, default: 1 (mono)
  127. int buffer_frames -- number of frames in streaming buffer, default: 2048
  128. The stream callback prototype (either with or without userdata):
  129. void (*stream_cb)(float* buffer, int num_frames, int num_channels)
  130. void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data)
  131. Function pointer to the user-provide stream callback.
  132. Push-model parameters:
  133. int packet_frames -- number of frames in a packet, default: 128
  134. int num_packets -- number of packets in ring buffer, default: 64
  135. The sample_rate and num_channels parameters are only hints for the audio
  136. backend, it isn't guaranteed that those are the values used for actual
  137. playback.
  138. To get the actual parameters, call the following functions after
  139. saudio_setup():
  140. int saudio_sample_rate(void)
  141. int saudio_channels(void);
  142. It's unlikely that the number of channels will be different than requested,
  143. but a different sample rate isn't uncommon.
  144. (NOTE: there's an yet unsolved issue when an audio backend might switch
  145. to a different sample rate when switching output devices, for instance
  146. plugging in a bluetooth headset, this case is currently not handled in
  147. Sokol Audio).
  148. You can check if audio initialization was successful with
  149. saudio_isvalid(). If backend initialization failed for some reason
  150. (for instance when there's no audio device in the machine), this
  151. will return false. Not checking for success won't do any harm, all
  152. Sokol Audio function will silently fail when called after initialization
  153. has failed, so apart from missing audio output, nothing bad will happen.
  154. Before your application exits, you should call
  155. saudio_shutdown();
  156. This stops the audio thread (on Linux, Windows and macOS/iOS) and
  157. properly shuts down the audio backend.
  158. THE STREAM CALLBACK MODEL
  159. =========================
  160. To use Sokol Audio in stream-callback-mode, provide a callback function
  161. like this in the saudio_desc struct when calling saudio_setup():
  162. void stream_cb(float* buffer, int num_frames, int num_channels) {
  163. ...
  164. }
  165. Or the alternative version with a user-data argument:
  166. void stream_userdata_cb(float* buffer, int num_frames, int num_channels, void* user_data) {
  167. my_data_t* my_data = (my_data_t*) user_data;
  168. ...
  169. }
  170. The job of the callback function is to fill the *buffer* with 32-bit
  171. float sample values.
  172. To output silence, fill the buffer with zeros:
  173. void stream_cb(float* buffer, int num_frames, int num_channels) {
  174. const int num_samples = num_frames * num_channels;
  175. for (int i = 0; i < num_samples; i++) {
  176. buffer[i] = 0.0f;
  177. }
  178. }
  179. For stereo output (num_channels == 2), the samples for the left
  180. and right channel are interleaved:
  181. void stream_cb(float* buffer, int num_frames, int num_channels) {
  182. assert(2 == num_channels);
  183. for (int i = 0; i < num_frames; i++) {
  184. buffer[2*i + 0] = ...; // left channel
  185. buffer[2*i + 1] = ...; // right channel
  186. }
  187. }
  188. Please keep in mind that the stream callback function is running in a
  189. separate thread, if you need to share data with the main thread you need
  190. to take care yourself to make the access to the shared data thread-safe!
  191. THE PUSH MODEL
  192. ==============
  193. To use the push-model for providing audio data, simply don't set (keep
  194. zero-initialized) the stream_cb field in the saudio_desc struct when
  195. calling saudio_setup().
  196. To provide sample data with the push model, call the saudio_push()
  197. function at regular intervals (for instance once per frame). You can
  198. call the saudio_expect() function to ask Sokol Audio how much room is
  199. in the ring buffer, but if you provide a continuous stream of data
  200. at the right sample rate, saudio_expect() isn't required (it's a simple
  201. way to sync/throttle your sample generation code with the playback
  202. rate though).
  203. With saudio_push() you may need to maintain your own intermediate sample
  204. buffer, since pushing individual sample values isn't very efficient.
  205. The following example is from the MOD player sample in
  206. sokol-samples (https://github.com/floooh/sokol-samples):
  207. const int num_frames = saudio_expect();
  208. if (num_frames > 0) {
  209. const int num_samples = num_frames * saudio_channels();
  210. read_samples(flt_buf, num_samples);
  211. saudio_push(flt_buf, num_frames);
  212. }
  213. Another option is to ignore saudio_expect(), and just push samples as they
  214. are generated in small batches. In this case you *need* to generate the
  215. samples at the right sample rate:
  216. The following example is taken from the Tiny Emulators project
  217. (https://github.com/floooh/chips-test), this is for mono playback,
  218. so (num_samples == num_frames):
  219. // tick the sound generator
  220. if (ay38910_tick(&sys->psg)) {
  221. // new sample is ready
  222. sys->sample_buffer[sys->sample_pos++] = sys->psg.sample;
  223. if (sys->sample_pos == sys->num_samples) {
  224. // new sample packet is ready
  225. saudio_push(sys->sample_buffer, sys->num_samples);
  226. sys->sample_pos = 0;
  227. }
  228. }
  229. THE WEBAUDIO BACKEND
  230. ====================
  231. The WebAudio backend is currently using a ScriptProcessorNode callback to
  232. feed the sample data into WebAudio. ScriptProcessorNode has been
  233. deprecated for a while because it is running from the main thread, with
  234. the default initialization parameters it works 'pretty well' though.
  235. Ultimately Sokol Audio will use Audio Worklets, but this requires a few
  236. more things to fall into place (Audio Worklets implemented everywhere,
  237. SharedArrayBuffers enabled again, and I need to figure out a 'low-cost'
  238. solution in terms of implementation effort, since Audio Worklets are
  239. a lot more complex than ScriptProcessorNode if the audio data needs to come
  240. from the main thread).
  241. The WebAudio backend is automatically selected when compiling for
  242. emscripten (__EMSCRIPTEN__ define exists).
  243. https://developers.google.com/web/updates/2017/12/audio-worklet
  244. https://developers.google.com/web/updates/2018/06/audio-worklet-design-pattern
  245. "Blob URLs": https://www.html5rocks.com/en/tutorials/workers/basics/
  246. THE COREAUDIO BACKEND
  247. =====================
  248. The CoreAudio backend is selected on macOS and iOS (__APPLE__ is defined).
  249. Since the CoreAudio API is implemented in C (not Objective-C) on macOS the
  250. implementation part of Sokol Audio can be included into a C source file.
  251. However on iOS, Sokol Audio must be compiled as Objective-C due to it's
  252. reliance on the AVAudioSession object. The iOS code path support both
  253. being compiled with or without ARC (Automatic Reference Counting).
  254. For thread synchronisation, the CoreAudio backend will use the
  255. pthread_mutex_* functions.
  256. The incoming floating point samples will be directly forwarded to
  257. CoreAudio without further conversion.
  258. macOS and iOS applications that use Sokol Audio need to link with
  259. the AudioToolbox framework.
  260. THE WASAPI BACKEND
  261. ==================
  262. The WASAPI backend is automatically selected when compiling on Windows
  263. (_WIN32 is defined).
  264. For thread synchronisation a Win32 critical section is used.
  265. WASAPI may use a different size for its own streaming buffer then requested,
  266. so the base latency may be slightly bigger. The current backend implementation
  267. converts the incoming floating point sample values to signed 16-bit
  268. integers.
  269. The required Windows system DLLs are linked with #pragma comment(lib, ...),
  270. so you shouldn't need to add additional linker libs in the build process
  271. (otherwise this is a bug which should be fixed in sokol_audio.h).
  272. THE ALSA BACKEND
  273. ================
  274. The ALSA backend is automatically selected when compiling on Linux
  275. ('linux' is defined).
  276. For thread synchronisation, the pthread_mutex_* functions are used.
  277. Samples are directly forwarded to ALSA in 32-bit float format, no
  278. further conversion is taking place.
  279. You need to link with the 'asound' library, and the <alsa/asoundlib.h>
  280. header must be present (usually both are installed with some sort
  281. of ALSA development package).
  282. LICENSE
  283. =======
  284. zlib/libpng license
  285. Copyright (c) 2018 Andre Weissflog
  286. This software is provided 'as-is', without any express or implied warranty.
  287. In no event will the authors be held liable for any damages arising from the
  288. use of this software.
  289. Permission is granted to anyone to use this software for any purpose,
  290. including commercial applications, and to alter it and redistribute it
  291. freely, subject to the following restrictions:
  292. 1. The origin of this software must not be misrepresented; you must not
  293. claim that you wrote the original software. If you use this software in a
  294. product, an acknowledgment in the product documentation would be
  295. appreciated but is not required.
  296. 2. Altered source versions must be plainly marked as such, and must not
  297. be misrepresented as being the original software.
  298. 3. This notice may not be removed or altered from any source
  299. distribution.
  300. */
  301. #define SOKOL_AUDIO_INCLUDED (1)
  302. #include <stdint.h>
  303. #include <stdbool.h>
  304. #if defined(SOKOL_API_DECL) && !defined(SOKOL_AUDIO_API_DECL)
  305. #define SOKOL_AUDIO_API_DECL SOKOL_API_DECL
  306. #endif
  307. #ifndef SOKOL_AUDIO_API_DECL
  308. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_AUDIO_IMPL)
  309. #define SOKOL_AUDIO_API_DECL __declspec(dllexport)
  310. #elif defined(_WIN32) && defined(SOKOL_DLL)
  311. #define SOKOL_AUDIO_API_DECL __declspec(dllimport)
  312. #else
  313. #define SOKOL_AUDIO_API_DECL extern
  314. #endif
  315. #endif
  316. #ifdef __cplusplus
  317. extern "C" {
  318. #endif
  319. typedef struct saudio_desc {
  320. int sample_rate; /* requested sample rate */
  321. int num_channels; /* number of channels, default: 1 (mono) */
  322. int buffer_frames; /* number of frames in streaming buffer */
  323. int packet_frames; /* number of frames in a packet */
  324. int num_packets; /* number of packets in packet queue */
  325. void (*stream_cb)(float* buffer, int num_frames, int num_channels); /* optional streaming callback (no user data) */
  326. void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data); /*... and with user data */
  327. void* user_data; /* optional user data argument for stream_userdata_cb */
  328. } saudio_desc;
  329. /* setup sokol-audio */
  330. SOKOL_AUDIO_API_DECL void saudio_setup(const saudio_desc* desc);
  331. /* shutdown sokol-audio */
  332. SOKOL_AUDIO_API_DECL void saudio_shutdown(void);
  333. /* true after setup if audio backend was successfully initialized */
  334. SOKOL_AUDIO_API_DECL bool saudio_isvalid(void);
  335. /* return the saudio_desc.user_data pointer */
  336. SOKOL_AUDIO_API_DECL void* saudio_userdata(void);
  337. /* return a copy of the original saudio_desc struct */
  338. SOKOL_AUDIO_API_DECL saudio_desc saudio_query_desc(void);
  339. /* actual sample rate */
  340. SOKOL_AUDIO_API_DECL int saudio_sample_rate(void);
  341. /* return actual backend buffer size in number of frames */
  342. SOKOL_AUDIO_API_DECL int saudio_buffer_frames(void);
  343. /* actual number of channels */
  344. SOKOL_AUDIO_API_DECL int saudio_channels(void);
  345. /* get current number of frames to fill packet queue */
  346. SOKOL_AUDIO_API_DECL int saudio_expect(void);
  347. /* push sample frames from main thread, returns number of frames actually pushed */
  348. SOKOL_AUDIO_API_DECL int saudio_push(const float* frames, int num_frames);
  349. #ifdef __cplusplus
  350. } /* extern "C" */
  351. /* reference-based equivalents for c++ */
  352. inline void saudio_setup(const saudio_desc& desc) { return saudio_setup(&desc); }
  353. #endif
  354. #endif // SOKOL_AUDIO_INCLUDED
  355. /*=== IMPLEMENTATION =========================================================*/
  356. #ifdef SOKOL_AUDIO_IMPL
  357. #define SOKOL_AUDIO_IMPL_INCLUDED (1)
  358. #include <string.h> // memset, memcpy
  359. #include <stddef.h> // size_t
  360. #ifndef SOKOL_API_IMPL
  361. #define SOKOL_API_IMPL
  362. #endif
  363. #ifndef SOKOL_DEBUG
  364. #ifndef NDEBUG
  365. #define SOKOL_DEBUG (1)
  366. #endif
  367. #endif
  368. #ifndef SOKOL_ASSERT
  369. #include <assert.h>
  370. #define SOKOL_ASSERT(c) assert(c)
  371. #endif
  372. #ifndef SOKOL_MALLOC
  373. #include <stdlib.h>
  374. #define SOKOL_MALLOC(s) malloc(s)
  375. #define SOKOL_FREE(p) free(p)
  376. #endif
  377. #ifndef SOKOL_LOG
  378. #ifdef SOKOL_DEBUG
  379. #include <stdio.h>
  380. #define SOKOL_LOG(s) { SOKOL_ASSERT(s); puts(s); }
  381. #else
  382. #define SOKOL_LOG(s)
  383. #endif
  384. #endif
  385. #ifndef _SOKOL_PRIVATE
  386. #if defined(__GNUC__) || defined(__clang__)
  387. #define _SOKOL_PRIVATE __attribute__((unused)) static
  388. #else
  389. #define _SOKOL_PRIVATE static
  390. #endif
  391. #endif
  392. #ifndef _SOKOL_UNUSED
  393. #define _SOKOL_UNUSED(x) (void)(x)
  394. #endif
  395. // platform detection defines
  396. #if defined(SOKOL_DUMMY_BACKEND)
  397. // nothing
  398. #elif defined(__APPLE__)
  399. #define _SAUDIO_APPLE (1)
  400. #include <TargetConditionals.h>
  401. #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
  402. #define _SAUDIO_IOS (1)
  403. #else
  404. #define _SAUDIO_MACOS (1)
  405. #endif
  406. #elif defined(__EMSCRIPTEN__)
  407. #define _SAUDIO_EMSCRIPTEN
  408. #elif defined(_WIN32)
  409. #define _SAUDIO_WINDOWS (1)
  410. #include <winapifamily.h>
  411. #if (defined(WINAPI_FAMILY_PARTITION) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
  412. #define _SAUDIO_UWP (1)
  413. #else
  414. #define _SAUDIO_WIN32 (1)
  415. #endif
  416. #elif defined(__ANDROID__)
  417. #define _SAUDIO_ANDROID (1)
  418. #elif defined(__linux__) || defined(__unix__)
  419. #define _SAUDIO_LINUX (1)
  420. #else
  421. #error "sokol_audio.h: Unknown platform"
  422. #endif
  423. // platform-specific headers and definitions
  424. #if defined(SOKOL_DUMMY_BACKEND)
  425. #define _SAUDIO_NOTHREADS (1)
  426. #elif defined(_SAUDIO_WINDOWS)
  427. #define _SAUDIO_WINTHREADS (1)
  428. #ifndef WIN32_LEAN_AND_MEAN
  429. #define WIN32_LEAN_AND_MEAN
  430. #endif
  431. #ifndef NOMINMAX
  432. #define NOMINMAX
  433. #endif
  434. #include <windows.h>
  435. #include <synchapi.h>
  436. #if defined(_SAUDIO_UWP)
  437. #pragma comment (lib, "WindowsApp")
  438. #else
  439. #pragma comment (lib, "kernel32")
  440. #pragma comment (lib, "ole32")
  441. #endif
  442. #ifndef CINTERFACE
  443. #define CINTERFACE
  444. #endif
  445. #ifndef COBJMACROS
  446. #define COBJMACROS
  447. #endif
  448. #ifndef CONST_VTABLE
  449. #define CONST_VTABLE
  450. #endif
  451. #include <mmdeviceapi.h>
  452. #include <audioclient.h>
  453. static const IID _saudio_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, { 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
  454. static const IID _saudio_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, { 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
  455. static const CLSID _saudio_CLSID_IMMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, { 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
  456. static const IID _saudio_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
  457. static const IID _saudio_IID_Devinterface_Audio_Render = { 0xe6327cad, 0xdcec, 0x4949, {0xae, 0x8a, 0x99, 0x1e, 0x97, 0x6a, 0x79, 0xd2 } };
  458. static const IID _saudio_IID_IActivateAudioInterface_Completion_Handler = { 0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90} };
  459. #if defined(__cplusplus)
  460. #define _SOKOL_AUDIO_WIN32COM_ID(x) (x)
  461. #else
  462. #define _SOKOL_AUDIO_WIN32COM_ID(x) (&x)
  463. #endif
  464. /* fix for Visual Studio 2015 SDKs */
  465. #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
  466. #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  467. #endif
  468. #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
  469. #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  470. #endif
  471. #ifdef _MSC_VER
  472. #pragma warning(push)
  473. #pragma warning(disable:4505) /* unreferenced local function has been removed */
  474. #endif
  475. #elif defined(_SAUDIO_APPLE)
  476. #define _SAUDIO_PTHREADS (1)
  477. #include <pthread.h>
  478. #if defined(_SAUDIO_IOS)
  479. // always use system headers on iOS (for now at least)
  480. #if !defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
  481. #define SAUDIO_OSX_USE_SYSTEM_HEADERS (1)
  482. #endif
  483. #if !defined(__cplusplus)
  484. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  485. #error "sokol_audio.h on iOS requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  486. #endif
  487. #endif
  488. #include <AudioToolbox/AudioToolbox.h>
  489. #include <AVFoundation/AVFoundation.h>
  490. #else
  491. #if defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
  492. #include <AudioToolbox/AudioToolbox.h>
  493. #endif
  494. #endif
  495. #elif defined(_SAUDIO_ANDROID)
  496. #define _SAUDIO_PTHREADS (1)
  497. #include <pthread.h>
  498. #include "SLES/OpenSLES_Android.h"
  499. #elif defined(_SAUDIO_LINUX)
  500. #define _SAUDIO_PTHREADS (1)
  501. #include <pthread.h>
  502. #define ALSA_PCM_NEW_HW_PARAMS_API
  503. #include <alsa/asoundlib.h>
  504. #elif defined(__EMSCRIPTEN__)
  505. #define _SAUDIO_NOTHREADS (1)
  506. #include <emscripten/emscripten.h>
  507. #endif
  508. #define _saudio_def(val, def) (((val) == 0) ? (def) : (val))
  509. #define _saudio_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
  510. #define _SAUDIO_DEFAULT_SAMPLE_RATE (44100)
  511. #define _SAUDIO_DEFAULT_BUFFER_FRAMES (2048)
  512. #define _SAUDIO_DEFAULT_PACKET_FRAMES (128)
  513. #define _SAUDIO_DEFAULT_NUM_PACKETS ((_SAUDIO_DEFAULT_BUFFER_FRAMES/_SAUDIO_DEFAULT_PACKET_FRAMES)*4)
  514. #ifndef SAUDIO_RING_MAX_SLOTS
  515. #define SAUDIO_RING_MAX_SLOTS (1024)
  516. #endif
  517. /*=== MUTEX WRAPPER DECLARATIONS =============================================*/
  518. #if defined(_SAUDIO_PTHREADS)
  519. typedef struct {
  520. pthread_mutex_t mutex;
  521. } _saudio_mutex_t;
  522. #elif defined(_SAUDIO_WINTHREADS)
  523. typedef struct {
  524. CRITICAL_SECTION critsec;
  525. } _saudio_mutex_t;
  526. #elif defined(_SAUDIO_NOTHREADS)
  527. typedef struct {
  528. int dummy_mutex;
  529. } _saudio_mutex_t;
  530. #endif
  531. /*=== DUMMY BACKEND DECLARATIONS =============================================*/
  532. #if defined(SOKOL_DUMMY_BACKEND)
  533. typedef struct {
  534. int dummy_backend;
  535. } _saudio_backend_t;
  536. /*=== COREAUDIO BACKEND DECLARATIONS =========================================*/
  537. #elif defined(_SAUDIO_APPLE)
  538. #if defined(SAUDIO_OSX_USE_SYSTEM_HEADERS)
  539. typedef AudioQueueRef _saudio_AudioQueueRef;
  540. typedef AudioQueueBufferRef _saudio_AudioQueueBufferRef;
  541. typedef AudioStreamBasicDescription _saudio_AudioStreamBasicDescription;
  542. typedef OSStatus _saudio_OSStatus;
  543. #define _saudio_kAudioFormatLinearPCM (kAudioFormatLinearPCM)
  544. #define _saudio_kLinearPCMFormatFlagIsFloat (kLinearPCMFormatFlagIsFloat)
  545. #define _saudio_kAudioFormatFlagIsPacked (kAudioFormatFlagIsPacked)
  546. #else
  547. // embedded AudioToolbox declarations
  548. typedef uint32_t _saudio_AudioFormatID;
  549. typedef uint32_t _saudio_AudioFormatFlags;
  550. typedef int32_t _saudio_OSStatus;
  551. typedef uint32_t _saudio_SMPTETimeType;
  552. typedef uint32_t _saudio_SMPTETimeFlags;
  553. typedef uint32_t _saudio_AudioTimeStampFlags;
  554. typedef void* _saudio_CFRunLoopRef;
  555. typedef void* _saudio_CFStringRef;
  556. typedef void* _saudio_AudioQueueRef;
  557. #define _saudio_kAudioFormatLinearPCM ('lpcm')
  558. #define _saudio_kLinearPCMFormatFlagIsFloat (1U << 0)
  559. #define _saudio_kAudioFormatFlagIsPacked (1U << 3)
  560. typedef struct _saudio_AudioStreamBasicDescription {
  561. double mSampleRate;
  562. _saudio_AudioFormatID mFormatID;
  563. _saudio_AudioFormatFlags mFormatFlags;
  564. uint32_t mBytesPerPacket;
  565. uint32_t mFramesPerPacket;
  566. uint32_t mBytesPerFrame;
  567. uint32_t mChannelsPerFrame;
  568. uint32_t mBitsPerChannel;
  569. uint32_t mReserved;
  570. } _saudio_AudioStreamBasicDescription;
  571. typedef struct _saudio_AudioStreamPacketDescription {
  572. int64_t mStartOffset;
  573. uint32_t mVariableFramesInPacket;
  574. uint32_t mDataByteSize;
  575. } _saudio_AudioStreamPacketDescription;
  576. typedef struct _saudio_SMPTETime {
  577. int16_t mSubframes;
  578. int16_t mSubframeDivisor;
  579. uint32_t mCounter;
  580. _saudio_SMPTETimeType mType;
  581. _saudio_SMPTETimeFlags mFlags;
  582. int16_t mHours;
  583. int16_t mMinutes;
  584. int16_t mSeconds;
  585. int16_t mFrames;
  586. } _saudio_SMPTETime;
  587. typedef struct _saudio_AudioTimeStamp {
  588. double mSampleTime;
  589. uint64_t mHostTime;
  590. double mRateScalar;
  591. uint64_t mWordClockTime;
  592. _saudio_SMPTETime mSMPTETime;
  593. _saudio_AudioTimeStampFlags mFlags;
  594. uint32_t mReserved;
  595. } _saudio_AudioTimeStamp;
  596. typedef struct _saudio_AudioQueueBuffer {
  597. const uint32_t mAudioDataBytesCapacity;
  598. void* const mAudioData;
  599. uint32_t mAudioDataByteSize;
  600. void * mUserData;
  601. const uint32_t mPacketDescriptionCapacity;
  602. _saudio_AudioStreamPacketDescription* const mPacketDescriptions;
  603. uint32_t mPacketDescriptionCount;
  604. } _saudio_AudioQueueBuffer;
  605. typedef _saudio_AudioQueueBuffer* _saudio_AudioQueueBufferRef;
  606. typedef void (*_saudio_AudioQueueOutputCallback)(void* user_data, _saudio_AudioQueueRef inAQ, _saudio_AudioQueueBufferRef inBuffer);
  607. 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);
  608. extern _saudio_OSStatus AudioQueueDispose(_saudio_AudioQueueRef inAQ, bool inImmediate);
  609. extern _saudio_OSStatus AudioQueueAllocateBuffer(_saudio_AudioQueueRef inAQ, uint32_t inBufferByteSize, _saudio_AudioQueueBufferRef* outBuffer);
  610. extern _saudio_OSStatus AudioQueueEnqueueBuffer(_saudio_AudioQueueRef inAQ, _saudio_AudioQueueBufferRef inBuffer, uint32_t inNumPacketDescs, const _saudio_AudioStreamPacketDescription* inPacketDescs);
  611. extern _saudio_OSStatus AudioQueueStart(_saudio_AudioQueueRef inAQ, const _saudio_AudioTimeStamp * inStartTime);
  612. extern _saudio_OSStatus AudioQueueStop(_saudio_AudioQueueRef inAQ, bool inImmediate);
  613. #endif // SAUDIO_OSX_USE_SYSTEM_HEADERS
  614. typedef struct {
  615. _saudio_AudioQueueRef ca_audio_queue;
  616. #if defined(_SAUDIO_IOS)
  617. id ca_interruption_handler;
  618. #endif
  619. } _saudio_backend_t;
  620. /*=== ALSA BACKEND DECLARATIONS ==============================================*/
  621. #elif defined(_SAUDIO_LINUX)
  622. typedef struct {
  623. snd_pcm_t* device;
  624. float* buffer;
  625. int buffer_byte_size;
  626. int buffer_frames;
  627. pthread_t thread;
  628. bool thread_stop;
  629. } _saudio_backend_t;
  630. /*=== OpenSLES BACKEND DECLARATIONS ==============================================*/
  631. #elif defined(_SAUDIO_ANDROID)
  632. #define SAUDIO_NUM_BUFFERS 2
  633. typedef struct {
  634. pthread_mutex_t mutex;
  635. pthread_cond_t cond;
  636. int count;
  637. } _saudio_semaphore_t;
  638. typedef struct {
  639. SLObjectItf engine_obj;
  640. SLEngineItf engine;
  641. SLObjectItf output_mix_obj;
  642. SLVolumeItf output_mix_vol;
  643. SLDataLocator_OutputMix out_locator;
  644. SLDataSink dst_data_sink;
  645. SLObjectItf player_obj;
  646. SLPlayItf player;
  647. SLVolumeItf player_vol;
  648. SLAndroidSimpleBufferQueueItf player_buffer_queue;
  649. int16_t* output_buffers[SAUDIO_NUM_BUFFERS];
  650. float* src_buffer;
  651. int active_buffer;
  652. _saudio_semaphore_t buffer_sem;
  653. pthread_t thread;
  654. volatile int thread_stop;
  655. SLDataLocator_AndroidSimpleBufferQueue in_locator;
  656. } _saudio_backend_t;
  657. /*=== WASAPI BACKEND DECLARATIONS ============================================*/
  658. #elif defined(_SAUDIO_WINDOWS)
  659. typedef struct {
  660. HANDLE thread_handle;
  661. HANDLE buffer_end_event;
  662. bool stop;
  663. UINT32 dst_buffer_frames;
  664. int src_buffer_frames;
  665. int src_buffer_byte_size;
  666. int src_buffer_pos;
  667. float* src_buffer;
  668. } _saudio_wasapi_thread_data_t;
  669. typedef struct {
  670. #if defined(_SAUDIO_UWP)
  671. LPOLESTR interface_activation_audio_interface_uid_string;
  672. IActivateAudioInterfaceAsyncOperation* interface_activation_operation;
  673. BOOL interface_activation_success;
  674. HANDLE interface_activation_mutex;
  675. #else
  676. IMMDeviceEnumerator* device_enumerator;
  677. IMMDevice* device;
  678. #endif
  679. IAudioClient* audio_client;
  680. IAudioRenderClient* render_client;
  681. int si16_bytes_per_frame;
  682. _saudio_wasapi_thread_data_t thread;
  683. } _saudio_backend_t;
  684. /*=== WEBAUDIO BACKEND DECLARATIONS ==========================================*/
  685. #elif defined(_SAUDIO_EMSCRIPTEN)
  686. typedef struct {
  687. uint8_t* buffer;
  688. } _saudio_backend_t;
  689. #else
  690. #error "unknown platform"
  691. #endif
  692. /*=== GENERAL DECLARATIONS ===================================================*/
  693. /* a ringbuffer structure */
  694. typedef struct {
  695. int head; // next slot to write to
  696. int tail; // next slot to read from
  697. int num; // number of slots in queue
  698. int queue[SAUDIO_RING_MAX_SLOTS];
  699. } _saudio_ring_t;
  700. /* a packet FIFO structure */
  701. typedef struct {
  702. bool valid;
  703. int packet_size; /* size of a single packets in bytes(!) */
  704. int num_packets; /* number of packet in fifo */
  705. uint8_t* base_ptr; /* packet memory chunk base pointer (dynamically allocated) */
  706. int cur_packet; /* current write-packet */
  707. int cur_offset; /* current byte-offset into current write packet */
  708. _saudio_mutex_t mutex; /* mutex for thread-safe access */
  709. _saudio_ring_t read_queue; /* buffers with data, ready to be streamed */
  710. _saudio_ring_t write_queue; /* empty buffers, ready to be pushed to */
  711. } _saudio_fifo_t;
  712. /* sokol-audio state */
  713. typedef struct {
  714. bool valid;
  715. void (*stream_cb)(float* buffer, int num_frames, int num_channels);
  716. void (*stream_userdata_cb)(float* buffer, int num_frames, int num_channels, void* user_data);
  717. void* user_data;
  718. int sample_rate; /* sample rate */
  719. int buffer_frames; /* number of frames in streaming buffer */
  720. int bytes_per_frame; /* filled by backend */
  721. int packet_frames; /* number of frames in a packet */
  722. int num_packets; /* number of packets in packet queue */
  723. int num_channels; /* actual number of channels */
  724. saudio_desc desc;
  725. _saudio_fifo_t fifo;
  726. _saudio_backend_t backend;
  727. } _saudio_state_t;
  728. static _saudio_state_t _saudio;
  729. _SOKOL_PRIVATE bool _saudio_has_callback(void) {
  730. return (_saudio.stream_cb || _saudio.stream_userdata_cb);
  731. }
  732. _SOKOL_PRIVATE void _saudio_stream_callback(float* buffer, int num_frames, int num_channels) {
  733. if (_saudio.stream_cb) {
  734. _saudio.stream_cb(buffer, num_frames, num_channels);
  735. }
  736. else if (_saudio.stream_userdata_cb) {
  737. _saudio.stream_userdata_cb(buffer, num_frames, num_channels, _saudio.user_data);
  738. }
  739. }
  740. /*=== MUTEX IMPLEMENTATION ===================================================*/
  741. #if defined(_SAUDIO_NOTHREADS)
  742. _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) { (void)m; }
  743. _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) { (void)m; }
  744. _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) { (void)m; }
  745. _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) { (void)m; }
  746. #elif defined(_SAUDIO_PTHREADS)
  747. _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) {
  748. pthread_mutexattr_t attr;
  749. pthread_mutexattr_init(&attr);
  750. pthread_mutex_init(&m->mutex, &attr);
  751. }
  752. _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) {
  753. pthread_mutex_destroy(&m->mutex);
  754. }
  755. _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) {
  756. pthread_mutex_lock(&m->mutex);
  757. }
  758. _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) {
  759. pthread_mutex_unlock(&m->mutex);
  760. }
  761. #elif defined(_SAUDIO_WINTHREADS)
  762. _SOKOL_PRIVATE void _saudio_mutex_init(_saudio_mutex_t* m) {
  763. InitializeCriticalSection(&m->critsec);
  764. }
  765. _SOKOL_PRIVATE void _saudio_mutex_destroy(_saudio_mutex_t* m) {
  766. DeleteCriticalSection(&m->critsec);
  767. }
  768. _SOKOL_PRIVATE void _saudio_mutex_lock(_saudio_mutex_t* m) {
  769. EnterCriticalSection(&m->critsec);
  770. }
  771. _SOKOL_PRIVATE void _saudio_mutex_unlock(_saudio_mutex_t* m) {
  772. LeaveCriticalSection(&m->critsec);
  773. }
  774. #else
  775. #error "unknown platform!"
  776. #endif
  777. /*=== RING-BUFFER QUEUE IMPLEMENTATION =======================================*/
  778. _SOKOL_PRIVATE int _saudio_ring_idx(_saudio_ring_t* ring, int i) {
  779. return (i % ring->num);
  780. }
  781. _SOKOL_PRIVATE void _saudio_ring_init(_saudio_ring_t* ring, int num_slots) {
  782. SOKOL_ASSERT((num_slots + 1) <= SAUDIO_RING_MAX_SLOTS);
  783. ring->head = 0;
  784. ring->tail = 0;
  785. /* one slot reserved to detect 'full' vs 'empty' */
  786. ring->num = num_slots + 1;
  787. }
  788. _SOKOL_PRIVATE bool _saudio_ring_full(_saudio_ring_t* ring) {
  789. return _saudio_ring_idx(ring, ring->head + 1) == ring->tail;
  790. }
  791. _SOKOL_PRIVATE bool _saudio_ring_empty(_saudio_ring_t* ring) {
  792. return ring->head == ring->tail;
  793. }
  794. _SOKOL_PRIVATE int _saudio_ring_count(_saudio_ring_t* ring) {
  795. int count;
  796. if (ring->head >= ring->tail) {
  797. count = ring->head - ring->tail;
  798. }
  799. else {
  800. count = (ring->head + ring->num) - ring->tail;
  801. }
  802. SOKOL_ASSERT(count < ring->num);
  803. return count;
  804. }
  805. _SOKOL_PRIVATE void _saudio_ring_enqueue(_saudio_ring_t* ring, int val) {
  806. SOKOL_ASSERT(!_saudio_ring_full(ring));
  807. ring->queue[ring->head] = val;
  808. ring->head = _saudio_ring_idx(ring, ring->head + 1);
  809. }
  810. _SOKOL_PRIVATE int _saudio_ring_dequeue(_saudio_ring_t* ring) {
  811. SOKOL_ASSERT(!_saudio_ring_empty(ring));
  812. int val = ring->queue[ring->tail];
  813. ring->tail = _saudio_ring_idx(ring, ring->tail + 1);
  814. return val;
  815. }
  816. /*--- a packet fifo for queueing audio data from main thread ----------------*/
  817. _SOKOL_PRIVATE void _saudio_fifo_init_mutex(_saudio_fifo_t* fifo) {
  818. /* this must be called before initializing both the backend and the fifo itself! */
  819. _saudio_mutex_init(&fifo->mutex);
  820. }
  821. _SOKOL_PRIVATE void _saudio_fifo_init(_saudio_fifo_t* fifo, int packet_size, int num_packets) {
  822. /* NOTE: there's a chicken-egg situation during the init phase where the
  823. streaming thread must be started before the fifo is actually initialized,
  824. thus the fifo init must already be protected from access by the fifo_read() func.
  825. */
  826. _saudio_mutex_lock(&fifo->mutex);
  827. SOKOL_ASSERT((packet_size > 0) && (num_packets > 0));
  828. fifo->packet_size = packet_size;
  829. fifo->num_packets = num_packets;
  830. fifo->base_ptr = (uint8_t*) SOKOL_MALLOC((size_t)(packet_size * num_packets));
  831. SOKOL_ASSERT(fifo->base_ptr);
  832. fifo->cur_packet = -1;
  833. fifo->cur_offset = 0;
  834. _saudio_ring_init(&fifo->read_queue, num_packets);
  835. _saudio_ring_init(&fifo->write_queue, num_packets);
  836. for (int i = 0; i < num_packets; i++) {
  837. _saudio_ring_enqueue(&fifo->write_queue, i);
  838. }
  839. SOKOL_ASSERT(_saudio_ring_full(&fifo->write_queue));
  840. SOKOL_ASSERT(_saudio_ring_count(&fifo->write_queue) == num_packets);
  841. SOKOL_ASSERT(_saudio_ring_empty(&fifo->read_queue));
  842. SOKOL_ASSERT(_saudio_ring_count(&fifo->read_queue) == 0);
  843. fifo->valid = true;
  844. _saudio_mutex_unlock(&fifo->mutex);
  845. }
  846. _SOKOL_PRIVATE void _saudio_fifo_shutdown(_saudio_fifo_t* fifo) {
  847. SOKOL_ASSERT(fifo->base_ptr);
  848. SOKOL_FREE(fifo->base_ptr);
  849. fifo->base_ptr = 0;
  850. fifo->valid = false;
  851. _saudio_mutex_destroy(&fifo->mutex);
  852. }
  853. _SOKOL_PRIVATE int _saudio_fifo_writable_bytes(_saudio_fifo_t* fifo) {
  854. _saudio_mutex_lock(&fifo->mutex);
  855. int num_bytes = (_saudio_ring_count(&fifo->write_queue) * fifo->packet_size);
  856. if (fifo->cur_packet != -1) {
  857. num_bytes += fifo->packet_size - fifo->cur_offset;
  858. }
  859. _saudio_mutex_unlock(&fifo->mutex);
  860. SOKOL_ASSERT((num_bytes >= 0) && (num_bytes <= (fifo->num_packets * fifo->packet_size)));
  861. return num_bytes;
  862. }
  863. /* write new data to the write queue, this is called from main thread */
  864. _SOKOL_PRIVATE int _saudio_fifo_write(_saudio_fifo_t* fifo, const uint8_t* ptr, int num_bytes) {
  865. /* returns the number of bytes written, this will be smaller then requested
  866. if the write queue runs full
  867. */
  868. int all_to_copy = num_bytes;
  869. while (all_to_copy > 0) {
  870. /* need to grab a new packet? */
  871. if (fifo->cur_packet == -1) {
  872. _saudio_mutex_lock(&fifo->mutex);
  873. if (!_saudio_ring_empty(&fifo->write_queue)) {
  874. fifo->cur_packet = _saudio_ring_dequeue(&fifo->write_queue);
  875. }
  876. _saudio_mutex_unlock(&fifo->mutex);
  877. SOKOL_ASSERT(fifo->cur_offset == 0);
  878. }
  879. /* append data to current write packet */
  880. if (fifo->cur_packet != -1) {
  881. int to_copy = all_to_copy;
  882. const int max_copy = fifo->packet_size - fifo->cur_offset;
  883. if (to_copy > max_copy) {
  884. to_copy = max_copy;
  885. }
  886. uint8_t* dst = fifo->base_ptr + fifo->cur_packet * fifo->packet_size + fifo->cur_offset;
  887. memcpy(dst, ptr, (size_t)to_copy);
  888. ptr += to_copy;
  889. fifo->cur_offset += to_copy;
  890. all_to_copy -= to_copy;
  891. SOKOL_ASSERT(fifo->cur_offset <= fifo->packet_size);
  892. SOKOL_ASSERT(all_to_copy >= 0);
  893. }
  894. else {
  895. /* early out if we're starving */
  896. int bytes_copied = num_bytes - all_to_copy;
  897. SOKOL_ASSERT((bytes_copied >= 0) && (bytes_copied < num_bytes));
  898. return bytes_copied;
  899. }
  900. /* if write packet is full, push to read queue */
  901. if (fifo->cur_offset == fifo->packet_size) {
  902. _saudio_mutex_lock(&fifo->mutex);
  903. _saudio_ring_enqueue(&fifo->read_queue, fifo->cur_packet);
  904. _saudio_mutex_unlock(&fifo->mutex);
  905. fifo->cur_packet = -1;
  906. fifo->cur_offset = 0;
  907. }
  908. }
  909. SOKOL_ASSERT(all_to_copy == 0);
  910. return num_bytes;
  911. }
  912. /* read queued data, this is called form the stream callback (maybe separate thread) */
  913. _SOKOL_PRIVATE int _saudio_fifo_read(_saudio_fifo_t* fifo, uint8_t* ptr, int num_bytes) {
  914. /* NOTE: fifo_read might be called before the fifo is properly initialized */
  915. _saudio_mutex_lock(&fifo->mutex);
  916. int num_bytes_copied = 0;
  917. if (fifo->valid) {
  918. SOKOL_ASSERT(0 == (num_bytes % fifo->packet_size));
  919. SOKOL_ASSERT(num_bytes <= (fifo->packet_size * fifo->num_packets));
  920. const int num_packets_needed = num_bytes / fifo->packet_size;
  921. uint8_t* dst = ptr;
  922. /* either pull a full buffer worth of data, or nothing */
  923. if (_saudio_ring_count(&fifo->read_queue) >= num_packets_needed) {
  924. for (int i = 0; i < num_packets_needed; i++) {
  925. int packet_index = _saudio_ring_dequeue(&fifo->read_queue);
  926. _saudio_ring_enqueue(&fifo->write_queue, packet_index);
  927. const uint8_t* src = fifo->base_ptr + packet_index * fifo->packet_size;
  928. memcpy(dst, src, (size_t)fifo->packet_size);
  929. dst += fifo->packet_size;
  930. num_bytes_copied += fifo->packet_size;
  931. }
  932. SOKOL_ASSERT(num_bytes == num_bytes_copied);
  933. }
  934. }
  935. _saudio_mutex_unlock(&fifo->mutex);
  936. return num_bytes_copied;
  937. }
  938. /*=== DUMMY BACKEND IMPLEMENTATION ===========================================*/
  939. #if defined(SOKOL_DUMMY_BACKEND)
  940. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  941. _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
  942. return true;
  943. };
  944. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) { };
  945. /*=== COREAUDIO BACKEND IMPLEMENTATION =======================================*/
  946. #elif defined(_SAUDIO_APPLE)
  947. #if defined(_SAUDIO_IOS)
  948. #if __has_feature(objc_arc)
  949. #define _SAUDIO_OBJC_RELEASE(obj) { obj = nil; }
  950. #else
  951. #define _SAUDIO_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  952. #endif
  953. @interface _saudio_interruption_handler : NSObject { }
  954. @end
  955. @implementation _saudio_interruption_handler
  956. -(id)init {
  957. self = [super init];
  958. AVAudioSession* session = [AVAudioSession sharedInstance];
  959. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_interruption:) name:AVAudioSessionInterruptionNotification object:session];
  960. return self;
  961. }
  962. -(void)dealloc {
  963. [self remove_handler];
  964. #if !__has_feature(objc_arc)
  965. [super dealloc];
  966. #endif
  967. }
  968. -(void)remove_handler {
  969. [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVAudioSessionInterruptionNotification" object:nil];
  970. }
  971. -(void)handle_interruption:(NSNotification*)notification {
  972. AVAudioSession* session = [AVAudioSession sharedInstance];
  973. SOKOL_ASSERT(session);
  974. NSDictionary* dict = notification.userInfo;
  975. SOKOL_ASSERT(dict);
  976. NSInteger type = [[dict valueForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  977. switch (type) {
  978. case AVAudioSessionInterruptionTypeBegan:
  979. AudioQueuePause(_saudio.backend.ca_audio_queue);
  980. [session setActive:false error:nil];
  981. break;
  982. case AVAudioSessionInterruptionTypeEnded:
  983. [session setActive:true error:nil];
  984. AudioQueueStart(_saudio.backend.ca_audio_queue, NULL);
  985. break;
  986. default:
  987. break;
  988. }
  989. }
  990. @end
  991. #endif // _SAUDIO_IOS
  992. /* NOTE: the buffer data callback is called on a separate thread! */
  993. _SOKOL_PRIVATE void _saudio_coreaudio_callback(void* user_data, _saudio_AudioQueueRef queue, _saudio_AudioQueueBufferRef buffer) {
  994. _SOKOL_UNUSED(user_data);
  995. if (_saudio_has_callback()) {
  996. const int num_frames = (int)buffer->mAudioDataByteSize / _saudio.bytes_per_frame;
  997. const int num_channels = _saudio.num_channels;
  998. _saudio_stream_callback((float*)buffer->mAudioData, num_frames, num_channels);
  999. }
  1000. else {
  1001. uint8_t* ptr = (uint8_t*)buffer->mAudioData;
  1002. int num_bytes = (int) buffer->mAudioDataByteSize;
  1003. if (0 == _saudio_fifo_read(&_saudio.fifo, ptr, num_bytes)) {
  1004. /* not enough read data available, fill the entire buffer with silence */
  1005. memset(ptr, 0, (size_t)num_bytes);
  1006. }
  1007. }
  1008. AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);
  1009. }
  1010. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1011. SOKOL_ASSERT(0 == _saudio.backend.ca_audio_queue);
  1012. #if defined(_SAUDIO_IOS)
  1013. /* activate audio session */
  1014. AVAudioSession* session = [AVAudioSession sharedInstance];
  1015. SOKOL_ASSERT(session != nil);
  1016. [session setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
  1017. [session setActive:true error:nil];
  1018. /* create interruption handler */
  1019. _saudio.backend.ca_interruption_handler = [[_saudio_interruption_handler alloc] init];
  1020. #endif // _SAUDIO_IOS
  1021. /* create an audio queue with fp32 samples */
  1022. _saudio_AudioStreamBasicDescription fmt;
  1023. memset(&fmt, 0, sizeof(fmt));
  1024. fmt.mSampleRate = (double) _saudio.sample_rate;
  1025. fmt.mFormatID = _saudio_kAudioFormatLinearPCM;
  1026. fmt.mFormatFlags = _saudio_kLinearPCMFormatFlagIsFloat | _saudio_kAudioFormatFlagIsPacked;
  1027. fmt.mFramesPerPacket = 1;
  1028. fmt.mChannelsPerFrame = (uint32_t) _saudio.num_channels;
  1029. fmt.mBytesPerFrame = (uint32_t)sizeof(float) * (uint32_t)_saudio.num_channels;
  1030. fmt.mBytesPerPacket = fmt.mBytesPerFrame;
  1031. fmt.mBitsPerChannel = 32;
  1032. _saudio_OSStatus res = AudioQueueNewOutput(&fmt, _saudio_coreaudio_callback, 0, NULL, NULL, 0, &_saudio.backend.ca_audio_queue);
  1033. SOKOL_ASSERT((res == 0) && _saudio.backend.ca_audio_queue);
  1034. /* create 2 audio buffers */
  1035. for (int i = 0; i < 2; i++) {
  1036. _saudio_AudioQueueBufferRef buf = NULL;
  1037. const uint32_t buf_byte_size = (uint32_t)_saudio.buffer_frames * fmt.mBytesPerFrame;
  1038. res = AudioQueueAllocateBuffer(_saudio.backend.ca_audio_queue, buf_byte_size, &buf);
  1039. SOKOL_ASSERT((res == 0) && buf);
  1040. buf->mAudioDataByteSize = buf_byte_size;
  1041. memset(buf->mAudioData, 0, buf->mAudioDataByteSize);
  1042. AudioQueueEnqueueBuffer(_saudio.backend.ca_audio_queue, buf, 0, NULL);
  1043. }
  1044. /* init or modify actual playback parameters */
  1045. _saudio.bytes_per_frame = (int)fmt.mBytesPerFrame;
  1046. /* ...and start playback */
  1047. res = AudioQueueStart(_saudio.backend.ca_audio_queue, NULL);
  1048. SOKOL_ASSERT(0 == res);
  1049. return true;
  1050. }
  1051. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1052. AudioQueueStop(_saudio.backend.ca_audio_queue, true);
  1053. AudioQueueDispose(_saudio.backend.ca_audio_queue, false);
  1054. _saudio.backend.ca_audio_queue = NULL;
  1055. #if defined(_SAUDIO_IOS)
  1056. /* remove interruption handler */
  1057. if (_saudio.backend.ca_interruption_handler != nil) {
  1058. [_saudio.backend.ca_interruption_handler remove_handler];
  1059. _SAUDIO_OBJC_RELEASE(_saudio.backend.ca_interruption_handler);
  1060. }
  1061. /* deactivate audio session */
  1062. AVAudioSession* session = [AVAudioSession sharedInstance];
  1063. SOKOL_ASSERT(session);
  1064. [session setActive:false error:nil];;
  1065. #endif // _SAUDIO_IOS
  1066. }
  1067. /*=== ALSA BACKEND IMPLEMENTATION ============================================*/
  1068. #elif defined(_SAUDIO_LINUX)
  1069. /* the streaming callback runs in a separate thread */
  1070. _SOKOL_PRIVATE void* _saudio_alsa_cb(void* param) {
  1071. _SOKOL_UNUSED(param);
  1072. while (!_saudio.backend.thread_stop) {
  1073. /* snd_pcm_writei() will be blocking until it needs data */
  1074. int write_res = snd_pcm_writei(_saudio.backend.device, _saudio.backend.buffer, (snd_pcm_uframes_t)_saudio.backend.buffer_frames);
  1075. if (write_res < 0) {
  1076. /* underrun occurred */
  1077. snd_pcm_prepare(_saudio.backend.device);
  1078. }
  1079. else {
  1080. /* fill the streaming buffer with new data */
  1081. if (_saudio_has_callback()) {
  1082. _saudio_stream_callback(_saudio.backend.buffer, _saudio.backend.buffer_frames, _saudio.num_channels);
  1083. }
  1084. else {
  1085. if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.buffer, _saudio.backend.buffer_byte_size)) {
  1086. /* not enough read data available, fill the entire buffer with silence */
  1087. memset(_saudio.backend.buffer, 0, (size_t)_saudio.backend.buffer_byte_size);
  1088. }
  1089. }
  1090. }
  1091. }
  1092. return 0;
  1093. }
  1094. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1095. int dir; uint32_t rate;
  1096. int rc = snd_pcm_open(&_saudio.backend.device, "default", SND_PCM_STREAM_PLAYBACK, 0);
  1097. if (rc < 0) {
  1098. SOKOL_LOG("sokol_audio.h: snd_pcm_open() failed");
  1099. return false;
  1100. }
  1101. /* configuration works by restricting the 'configuration space' step
  1102. by step, we require all parameters except the sample rate to
  1103. match perfectly
  1104. */
  1105. snd_pcm_hw_params_t* params = 0;
  1106. snd_pcm_hw_params_alloca(&params);
  1107. snd_pcm_hw_params_any(_saudio.backend.device, params);
  1108. snd_pcm_hw_params_set_access(_saudio.backend.device, params, SND_PCM_ACCESS_RW_INTERLEAVED);
  1109. if (0 > snd_pcm_hw_params_set_format(_saudio.backend.device, params, SND_PCM_FORMAT_FLOAT_LE)) {
  1110. SOKOL_LOG("sokol_audio.h: float samples not supported");
  1111. goto error;
  1112. }
  1113. if (0 > snd_pcm_hw_params_set_buffer_size(_saudio.backend.device, params, (snd_pcm_uframes_t)_saudio.buffer_frames)) {
  1114. SOKOL_LOG("sokol_audio.h: requested buffer size not supported");
  1115. goto error;
  1116. }
  1117. if (0 > snd_pcm_hw_params_set_channels(_saudio.backend.device, params, (uint32_t)_saudio.num_channels)) {
  1118. SOKOL_LOG("sokol_audio.h: requested channel count not supported");
  1119. goto error;
  1120. }
  1121. /* let ALSA pick a nearby sampling rate */
  1122. rate = (uint32_t) _saudio.sample_rate;
  1123. dir = 0;
  1124. if (0 > snd_pcm_hw_params_set_rate_near(_saudio.backend.device, params, &rate, &dir)) {
  1125. SOKOL_LOG("sokol_audio.h: snd_pcm_hw_params_set_rate_near() failed");
  1126. goto error;
  1127. }
  1128. if (0 > snd_pcm_hw_params(_saudio.backend.device, params)) {
  1129. SOKOL_LOG("sokol_audio.h: snd_pcm_hw_params() failed");
  1130. goto error;
  1131. }
  1132. /* read back actual sample rate and channels */
  1133. _saudio.sample_rate = (int)rate;
  1134. _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
  1135. /* allocate the streaming buffer */
  1136. _saudio.backend.buffer_byte_size = _saudio.buffer_frames * _saudio.bytes_per_frame;
  1137. _saudio.backend.buffer_frames = _saudio.buffer_frames;
  1138. _saudio.backend.buffer = (float*) SOKOL_MALLOC((size_t)_saudio.backend.buffer_byte_size);
  1139. memset(_saudio.backend.buffer, 0, (size_t)_saudio.backend.buffer_byte_size);
  1140. /* create the buffer-streaming start thread */
  1141. if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_alsa_cb, 0)) {
  1142. SOKOL_LOG("sokol_audio.h: pthread_create() failed");
  1143. goto error;
  1144. }
  1145. return true;
  1146. error:
  1147. if (_saudio.backend.device) {
  1148. snd_pcm_close(_saudio.backend.device);
  1149. _saudio.backend.device = 0;
  1150. }
  1151. return false;
  1152. };
  1153. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1154. SOKOL_ASSERT(_saudio.backend.device);
  1155. _saudio.backend.thread_stop = true;
  1156. pthread_join(_saudio.backend.thread, 0);
  1157. snd_pcm_drain(_saudio.backend.device);
  1158. snd_pcm_close(_saudio.backend.device);
  1159. SOKOL_FREE(_saudio.backend.buffer);
  1160. };
  1161. /*=== WASAPI BACKEND IMPLEMENTATION ==========================================*/
  1162. #elif defined(_SAUDIO_WINDOWS)
  1163. #if defined(_SAUDIO_UWP)
  1164. /* Minimal implementation of an IActivateAudioInterfaceCompletionHandler COM object in plain C.
  1165. Meant to be a static singleton (always one reference when add/remove reference)
  1166. and implements IUnknown and IActivateAudioInterfaceCompletionHandler when queryinterface'd
  1167. Do not know why but IActivateAudioInterfaceCompletionHandler's GUID is not the one system queries for,
  1168. so I'm advertising the one actually requested.
  1169. */
  1170. _SOKOL_PRIVATE HRESULT STDMETHODCALLTYPE _saudio_interface_completion_handler_queryinterface(IActivateAudioInterfaceCompletionHandler* instance, REFIID riid, void** ppvObject) {
  1171. if (!ppvObject) {
  1172. return E_POINTER;
  1173. }
  1174. if (IsEqualIID(riid, _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IActivateAudioInterface_Completion_Handler)) || IsEqualIID(riid, _SOKOL_AUDIO_WIN32COM_ID(IID_IUnknown)))
  1175. {
  1176. *ppvObject = (void*)instance;
  1177. return S_OK;
  1178. }
  1179. *ppvObject = NULL;
  1180. return E_NOINTERFACE;
  1181. }
  1182. _SOKOL_PRIVATE ULONG STDMETHODCALLTYPE _saudio_interface_completion_handler_addref_release(IActivateAudioInterfaceCompletionHandler* instance) {
  1183. _SOKOL_UNUSED(instance);
  1184. return 1;
  1185. }
  1186. _SOKOL_PRIVATE HRESULT STDMETHODCALLTYPE _saudio_backend_activate_audio_interface_cb(IActivateAudioInterfaceCompletionHandler* instance, IActivateAudioInterfaceAsyncOperation* activateOperation) {
  1187. _SOKOL_UNUSED(instance);
  1188. WaitForSingleObject(_saudio.backend.interface_activation_mutex, INFINITE);
  1189. _saudio.backend.interface_activation_success = TRUE;
  1190. HRESULT activation_result;
  1191. if (FAILED(activateOperation->lpVtbl->GetActivateResult(activateOperation, &activation_result, (IUnknown**)(&_saudio.backend.audio_client))) || FAILED(activation_result)) {
  1192. _saudio.backend.interface_activation_success = FALSE;
  1193. }
  1194. ReleaseMutex(_saudio.backend.interface_activation_mutex);
  1195. return S_OK;
  1196. }
  1197. #endif // _SAUDIO_UWP
  1198. /* fill intermediate buffer with new data and reset buffer_pos */
  1199. _SOKOL_PRIVATE void _saudio_wasapi_fill_buffer(void) {
  1200. if (_saudio_has_callback()) {
  1201. _saudio_stream_callback(_saudio.backend.thread.src_buffer, _saudio.backend.thread.src_buffer_frames, _saudio.num_channels);
  1202. }
  1203. else {
  1204. if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.thread.src_buffer, _saudio.backend.thread.src_buffer_byte_size)) {
  1205. /* not enough read data available, fill the entire buffer with silence */
  1206. memset(_saudio.backend.thread.src_buffer, 0, (size_t)_saudio.backend.thread.src_buffer_byte_size);
  1207. }
  1208. }
  1209. }
  1210. _SOKOL_PRIVATE void _saudio_wasapi_submit_buffer(int num_frames) {
  1211. BYTE* wasapi_buffer = 0;
  1212. if (FAILED(IAudioRenderClient_GetBuffer(_saudio.backend.render_client, num_frames, &wasapi_buffer))) {
  1213. return;
  1214. }
  1215. SOKOL_ASSERT(wasapi_buffer);
  1216. /* convert float samples to int16_t, refill float buffer if needed */
  1217. const int num_samples = num_frames * _saudio.num_channels;
  1218. int16_t* dst = (int16_t*) wasapi_buffer;
  1219. int buffer_pos = _saudio.backend.thread.src_buffer_pos;
  1220. const int buffer_float_size = _saudio.backend.thread.src_buffer_byte_size / (int)sizeof(float);
  1221. float* src = _saudio.backend.thread.src_buffer;
  1222. for (int i = 0; i < num_samples; i++) {
  1223. if (0 == buffer_pos) {
  1224. _saudio_wasapi_fill_buffer();
  1225. }
  1226. dst[i] = (int16_t) (src[buffer_pos] * 0x7FFF);
  1227. buffer_pos += 1;
  1228. if (buffer_pos == buffer_float_size) {
  1229. buffer_pos = 0;
  1230. }
  1231. }
  1232. _saudio.backend.thread.src_buffer_pos = buffer_pos;
  1233. IAudioRenderClient_ReleaseBuffer(_saudio.backend.render_client, num_frames, 0);
  1234. }
  1235. _SOKOL_PRIVATE DWORD WINAPI _saudio_wasapi_thread_fn(LPVOID param) {
  1236. (void)param;
  1237. _saudio_wasapi_submit_buffer(_saudio.backend.thread.src_buffer_frames);
  1238. IAudioClient_Start(_saudio.backend.audio_client);
  1239. while (!_saudio.backend.thread.stop) {
  1240. WaitForSingleObject(_saudio.backend.thread.buffer_end_event, INFINITE);
  1241. UINT32 padding = 0;
  1242. if (FAILED(IAudioClient_GetCurrentPadding(_saudio.backend.audio_client, &padding))) {
  1243. continue;
  1244. }
  1245. SOKOL_ASSERT(_saudio.backend.thread.dst_buffer_frames >= padding);
  1246. int num_frames = (int)_saudio.backend.thread.dst_buffer_frames - (int)padding;
  1247. if (num_frames > 0) {
  1248. _saudio_wasapi_submit_buffer(num_frames);
  1249. }
  1250. }
  1251. return 0;
  1252. }
  1253. _SOKOL_PRIVATE void _saudio_wasapi_release(void) {
  1254. if (_saudio.backend.thread.src_buffer) {
  1255. SOKOL_FREE(_saudio.backend.thread.src_buffer);
  1256. _saudio.backend.thread.src_buffer = 0;
  1257. }
  1258. if (_saudio.backend.render_client) {
  1259. IAudioRenderClient_Release(_saudio.backend.render_client);
  1260. _saudio.backend.render_client = 0;
  1261. }
  1262. if (_saudio.backend.audio_client) {
  1263. IAudioClient_Release(_saudio.backend.audio_client);
  1264. _saudio.backend.audio_client = 0;
  1265. }
  1266. #if defined(_SAUDIO_UWP)
  1267. if (_saudio.backend.interface_activation_audio_interface_uid_string) {
  1268. CoTaskMemFree(_saudio.backend.interface_activation_audio_interface_uid_string);
  1269. _saudio.backend.interface_activation_audio_interface_uid_string = 0;
  1270. }
  1271. if (_saudio.backend.interface_activation_operation) {
  1272. IActivateAudioInterfaceAsyncOperation_Release(_saudio.backend.interface_activation_operation);
  1273. _saudio.backend.interface_activation_operation = 0;
  1274. }
  1275. #else
  1276. if (_saudio.backend.device) {
  1277. IMMDevice_Release(_saudio.backend.device);
  1278. _saudio.backend.device = 0;
  1279. }
  1280. if (_saudio.backend.device_enumerator) {
  1281. IMMDeviceEnumerator_Release(_saudio.backend.device_enumerator);
  1282. _saudio.backend.device_enumerator = 0;
  1283. }
  1284. #endif
  1285. if (0 != _saudio.backend.thread.buffer_end_event) {
  1286. CloseHandle(_saudio.backend.thread.buffer_end_event);
  1287. _saudio.backend.thread.buffer_end_event = 0;
  1288. }
  1289. }
  1290. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1291. REFERENCE_TIME dur;
  1292. /* UWP Threads are CoInitialized by default with a different threading model, and this call fails
  1293. See https://github.com/Microsoft/cppwinrt/issues/6#issuecomment-253930637 */
  1294. #if defined(_SAUDIO_WIN32)
  1295. /* CoInitializeEx could have been called elsewhere already, in which
  1296. case the function returns with S_FALSE (thus it does not make much
  1297. sense to check the result)
  1298. */
  1299. HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  1300. _SOKOL_UNUSED(hr);
  1301. #endif
  1302. _saudio.backend.thread.buffer_end_event = CreateEvent(0, FALSE, FALSE, 0);
  1303. if (0 == _saudio.backend.thread.buffer_end_event) {
  1304. SOKOL_LOG("sokol_audio wasapi: failed to create buffer_end_event");
  1305. goto error;
  1306. }
  1307. #if defined(_SAUDIO_UWP)
  1308. _saudio.backend.interface_activation_mutex = CreateMutexA(NULL, FALSE, "interface_activation_mutex");
  1309. if (_saudio.backend.interface_activation_mutex == NULL) {
  1310. SOKOL_LOG("sokol_audio wasapi: failed to create interface activation mutex");
  1311. goto error;
  1312. }
  1313. if (FAILED(StringFromIID(_SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_Devinterface_Audio_Render), &_saudio.backend.interface_activation_audio_interface_uid_string))) {
  1314. SOKOL_LOG("sokol_audio wasapi: failed to get default audio device ID string");
  1315. goto error;
  1316. }
  1317. /* static instance of the fake COM object */
  1318. static IActivateAudioInterfaceCompletionHandlerVtbl completion_handler_interface_vtable = {
  1319. _saudio_interface_completion_handler_queryinterface,
  1320. _saudio_interface_completion_handler_addref_release,
  1321. _saudio_interface_completion_handler_addref_release,
  1322. _saudio_backend_activate_audio_interface_cb
  1323. };
  1324. static IActivateAudioInterfaceCompletionHandler completion_handler_interface = { &completion_handler_interface_vtable };
  1325. if (FAILED(ActivateAudioInterfaceAsync(_saudio.backend.interface_activation_audio_interface_uid_string, _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioClient), NULL, &completion_handler_interface, &_saudio.backend.interface_activation_operation))) {
  1326. SOKOL_LOG("sokol_audio wasapi: failed to get default audio device ID string");
  1327. goto error;
  1328. }
  1329. while (!(_saudio.backend.audio_client)) {
  1330. if (WaitForSingleObject(_saudio.backend.interface_activation_mutex, 10) != WAIT_TIMEOUT) {
  1331. ReleaseMutex(_saudio.backend.interface_activation_mutex);
  1332. }
  1333. }
  1334. if (!(_saudio.backend.interface_activation_success)) {
  1335. SOKOL_LOG("sokol_audio wasapi: interface activation failed. Unable to get audio client");
  1336. goto error;
  1337. }
  1338. #else
  1339. if (FAILED(CoCreateInstance(_SOKOL_AUDIO_WIN32COM_ID(_saudio_CLSID_IMMDeviceEnumerator),
  1340. 0, CLSCTX_ALL,
  1341. _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IMMDeviceEnumerator),
  1342. (void**)&_saudio.backend.device_enumerator)))
  1343. {
  1344. SOKOL_LOG("sokol_audio wasapi: failed to create device enumerator");
  1345. goto error;
  1346. }
  1347. if (FAILED(IMMDeviceEnumerator_GetDefaultAudioEndpoint(_saudio.backend.device_enumerator,
  1348. eRender, eConsole,
  1349. &_saudio.backend.device)))
  1350. {
  1351. SOKOL_LOG("sokol_audio wasapi: GetDefaultAudioEndPoint failed");
  1352. goto error;
  1353. }
  1354. if (FAILED(IMMDevice_Activate(_saudio.backend.device,
  1355. _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioClient),
  1356. CLSCTX_ALL, 0,
  1357. (void**)&_saudio.backend.audio_client)))
  1358. {
  1359. SOKOL_LOG("sokol_audio wasapi: device activate failed");
  1360. goto error;
  1361. }
  1362. #endif
  1363. WAVEFORMATEX fmt;
  1364. memset(&fmt, 0, sizeof(fmt));
  1365. fmt.nChannels = (WORD)_saudio.num_channels;
  1366. fmt.nSamplesPerSec = (DWORD)_saudio.sample_rate;
  1367. fmt.wFormatTag = WAVE_FORMAT_PCM;
  1368. fmt.wBitsPerSample = 16;
  1369. fmt.nBlockAlign = (fmt.nChannels * fmt.wBitsPerSample) / 8;
  1370. fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign;
  1371. dur = (REFERENCE_TIME)
  1372. (((double)_saudio.buffer_frames) / (((double)_saudio.sample_rate) * (1.0/10000000.0)));
  1373. if (FAILED(IAudioClient_Initialize(_saudio.backend.audio_client,
  1374. AUDCLNT_SHAREMODE_SHARED,
  1375. AUDCLNT_STREAMFLAGS_EVENTCALLBACK|AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM|AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
  1376. dur, 0, &fmt, 0)))
  1377. {
  1378. SOKOL_LOG("sokol_audio wasapi: audio client initialize failed");
  1379. goto error;
  1380. }
  1381. if (FAILED(IAudioClient_GetBufferSize(_saudio.backend.audio_client, &_saudio.backend.thread.dst_buffer_frames))) {
  1382. SOKOL_LOG("sokol_audio wasapi: audio client get buffer size failed");
  1383. goto error;
  1384. }
  1385. if (FAILED(IAudioClient_GetService(_saudio.backend.audio_client,
  1386. _SOKOL_AUDIO_WIN32COM_ID(_saudio_IID_IAudioRenderClient),
  1387. (void**)&_saudio.backend.render_client)))
  1388. {
  1389. SOKOL_LOG("sokol_audio wasapi: audio client GetService failed");
  1390. goto error;
  1391. }
  1392. if (FAILED(IAudioClient_SetEventHandle(_saudio.backend.audio_client, _saudio.backend.thread.buffer_end_event))) {
  1393. SOKOL_LOG("sokol_audio wasapi: audio client SetEventHandle failed");
  1394. goto error;
  1395. }
  1396. _saudio.backend.si16_bytes_per_frame = _saudio.num_channels * (int)sizeof(int16_t);
  1397. _saudio.bytes_per_frame = _saudio.num_channels * (int)sizeof(float);
  1398. _saudio.backend.thread.src_buffer_frames = _saudio.buffer_frames;
  1399. _saudio.backend.thread.src_buffer_byte_size = _saudio.backend.thread.src_buffer_frames * _saudio.bytes_per_frame;
  1400. /* allocate an intermediate buffer for sample format conversion */
  1401. _saudio.backend.thread.src_buffer = (float*) SOKOL_MALLOC((size_t)_saudio.backend.thread.src_buffer_byte_size);
  1402. SOKOL_ASSERT(_saudio.backend.thread.src_buffer);
  1403. /* create streaming thread */
  1404. _saudio.backend.thread.thread_handle = CreateThread(NULL, 0, _saudio_wasapi_thread_fn, 0, 0, 0);
  1405. if (0 == _saudio.backend.thread.thread_handle) {
  1406. SOKOL_LOG("sokol_audio wasapi: CreateThread failed");
  1407. goto error;
  1408. }
  1409. return true;
  1410. error:
  1411. _saudio_wasapi_release();
  1412. return false;
  1413. }
  1414. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1415. if (_saudio.backend.thread.thread_handle) {
  1416. _saudio.backend.thread.stop = true;
  1417. SetEvent(_saudio.backend.thread.buffer_end_event);
  1418. WaitForSingleObject(_saudio.backend.thread.thread_handle, INFINITE);
  1419. CloseHandle(_saudio.backend.thread.thread_handle);
  1420. _saudio.backend.thread.thread_handle = 0;
  1421. }
  1422. if (_saudio.backend.audio_client) {
  1423. IAudioClient_Stop(_saudio.backend.audio_client);
  1424. }
  1425. _saudio_wasapi_release();
  1426. #if defined(_SAUDIO_WIN32)
  1427. CoUninitialize();
  1428. #endif
  1429. }
  1430. /*=== EMSCRIPTEN BACKEND IMPLEMENTATION ======================================*/
  1431. #elif defined(_SAUDIO_EMSCRIPTEN)
  1432. #ifdef __cplusplus
  1433. extern "C" {
  1434. #endif
  1435. EMSCRIPTEN_KEEPALIVE int _saudio_emsc_pull(int num_frames) {
  1436. SOKOL_ASSERT(_saudio.backend.buffer);
  1437. if (num_frames == _saudio.buffer_frames) {
  1438. if (_saudio_has_callback()) {
  1439. _saudio_stream_callback((float*)_saudio.backend.buffer, num_frames, _saudio.num_channels);
  1440. }
  1441. else {
  1442. const int num_bytes = num_frames * _saudio.bytes_per_frame;
  1443. if (0 == _saudio_fifo_read(&_saudio.fifo, _saudio.backend.buffer, num_bytes)) {
  1444. /* not enough read data available, fill the entire buffer with silence */
  1445. memset(_saudio.backend.buffer, 0, (size_t)num_bytes);
  1446. }
  1447. }
  1448. int res = (int) _saudio.backend.buffer;
  1449. return res;
  1450. }
  1451. else {
  1452. return 0;
  1453. }
  1454. }
  1455. #ifdef __cplusplus
  1456. } /* extern "C" */
  1457. #endif
  1458. /* setup the WebAudio context and attach a ScriptProcessorNode */
  1459. EM_JS(int, saudio_js_init, (int sample_rate, int num_channels, int buffer_size), {
  1460. Module._saudio_context = null;
  1461. Module._saudio_node = null;
  1462. if (typeof AudioContext !== 'undefined') {
  1463. Module._saudio_context = new AudioContext({
  1464. sampleRate: sample_rate,
  1465. latencyHint: 'interactive',
  1466. });
  1467. }
  1468. else if (typeof webkitAudioContext !== 'undefined') {
  1469. Module._saudio_context = new webkitAudioContext({
  1470. sampleRate: sample_rate,
  1471. latencyHint: 'interactive',
  1472. });
  1473. }
  1474. else {
  1475. Module._saudio_context = null;
  1476. console.log('sokol_audio.h: no WebAudio support');
  1477. }
  1478. if (Module._saudio_context) {
  1479. console.log('sokol_audio.h: sample rate ', Module._saudio_context.sampleRate);
  1480. Module._saudio_node = Module._saudio_context.createScriptProcessor(buffer_size, 0, num_channels);
  1481. Module._saudio_node.onaudioprocess = function pump_audio(event) {
  1482. var num_frames = event.outputBuffer.length;
  1483. var ptr = __saudio_emsc_pull(num_frames);
  1484. if (ptr) {
  1485. var num_channels = event.outputBuffer.numberOfChannels;
  1486. for (var chn = 0; chn < num_channels; chn++) {
  1487. var chan = event.outputBuffer.getChannelData(chn);
  1488. for (var i = 0; i < num_frames; i++) {
  1489. chan[i] = HEAPF32[(ptr>>2) + ((num_channels*i)+chn)]
  1490. }
  1491. }
  1492. }
  1493. };
  1494. Module._saudio_node.connect(Module._saudio_context.destination);
  1495. // in some browsers, WebAudio needs to be activated on a user action
  1496. var resume_webaudio = function() {
  1497. if (Module._saudio_context) {
  1498. if (Module._saudio_context.state === 'suspended') {
  1499. Module._saudio_context.resume();
  1500. }
  1501. }
  1502. };
  1503. document.addEventListener('click', resume_webaudio, {once:true});
  1504. document.addEventListener('touchstart', resume_webaudio, {once:true});
  1505. document.addEventListener('keydown', resume_webaudio, {once:true});
  1506. return 1;
  1507. }
  1508. else {
  1509. return 0;
  1510. }
  1511. });
  1512. /* shutdown the WebAudioContext and ScriptProcessorNode */
  1513. EM_JS(void, saudio_js_shutdown, (void), {
  1514. if (Module._saudio_context !== null) {
  1515. if (Module._saudio_node) {
  1516. Module._saudio_node.disconnect();
  1517. }
  1518. Module._saudio_context.close();
  1519. Module._saudio_context = null;
  1520. Module._saudio_node = null;
  1521. }
  1522. });
  1523. /* get the actual sample rate back from the WebAudio context */
  1524. EM_JS(int, saudio_js_sample_rate, (void), {
  1525. if (Module._saudio_context) {
  1526. return Module._saudio_context.sampleRate;
  1527. }
  1528. else {
  1529. return 0;
  1530. }
  1531. });
  1532. /* get the actual buffer size in number of frames */
  1533. EM_JS(int, saudio_js_buffer_frames, (void), {
  1534. if (Module._saudio_node) {
  1535. return Module._saudio_node.bufferSize;
  1536. }
  1537. else {
  1538. return 0;
  1539. }
  1540. });
  1541. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1542. if (saudio_js_init(_saudio.sample_rate, _saudio.num_channels, _saudio.buffer_frames)) {
  1543. _saudio.bytes_per_frame = (int)sizeof(float) * _saudio.num_channels;
  1544. _saudio.sample_rate = saudio_js_sample_rate();
  1545. _saudio.buffer_frames = saudio_js_buffer_frames();
  1546. const size_t buf_size = (size_t) (_saudio.buffer_frames * _saudio.bytes_per_frame);
  1547. _saudio.backend.buffer = (uint8_t*) SOKOL_MALLOC(buf_size);
  1548. return true;
  1549. }
  1550. else {
  1551. return false;
  1552. }
  1553. }
  1554. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1555. saudio_js_shutdown();
  1556. if (_saudio.backend.buffer) {
  1557. SOKOL_FREE(_saudio.backend.buffer);
  1558. _saudio.backend.buffer = 0;
  1559. }
  1560. }
  1561. /*=== ANDROID BACKEND IMPLEMENTATION ======================================*/
  1562. #elif defined(_SAUDIO_ANDROID)
  1563. #ifdef __cplusplus
  1564. extern "C" {
  1565. #endif
  1566. _SOKOL_PRIVATE void _saudio_semaphore_init(_saudio_semaphore_t* sem) {
  1567. sem->count = 0;
  1568. int r = pthread_mutex_init(&sem->mutex, NULL);
  1569. SOKOL_ASSERT(r == 0);
  1570. r = pthread_cond_init(&sem->cond, NULL);
  1571. SOKOL_ASSERT(r == 0);
  1572. (void)(r);
  1573. }
  1574. _SOKOL_PRIVATE void _saudio_semaphore_destroy(_saudio_semaphore_t* sem)
  1575. {
  1576. pthread_cond_destroy(&sem->cond);
  1577. pthread_mutex_destroy(&sem->mutex);
  1578. }
  1579. _SOKOL_PRIVATE void _saudio_semaphore_post(_saudio_semaphore_t* sem, int count)
  1580. {
  1581. int r = pthread_mutex_lock(&sem->mutex);
  1582. SOKOL_ASSERT(r == 0);
  1583. for (int ii = 0; ii < count; ii++) {
  1584. r = pthread_cond_signal(&sem->cond);
  1585. SOKOL_ASSERT(r == 0);
  1586. }
  1587. sem->count += count;
  1588. r = pthread_mutex_unlock(&sem->mutex);
  1589. SOKOL_ASSERT(r == 0);
  1590. (void)(r);
  1591. }
  1592. _SOKOL_PRIVATE bool _saudio_semaphore_wait(_saudio_semaphore_t* sem)
  1593. {
  1594. int r = pthread_mutex_lock(&sem->mutex);
  1595. SOKOL_ASSERT(r == 0);
  1596. while (r == 0 && sem->count <= 0) {
  1597. r = pthread_cond_wait(&sem->cond, &sem->mutex);
  1598. }
  1599. bool ok = (r == 0);
  1600. if (ok) {
  1601. --sem->count;
  1602. }
  1603. r = pthread_mutex_unlock(&sem->mutex);
  1604. (void)(r);
  1605. return ok;
  1606. }
  1607. /* fill intermediate buffer with new data and reset buffer_pos */
  1608. _SOKOL_PRIVATE void _saudio_opensles_fill_buffer(void) {
  1609. int src_buffer_frames = _saudio.buffer_frames;
  1610. if (_saudio_has_callback()) {
  1611. _saudio_stream_callback(_saudio.backend.src_buffer, src_buffer_frames, _saudio.num_channels);
  1612. }
  1613. else {
  1614. const int src_buffer_byte_size = src_buffer_frames * _saudio.num_channels * (int)sizeof(float);
  1615. if (0 == _saudio_fifo_read(&_saudio.fifo, (uint8_t*)_saudio.backend.src_buffer, src_buffer_byte_size)) {
  1616. /* not enough read data available, fill the entire buffer with silence */
  1617. memset(_saudio.backend.src_buffer, 0x0, (size_t)src_buffer_byte_size);
  1618. }
  1619. }
  1620. }
  1621. _SOKOL_PRIVATE void SLAPIENTRY _saudio_opensles_play_cb(SLPlayItf player, void *context, SLuint32 event) {
  1622. (void)(context);
  1623. (void)(player);
  1624. if (event & SL_PLAYEVENT_HEADATEND) {
  1625. _saudio_semaphore_post(&_saudio.backend.buffer_sem, 1);
  1626. }
  1627. }
  1628. _SOKOL_PRIVATE void* _saudio_opensles_thread_fn(void* param) {
  1629. while (!_saudio.backend.thread_stop) {
  1630. /* get next output buffer, advance, next buffer. */
  1631. int16_t* out_buffer = _saudio.backend.output_buffers[_saudio.backend.active_buffer];
  1632. _saudio.backend.active_buffer = (_saudio.backend.active_buffer + 1) % SAUDIO_NUM_BUFFERS;
  1633. int16_t* next_buffer = _saudio.backend.output_buffers[_saudio.backend.active_buffer];
  1634. /* queue this buffer */
  1635. const int buffer_size_bytes = _saudio.buffer_frames * _saudio.num_channels * (int)sizeof(short);
  1636. (*_saudio.backend.player_buffer_queue)->Enqueue(_saudio.backend.player_buffer_queue, out_buffer, (SLuint32)buffer_size_bytes);
  1637. /* fill the next buffer */
  1638. _saudio_opensles_fill_buffer();
  1639. const int num_samples = _saudio.num_channels * _saudio.buffer_frames;
  1640. for (int i = 0; i < num_samples; ++i) {
  1641. next_buffer[i] = (int16_t) (_saudio.backend.src_buffer[i] * 0x7FFF);
  1642. }
  1643. _saudio_semaphore_wait(&_saudio.backend.buffer_sem);
  1644. }
  1645. return 0;
  1646. }
  1647. _SOKOL_PRIVATE void _saudio_backend_shutdown(void) {
  1648. _saudio.backend.thread_stop = 1;
  1649. pthread_join(_saudio.backend.thread, 0);
  1650. if (_saudio.backend.player_obj) {
  1651. (*_saudio.backend.player_obj)->Destroy(_saudio.backend.player_obj);
  1652. }
  1653. if (_saudio.backend.output_mix_obj) {
  1654. (*_saudio.backend.output_mix_obj)->Destroy(_saudio.backend.output_mix_obj);
  1655. }
  1656. if (_saudio.backend.engine_obj) {
  1657. (*_saudio.backend.engine_obj)->Destroy(_saudio.backend.engine_obj);
  1658. }
  1659. for (int i = 0; i < SAUDIO_NUM_BUFFERS; i++) {
  1660. SOKOL_FREE(_saudio.backend.output_buffers[i]);
  1661. }
  1662. SOKOL_FREE(_saudio.backend.src_buffer);
  1663. }
  1664. _SOKOL_PRIVATE bool _saudio_backend_init(void) {
  1665. _saudio.bytes_per_frame = (int)sizeof(float) * _saudio.num_channels;
  1666. for (int i = 0; i < SAUDIO_NUM_BUFFERS; ++i) {
  1667. const int buffer_size_bytes = (int)sizeof(int16_t) * _saudio.num_channels * _saudio.buffer_frames;
  1668. _saudio.backend.output_buffers[i] = (int16_t*) SOKOL_MALLOC((size_t)buffer_size_bytes);
  1669. SOKOL_ASSERT(_saudio.backend.output_buffers[i]);
  1670. memset(_saudio.backend.output_buffers[i], 0x0, (size_t)buffer_size_bytes);
  1671. }
  1672. {
  1673. const int buffer_size_bytes = _saudio.bytes_per_frame * _saudio.buffer_frames;
  1674. _saudio.backend.src_buffer = (float*) SOKOL_MALLOC((size_t)buffer_size_bytes);
  1675. SOKOL_ASSERT(_saudio.backend.src_buffer);
  1676. memset(_saudio.backend.src_buffer, 0x0, (size_t)buffer_size_bytes);
  1677. }
  1678. /* Create engine */
  1679. const SLEngineOption opts[] = { SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE };
  1680. if (slCreateEngine(&_saudio.backend.engine_obj, 1, opts, 0, NULL, NULL ) != SL_RESULT_SUCCESS) {
  1681. SOKOL_LOG("sokol_audio opensles: slCreateEngine failed");
  1682. _saudio_backend_shutdown();
  1683. return false;
  1684. }
  1685. (*_saudio.backend.engine_obj)->Realize(_saudio.backend.engine_obj, SL_BOOLEAN_FALSE);
  1686. if ((*_saudio.backend.engine_obj)->GetInterface(_saudio.backend.engine_obj, SL_IID_ENGINE, &_saudio.backend.engine) != SL_RESULT_SUCCESS) {
  1687. SOKOL_LOG("sokol_audio opensles: GetInterface->Engine failed");
  1688. _saudio_backend_shutdown();
  1689. return false;
  1690. }
  1691. /* Create output mix. */
  1692. {
  1693. const SLInterfaceID ids[] = { SL_IID_VOLUME };
  1694. const SLboolean req[] = { SL_BOOLEAN_FALSE };
  1695. if( (*_saudio.backend.engine)->CreateOutputMix(_saudio.backend.engine, &_saudio.backend.output_mix_obj, 1, ids, req) != SL_RESULT_SUCCESS)
  1696. {
  1697. SOKOL_LOG("sokol_audio opensles: CreateOutputMix failed");
  1698. _saudio_backend_shutdown();
  1699. return false;
  1700. }
  1701. (*_saudio.backend.output_mix_obj)->Realize(_saudio.backend.output_mix_obj, SL_BOOLEAN_FALSE);
  1702. if((*_saudio.backend.output_mix_obj)->GetInterface(_saudio.backend.output_mix_obj, SL_IID_VOLUME, &_saudio.backend.output_mix_vol) != SL_RESULT_SUCCESS) {
  1703. SOKOL_LOG("sokol_audio opensles: GetInterface->OutputMixVol failed");
  1704. }
  1705. }
  1706. /* android buffer queue */
  1707. _saudio.backend.in_locator.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  1708. _saudio.backend.in_locator.numBuffers = SAUDIO_NUM_BUFFERS;
  1709. /* data format */
  1710. SLDataFormat_PCM format;
  1711. format.formatType = SL_DATAFORMAT_PCM;
  1712. format.numChannels = (SLuint32)_saudio.num_channels;
  1713. format.samplesPerSec = (SLuint32) (_saudio.sample_rate * 1000);
  1714. format.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
  1715. format.containerSize = 16;
  1716. format.endianness = SL_BYTEORDER_LITTLEENDIAN;
  1717. if (_saudio.num_channels == 2) {
  1718. format.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  1719. } else {
  1720. format.channelMask = SL_SPEAKER_FRONT_CENTER;
  1721. }
  1722. SLDataSource src;
  1723. src.pLocator = &_saudio.backend.in_locator;
  1724. src.pFormat = &format;
  1725. /* Output mix. */
  1726. _saudio.backend.out_locator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  1727. _saudio.backend.out_locator.outputMix = _saudio.backend.output_mix_obj;
  1728. _saudio.backend.dst_data_sink.pLocator = &_saudio.backend.out_locator;
  1729. _saudio.backend.dst_data_sink.pFormat = NULL;
  1730. /* setup player */
  1731. {
  1732. const SLInterfaceID ids[] = { SL_IID_VOLUME, SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
  1733. const SLboolean req[] = { SL_BOOLEAN_FALSE, SL_BOOLEAN_TRUE };
  1734. (*_saudio.backend.engine)->CreateAudioPlayer(_saudio.backend.engine, &_saudio.backend.player_obj, &src, &_saudio.backend.dst_data_sink, sizeof(ids) / sizeof(ids[0]), ids, req);
  1735. (*_saudio.backend.player_obj)->Realize(_saudio.backend.player_obj, SL_BOOLEAN_FALSE);
  1736. (*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_PLAY, &_saudio.backend.player);
  1737. (*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_VOLUME, &_saudio.backend.player_vol);
  1738. (*_saudio.backend.player_obj)->GetInterface(_saudio.backend.player_obj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &_saudio.backend.player_buffer_queue);
  1739. }
  1740. /* begin */
  1741. {
  1742. const int buffer_size_bytes = (int)sizeof(int16_t) * _saudio.num_channels * _saudio.buffer_frames;
  1743. (*_saudio.backend.player_buffer_queue)->Enqueue(_saudio.backend.player_buffer_queue, _saudio.backend.output_buffers[0], (SLuint32)buffer_size_bytes);
  1744. _saudio.backend.active_buffer = (_saudio.backend.active_buffer + 1) % SAUDIO_NUM_BUFFERS;
  1745. (*_saudio.backend.player)->RegisterCallback(_saudio.backend.player, _saudio_opensles_play_cb, NULL);
  1746. (*_saudio.backend.player)->SetCallbackEventsMask(_saudio.backend.player, SL_PLAYEVENT_HEADATEND);
  1747. (*_saudio.backend.player)->SetPlayState(_saudio.backend.player, SL_PLAYSTATE_PLAYING);
  1748. }
  1749. /* create the buffer-streaming start thread */
  1750. if (0 != pthread_create(&_saudio.backend.thread, 0, _saudio_opensles_thread_fn, 0)) {
  1751. _saudio_backend_shutdown();
  1752. return false;
  1753. }
  1754. return true;
  1755. }
  1756. #ifdef __cplusplus
  1757. } /* extern "C" */
  1758. #endif
  1759. #else
  1760. #error "unsupported platform"
  1761. #endif
  1762. /*=== PUBLIC API FUNCTIONS ===================================================*/
  1763. SOKOL_API_IMPL void saudio_setup(const saudio_desc* desc) {
  1764. SOKOL_ASSERT(!_saudio.valid);
  1765. SOKOL_ASSERT(desc);
  1766. memset(&_saudio, 0, sizeof(_saudio));
  1767. _saudio.desc = *desc;
  1768. _saudio.stream_cb = desc->stream_cb;
  1769. _saudio.stream_userdata_cb = desc->stream_userdata_cb;
  1770. _saudio.user_data = desc->user_data;
  1771. _saudio.sample_rate = _saudio_def(_saudio.desc.sample_rate, _SAUDIO_DEFAULT_SAMPLE_RATE);
  1772. _saudio.buffer_frames = _saudio_def(_saudio.desc.buffer_frames, _SAUDIO_DEFAULT_BUFFER_FRAMES);
  1773. _saudio.packet_frames = _saudio_def(_saudio.desc.packet_frames, _SAUDIO_DEFAULT_PACKET_FRAMES);
  1774. _saudio.num_packets = _saudio_def(_saudio.desc.num_packets, _SAUDIO_DEFAULT_NUM_PACKETS);
  1775. _saudio.num_channels = _saudio_def(_saudio.desc.num_channels, 1);
  1776. _saudio_fifo_init_mutex(&_saudio.fifo);
  1777. if (_saudio_backend_init()) {
  1778. /* the backend might not support the requested exact buffer size,
  1779. make sure the actual buffer size is still a multiple of
  1780. the requested packet size
  1781. */
  1782. if (0 != (_saudio.buffer_frames % _saudio.packet_frames)) {
  1783. SOKOL_LOG("sokol_audio.h: actual backend buffer size isn't multiple of requested packet size");
  1784. _saudio_backend_shutdown();
  1785. return;
  1786. }
  1787. SOKOL_ASSERT(_saudio.bytes_per_frame > 0);
  1788. _saudio_fifo_init(&_saudio.fifo, _saudio.packet_frames * _saudio.bytes_per_frame, _saudio.num_packets);
  1789. _saudio.valid = true;
  1790. }
  1791. }
  1792. SOKOL_API_IMPL void saudio_shutdown(void) {
  1793. if (_saudio.valid) {
  1794. _saudio_backend_shutdown();
  1795. _saudio_fifo_shutdown(&_saudio.fifo);
  1796. _saudio.valid = false;
  1797. }
  1798. }
  1799. SOKOL_API_IMPL bool saudio_isvalid(void) {
  1800. return _saudio.valid;
  1801. }
  1802. SOKOL_API_IMPL void* saudio_userdata(void) {
  1803. return _saudio.desc.user_data;
  1804. }
  1805. SOKOL_API_IMPL saudio_desc saudio_query_desc(void) {
  1806. return _saudio.desc;
  1807. }
  1808. SOKOL_API_IMPL int saudio_sample_rate(void) {
  1809. return _saudio.sample_rate;
  1810. }
  1811. SOKOL_API_IMPL int saudio_buffer_frames(void) {
  1812. return _saudio.buffer_frames;
  1813. }
  1814. SOKOL_API_IMPL int saudio_channels(void) {
  1815. return _saudio.num_channels;
  1816. }
  1817. SOKOL_API_IMPL int saudio_expect(void) {
  1818. if (_saudio.valid) {
  1819. const int num_frames = _saudio_fifo_writable_bytes(&_saudio.fifo) / _saudio.bytes_per_frame;
  1820. return num_frames;
  1821. }
  1822. else {
  1823. return 0;
  1824. }
  1825. }
  1826. SOKOL_API_IMPL int saudio_push(const float* frames, int num_frames) {
  1827. SOKOL_ASSERT(frames && (num_frames > 0));
  1828. if (_saudio.valid) {
  1829. const int num_bytes = num_frames * _saudio.bytes_per_frame;
  1830. const int num_written = _saudio_fifo_write(&_saudio.fifo, (const uint8_t*)frames, num_bytes);
  1831. return num_written / _saudio.bytes_per_frame;
  1832. }
  1833. else {
  1834. return 0;
  1835. }
  1836. }
  1837. #undef _saudio_def
  1838. #undef _saudio_def_flt
  1839. #if defined(_SAUDIO_WINDOWS)
  1840. #ifdef _MSC_VER
  1841. #pragma warning(pop)
  1842. #endif
  1843. #endif
  1844. #endif /* SOKOL_AUDIO_IMPL */