SDL_emscriptenaudio.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../../SDL_internal.h"
  19. #if SDL_AUDIO_DRIVER_EMSCRIPTEN
  20. #include "SDL_audio.h"
  21. #include "../SDL_audio_c.h"
  22. #include "SDL_emscriptenaudio.h"
  23. #include <emscripten/emscripten.h>
  24. /* !!! FIXME: this currently expects that the audio callback runs in the main thread,
  25. !!! FIXME: in intervals when the application isn't running, but that may not be
  26. !!! FIXME: true always once pthread support becomes widespread. Revisit this code
  27. !!! FIXME: at some point and see what needs to be done for that! */
  28. static void FeedAudioDevice(_THIS, const void *buf, const int buflen)
  29. {
  30. const int framelen = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
  31. /* *INDENT-OFF* */ /* clang-format off */
  32. MAIN_THREAD_EM_ASM({
  33. var SDL2 = Module['SDL2'];
  34. var numChannels = SDL2.audio.currentOutputBuffer['numberOfChannels'];
  35. for (var c = 0; c < numChannels; ++c) {
  36. var channelData = SDL2.audio.currentOutputBuffer['getChannelData'](c);
  37. if (channelData.length != $1) {
  38. throw 'Web Audio output buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
  39. }
  40. for (var j = 0; j < $1; ++j) {
  41. channelData[j] = HEAPF32[$0 + ((j*numChannels + c) << 2) >> 2]; /* !!! FIXME: why are these shifts here? */
  42. }
  43. }
  44. }, buf, buflen / framelen);
  45. /* *INDENT-ON* */ /* clang-format on */
  46. }
  47. static void HandleAudioProcess(_THIS)
  48. {
  49. SDL_AudioCallback callback = this->callbackspec.callback;
  50. const int stream_len = this->callbackspec.size;
  51. /* Only do something if audio is enabled */
  52. if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
  53. if (this->stream) {
  54. SDL_AudioStreamClear(this->stream);
  55. }
  56. SDL_memset(this->work_buffer, this->spec.silence, this->spec.size);
  57. FeedAudioDevice(this, this->work_buffer, this->spec.size);
  58. return;
  59. }
  60. if (this->stream == NULL) { /* no conversion necessary. */
  61. SDL_assert(this->spec.size == stream_len);
  62. callback(this->callbackspec.userdata, this->work_buffer, stream_len);
  63. } else { /* streaming/converting */
  64. int got;
  65. while (SDL_AudioStreamAvailable(this->stream) < ((int)this->spec.size)) {
  66. callback(this->callbackspec.userdata, this->work_buffer, stream_len);
  67. if (SDL_AudioStreamPut(this->stream, this->work_buffer, stream_len) == -1) {
  68. SDL_AudioStreamClear(this->stream);
  69. SDL_AtomicSet(&this->enabled, 0);
  70. break;
  71. }
  72. }
  73. got = SDL_AudioStreamGet(this->stream, this->work_buffer, this->spec.size);
  74. SDL_assert((got < 0) || (got == this->spec.size));
  75. if (got != this->spec.size) {
  76. SDL_memset(this->work_buffer, this->spec.silence, this->spec.size);
  77. }
  78. }
  79. FeedAudioDevice(this, this->work_buffer, this->spec.size);
  80. }
  81. static void HandleCaptureProcess(_THIS)
  82. {
  83. SDL_AudioCallback callback = this->callbackspec.callback;
  84. const int stream_len = this->callbackspec.size;
  85. /* Only do something if audio is enabled */
  86. if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
  87. SDL_AudioStreamClear(this->stream);
  88. return;
  89. }
  90. /* *INDENT-OFF* */ /* clang-format off */
  91. MAIN_THREAD_EM_ASM({
  92. var SDL2 = Module['SDL2'];
  93. var numChannels = SDL2.capture.currentCaptureBuffer.numberOfChannels;
  94. for (var c = 0; c < numChannels; ++c) {
  95. var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(c);
  96. if (channelData.length != $1) {
  97. throw 'Web Audio capture buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
  98. }
  99. if (numChannels == 1) { /* fastpath this a little for the common (mono) case. */
  100. for (var j = 0; j < $1; ++j) {
  101. setValue($0 + (j * 4), channelData[j], 'float');
  102. }
  103. } else {
  104. for (var j = 0; j < $1; ++j) {
  105. setValue($0 + (((j * numChannels) + c) * 4), channelData[j], 'float');
  106. }
  107. }
  108. }
  109. }, this->work_buffer, (this->spec.size / sizeof(float)) / this->spec.channels);
  110. /* *INDENT-ON* */ /* clang-format on */
  111. /* okay, we've got an interleaved float32 array in C now. */
  112. if (this->stream == NULL) { /* no conversion necessary. */
  113. SDL_assert(this->spec.size == stream_len);
  114. callback(this->callbackspec.userdata, this->work_buffer, stream_len);
  115. } else { /* streaming/converting */
  116. if (SDL_AudioStreamPut(this->stream, this->work_buffer, this->spec.size) == -1) {
  117. SDL_AtomicSet(&this->enabled, 0);
  118. }
  119. while (SDL_AudioStreamAvailable(this->stream) >= stream_len) {
  120. const int got = SDL_AudioStreamGet(this->stream, this->work_buffer, stream_len);
  121. SDL_assert((got < 0) || (got == stream_len));
  122. if (got != stream_len) {
  123. SDL_memset(this->work_buffer, this->callbackspec.silence, stream_len);
  124. }
  125. callback(this->callbackspec.userdata, this->work_buffer, stream_len); /* Send it to the app. */
  126. }
  127. }
  128. }
  129. static void EMSCRIPTENAUDIO_CloseDevice(_THIS)
  130. {
  131. /* *INDENT-OFF* */ /* clang-format off */
  132. MAIN_THREAD_EM_ASM({
  133. var SDL2 = Module['SDL2'];
  134. if ($0) {
  135. if (SDL2.capture.silenceTimer !== undefined) {
  136. clearTimeout(SDL2.capture.silenceTimer);
  137. }
  138. if (SDL2.capture.stream !== undefined) {
  139. var tracks = SDL2.capture.stream.getAudioTracks();
  140. for (var i = 0; i < tracks.length; i++) {
  141. SDL2.capture.stream.removeTrack(tracks[i]);
  142. }
  143. SDL2.capture.stream = undefined;
  144. }
  145. if (SDL2.capture.scriptProcessorNode !== undefined) {
  146. SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {};
  147. SDL2.capture.scriptProcessorNode.disconnect();
  148. SDL2.capture.scriptProcessorNode = undefined;
  149. }
  150. if (SDL2.capture.mediaStreamNode !== undefined) {
  151. SDL2.capture.mediaStreamNode.disconnect();
  152. SDL2.capture.mediaStreamNode = undefined;
  153. }
  154. if (SDL2.capture.silenceBuffer !== undefined) {
  155. SDL2.capture.silenceBuffer = undefined
  156. }
  157. SDL2.capture = undefined;
  158. } else {
  159. if (SDL2.audio.scriptProcessorNode != undefined) {
  160. SDL2.audio.scriptProcessorNode.disconnect();
  161. SDL2.audio.scriptProcessorNode = undefined;
  162. }
  163. SDL2.audio = undefined;
  164. }
  165. if ((SDL2.audioContext !== undefined) && (SDL2.audio === undefined) && (SDL2.capture === undefined)) {
  166. SDL2.audioContext.close();
  167. SDL2.audioContext = undefined;
  168. }
  169. }, this->iscapture);
  170. /* *INDENT-ON* */ /* clang-format on */
  171. #if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */
  172. SDL_free(this->hidden);
  173. #endif
  174. }
  175. EM_JS_DEPS(sdlaudio, "$autoResumeAudioContext,$dynCall");
  176. static int EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
  177. {
  178. SDL_AudioFormat test_format;
  179. SDL_bool iscapture = this->iscapture;
  180. int result;
  181. /* based on parts of library_sdl.js */
  182. /* *INDENT-OFF* */ /* clang-format off */
  183. /* create context */
  184. result = MAIN_THREAD_EM_ASM_INT({
  185. if(typeof(Module['SDL2']) === 'undefined') {
  186. Module['SDL2'] = {};
  187. }
  188. var SDL2 = Module['SDL2'];
  189. if (!$0) {
  190. SDL2.audio = {};
  191. } else {
  192. SDL2.capture = {};
  193. }
  194. if (!SDL2.audioContext) {
  195. if (typeof(AudioContext) !== 'undefined') {
  196. SDL2.audioContext = new AudioContext();
  197. } else if (typeof(webkitAudioContext) !== 'undefined') {
  198. SDL2.audioContext = new webkitAudioContext();
  199. }
  200. if (SDL2.audioContext) {
  201. autoResumeAudioContext(SDL2.audioContext);
  202. }
  203. }
  204. return SDL2.audioContext === undefined ? -1 : 0;
  205. }, iscapture);
  206. /* *INDENT-ON* */ /* clang-format on */
  207. if (result < 0) {
  208. return SDL_SetError("Web Audio API is not available!");
  209. }
  210. for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) {
  211. switch (test_format) {
  212. case AUDIO_F32: /* web audio only supports floats */
  213. break;
  214. default:
  215. continue;
  216. }
  217. break;
  218. }
  219. if (!test_format) {
  220. /* Didn't find a compatible format :( */
  221. return SDL_SetError("%s: Unsupported audio format", "emscripten");
  222. }
  223. this->spec.format = test_format;
  224. /* Initialize all variables that we clean on shutdown */
  225. #if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */
  226. this->hidden = (struct SDL_PrivateAudioData *)
  227. SDL_malloc(sizeof(*this->hidden));
  228. if (this->hidden == NULL) {
  229. return SDL_OutOfMemory();
  230. }
  231. SDL_zerop(this->hidden);
  232. #endif
  233. this->hidden = (struct SDL_PrivateAudioData *)0x1;
  234. /* limit to native freq */
  235. this->spec.freq = EM_ASM_INT({
  236. var SDL2 = Module['SDL2'];
  237. return SDL2.audioContext.sampleRate;
  238. });
  239. SDL_CalculateAudioSpec(&this->spec);
  240. /* *INDENT-OFF* */ /* clang-format off */
  241. if (iscapture) {
  242. /* The idea is to take the capture media stream, hook it up to an
  243. audio graph where we can pass it through a ScriptProcessorNode
  244. to access the raw PCM samples and push them to the SDL app's
  245. callback. From there, we "process" the audio data into silence
  246. and forget about it. */
  247. /* This should, strictly speaking, use MediaRecorder for capture, but
  248. this API is cleaner to use and better supported, and fires a
  249. callback whenever there's enough data to fire down into the app.
  250. The downside is that we are spending CPU time silencing a buffer
  251. that the audiocontext uselessly mixes into any output. On the
  252. upside, both of those things are not only run in native code in
  253. the browser, they're probably SIMD code, too. MediaRecorder
  254. feels like it's a pretty inefficient tapdance in similar ways,
  255. to be honest. */
  256. MAIN_THREAD_EM_ASM({
  257. var SDL2 = Module['SDL2'];
  258. var have_microphone = function(stream) {
  259. //console.log('SDL audio capture: we have a microphone! Replacing silence callback.');
  260. if (SDL2.capture.silenceTimer !== undefined) {
  261. clearTimeout(SDL2.capture.silenceTimer);
  262. SDL2.capture.silenceTimer = undefined;
  263. }
  264. SDL2.capture.mediaStreamNode = SDL2.audioContext.createMediaStreamSource(stream);
  265. SDL2.capture.scriptProcessorNode = SDL2.audioContext.createScriptProcessor($1, $0, 1);
  266. SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {
  267. if ((SDL2 === undefined) || (SDL2.capture === undefined)) { return; }
  268. audioProcessingEvent.outputBuffer.getChannelData(0).fill(0.0);
  269. SDL2.capture.currentCaptureBuffer = audioProcessingEvent.inputBuffer;
  270. dynCall('vi', $2, [$3]);
  271. };
  272. SDL2.capture.mediaStreamNode.connect(SDL2.capture.scriptProcessorNode);
  273. SDL2.capture.scriptProcessorNode.connect(SDL2.audioContext.destination);
  274. SDL2.capture.stream = stream;
  275. };
  276. var no_microphone = function(error) {
  277. //console.log('SDL audio capture: we DO NOT have a microphone! (' + error.name + ')...leaving silence callback running.');
  278. };
  279. /* we write silence to the audio callback until the microphone is available (user approves use, etc). */
  280. SDL2.capture.silenceBuffer = SDL2.audioContext.createBuffer($0, $1, SDL2.audioContext.sampleRate);
  281. SDL2.capture.silenceBuffer.getChannelData(0).fill(0.0);
  282. var silence_callback = function() {
  283. SDL2.capture.currentCaptureBuffer = SDL2.capture.silenceBuffer;
  284. dynCall('vi', $2, [$3]);
  285. };
  286. SDL2.capture.silenceTimer = setTimeout(silence_callback, ($1 / SDL2.audioContext.sampleRate) * 1000);
  287. if ((navigator.mediaDevices !== undefined) && (navigator.mediaDevices.getUserMedia !== undefined)) {
  288. navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(have_microphone).catch(no_microphone);
  289. } else if (navigator.webkitGetUserMedia !== undefined) {
  290. navigator.webkitGetUserMedia({ audio: true, video: false }, have_microphone, no_microphone);
  291. }
  292. }, this->spec.channels, this->spec.samples, HandleCaptureProcess, this);
  293. } else {
  294. /* setup a ScriptProcessorNode */
  295. MAIN_THREAD_EM_ASM({
  296. var SDL2 = Module['SDL2'];
  297. SDL2.audio.scriptProcessorNode = SDL2.audioContext['createScriptProcessor']($1, 0, $0);
  298. SDL2.audio.scriptProcessorNode['onaudioprocess'] = function (e) {
  299. if ((SDL2 === undefined) || (SDL2.audio === undefined)) { return; }
  300. SDL2.audio.currentOutputBuffer = e['outputBuffer'];
  301. dynCall('vi', $2, [$3]);
  302. };
  303. SDL2.audio.scriptProcessorNode['connect'](SDL2.audioContext['destination']);
  304. }, this->spec.channels, this->spec.samples, HandleAudioProcess, this);
  305. }
  306. /* *INDENT-ON* */ /* clang-format on */
  307. return 0;
  308. }
  309. static void EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock(SDL_AudioDevice *device)
  310. {
  311. }
  312. static SDL_bool EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl *impl)
  313. {
  314. SDL_bool available, capture_available;
  315. /* Set the function pointers */
  316. impl->OpenDevice = EMSCRIPTENAUDIO_OpenDevice;
  317. impl->CloseDevice = EMSCRIPTENAUDIO_CloseDevice;
  318. impl->OnlyHasDefaultOutputDevice = SDL_TRUE;
  319. /* no threads here */
  320. impl->LockDevice = impl->UnlockDevice = EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock;
  321. impl->ProvidesOwnCallbackThread = SDL_TRUE;
  322. /* *INDENT-OFF* */ /* clang-format off */
  323. /* check availability */
  324. available = MAIN_THREAD_EM_ASM_INT({
  325. if (typeof(AudioContext) !== 'undefined') {
  326. return true;
  327. } else if (typeof(webkitAudioContext) !== 'undefined') {
  328. return true;
  329. }
  330. return false;
  331. });
  332. /* *INDENT-ON* */ /* clang-format on */
  333. if (!available) {
  334. SDL_SetError("No audio context available");
  335. }
  336. /* *INDENT-OFF* */ /* clang-format off */
  337. capture_available = available && MAIN_THREAD_EM_ASM_INT({
  338. if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) {
  339. return true;
  340. } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') {
  341. return true;
  342. }
  343. return false;
  344. });
  345. /* *INDENT-ON* */ /* clang-format on */
  346. impl->HasCaptureSupport = capture_available ? SDL_TRUE : SDL_FALSE;
  347. impl->OnlyHasDefaultCaptureDevice = capture_available ? SDL_TRUE : SDL_FALSE;
  348. return available;
  349. }
  350. AudioBootStrap EMSCRIPTENAUDIO_bootstrap = {
  351. "emscripten", "SDL emscripten audio driver", EMSCRIPTENAUDIO_Init, SDL_FALSE
  352. };
  353. #endif /* SDL_AUDIO_DRIVER_EMSCRIPTEN */
  354. /* vi: set ts=4 sw=4 expandtab: */