SDL_emscriptenaudio.c 15 KB

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