sokol_audio.h 102 KB

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