SDL_emscriptenaudio.c 15 KB

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