sokol_audio.h 102 KB

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