sokol_audio.h 103 KB

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