SDL_emscriptenaudio.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 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. #ifdef SDL_AUDIO_DRIVER_EMSCRIPTEN
  20. #include "../SDL_sysaudio.h"
  21. #include "SDL_emscriptenaudio.h"
  22. #include <emscripten/emscripten.h>
  23. // just turn off clang-format for this whole file, this INDENT_OFF stuff on
  24. // each EM_ASM section is ugly.
  25. /* *INDENT-OFF* */ /* clang-format off */
  26. static Uint8 *EMSCRIPTENAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
  27. {
  28. return device->hidden->mixbuf;
  29. }
  30. static int EMSCRIPTENAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
  31. {
  32. const int framelen = SDL_AUDIO_FRAMESIZE(device->spec);
  33. MAIN_THREAD_EM_ASM({
  34. var SDL3 = Module['SDL3'];
  35. var numChannels = SDL3.audio_playback.currentPlaybackBuffer['numberOfChannels'];
  36. for (var c = 0; c < numChannels; ++c) {
  37. var channelData = SDL3.audio_playback.currentPlaybackBuffer['getChannelData'](c);
  38. if (channelData.length != $1) {
  39. throw 'Web Audio playback buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
  40. }
  41. for (var j = 0; j < $1; ++j) {
  42. channelData[j] = HEAPF32[$0 + ((j*numChannels + c) << 2) >> 2]; // !!! FIXME: why are these shifts here?
  43. }
  44. }
  45. }, buffer, buffer_size / framelen);
  46. return 0;
  47. }
  48. static void EMSCRIPTENAUDIO_FlushRecording(SDL_AudioDevice *device)
  49. {
  50. // Do nothing, the new data will just be dropped.
  51. }
  52. static int EMSCRIPTENAUDIO_RecordDevice(SDL_AudioDevice *device, void *buffer, int buflen)
  53. {
  54. MAIN_THREAD_EM_ASM({
  55. var SDL3 = Module['SDL3'];
  56. var numChannels = SDL3.audio_recording.currentRecordingBuffer.numberOfChannels;
  57. for (var c = 0; c < numChannels; ++c) {
  58. var channelData = SDL3.audio_recording.currentRecordingBuffer.getChannelData(c);
  59. if (channelData.length != $1) {
  60. throw 'Web Audio recording buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
  61. }
  62. if (numChannels == 1) { // fastpath this a little for the common (mono) case.
  63. for (var j = 0; j < $1; ++j) {
  64. setValue($0 + (j * 4), channelData[j], 'float');
  65. }
  66. } else {
  67. for (var j = 0; j < $1; ++j) {
  68. setValue($0 + (((j * numChannels) + c) * 4), channelData[j], 'float');
  69. }
  70. }
  71. }
  72. }, buffer, (buflen / sizeof(float)) / device->spec.channels);
  73. return buflen;
  74. }
  75. static void EMSCRIPTENAUDIO_CloseDevice(SDL_AudioDevice *device)
  76. {
  77. if (!device->hidden) {
  78. return;
  79. }
  80. MAIN_THREAD_EM_ASM({
  81. var SDL3 = Module['SDL3'];
  82. if ($0) {
  83. if (SDL3.audio_recording.silenceTimer !== undefined) {
  84. clearInterval(SDL3.audio_recording.silenceTimer);
  85. }
  86. if (SDL3.audio_recording.stream !== undefined) {
  87. var tracks = SDL3.audio_recording.stream.getAudioTracks();
  88. for (var i = 0; i < tracks.length; i++) {
  89. SDL3.audio_recording.stream.removeTrack(tracks[i]);
  90. }
  91. }
  92. if (SDL3.audio_recording.scriptProcessorNode !== undefined) {
  93. SDL3.audio_recording.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {};
  94. SDL3.audio_recording.scriptProcessorNode.disconnect();
  95. }
  96. if (SDL3.audio_recording.mediaStreamNode !== undefined) {
  97. SDL3.audio_recording.mediaStreamNode.disconnect();
  98. }
  99. SDL3.audio_recording = undefined;
  100. } else {
  101. if (SDL3.audio_playback.scriptProcessorNode != undefined) {
  102. SDL3.audio_playback.scriptProcessorNode.disconnect();
  103. }
  104. if (SDL3.audio_playback.silenceTimer !== undefined) {
  105. clearInterval(SDL3.audio_playback.silenceTimer);
  106. }
  107. SDL3.audio_playback = undefined;
  108. }
  109. if ((SDL3.audioContext !== undefined) && (SDL3.audio_playback === undefined) && (SDL3.audio_recording === undefined)) {
  110. SDL3.audioContext.close();
  111. SDL3.audioContext = undefined;
  112. }
  113. }, device->recording);
  114. SDL_free(device->hidden->mixbuf);
  115. SDL_free(device->hidden);
  116. device->hidden = NULL;
  117. SDL_AudioThreadFinalize(device);
  118. }
  119. EM_JS_DEPS(sdlaudio, "$autoResumeAudioContext,$dynCall");
  120. static int EMSCRIPTENAUDIO_OpenDevice(SDL_AudioDevice *device)
  121. {
  122. // based on parts of library_sdl.js
  123. // create context
  124. const int result = MAIN_THREAD_EM_ASM_INT({
  125. if (typeof(Module['SDL3']) === 'undefined') {
  126. Module['SDL3'] = {};
  127. }
  128. var SDL3 = Module['SDL3'];
  129. if (!$0) {
  130. SDL3.audio_playback = {};
  131. } else {
  132. SDL3.audio_recording = {};
  133. }
  134. if (!SDL3.audioContext) {
  135. if (typeof(AudioContext) !== 'undefined') {
  136. SDL3.audioContext = new AudioContext();
  137. } else if (typeof(webkitAudioContext) !== 'undefined') {
  138. SDL3.audioContext = new webkitAudioContext();
  139. }
  140. if (SDL3.audioContext) {
  141. if ((typeof navigator.userActivation) === 'undefined') { // Firefox doesn't have this (as of August 2023), use autoResumeAudioContext instead.
  142. autoResumeAudioContext(SDL3.audioContext);
  143. }
  144. }
  145. }
  146. return SDL3.audioContext === undefined ? -1 : 0;
  147. }, device->recording);
  148. if (result < 0) {
  149. return SDL_SetError("Web Audio API is not available!");
  150. }
  151. device->spec.format = SDL_AUDIO_F32; // web audio only supports floats
  152. // Initialize all variables that we clean on shutdown
  153. device->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*device->hidden));
  154. if (!device->hidden) {
  155. return -1;
  156. }
  157. // limit to native freq
  158. device->spec.freq = EM_ASM_INT({ return Module['SDL3'].audioContext.sampleRate; });
  159. SDL_UpdatedAudioDeviceFormat(device);
  160. if (!device->recording) {
  161. device->hidden->mixbuf = (Uint8 *)SDL_malloc(device->buffer_size);
  162. if (!device->hidden->mixbuf) {
  163. return -1;
  164. }
  165. SDL_memset(device->hidden->mixbuf, device->silence_value, device->buffer_size);
  166. }
  167. if (device->recording) {
  168. /* The idea is to take the recording media stream, hook it up to an
  169. audio graph where we can pass it through a ScriptProcessorNode
  170. to access the raw PCM samples and push them to the SDL app's
  171. callback. From there, we "process" the audio data into silence
  172. and forget about it.
  173. This should, strictly speaking, use MediaRecorder for recording, but
  174. this API is cleaner to use and better supported, and fires a
  175. callback whenever there's enough data to fire down into the app.
  176. The downside is that we are spending CPU time silencing a buffer
  177. that the audiocontext uselessly mixes into any playback. On the
  178. upside, both of those things are not only run in native code in
  179. the browser, they're probably SIMD code, too. MediaRecorder
  180. feels like it's a pretty inefficient tapdance in similar ways,
  181. to be honest. */
  182. MAIN_THREAD_EM_ASM({
  183. var SDL3 = Module['SDL3'];
  184. var have_microphone = function(stream) {
  185. //console.log('SDL audio recording: we have a microphone! Replacing silence callback.');
  186. if (SDL3.audio_recording.silenceTimer !== undefined) {
  187. clearInterval(SDL3.audio_recording.silenceTimer);
  188. SDL3.audio_recording.silenceTimer = undefined;
  189. SDL3.audio_recording.silenceBuffer = undefined
  190. }
  191. SDL3.audio_recording.mediaStreamNode = SDL3.audioContext.createMediaStreamSource(stream);
  192. SDL3.audio_recording.scriptProcessorNode = SDL3.audioContext.createScriptProcessor($1, $0, 1);
  193. SDL3.audio_recording.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {
  194. if ((SDL3 === undefined) || (SDL3.audio_recording === undefined)) { return; }
  195. audioProcessingEvent.outputBuffer.getChannelData(0).fill(0.0);
  196. SDL3.audio_recording.currentRecordingBuffer = audioProcessingEvent.inputBuffer;
  197. dynCall('vi', $2, [$3]);
  198. };
  199. SDL3.audio_recording.mediaStreamNode.connect(SDL3.audio_recording.scriptProcessorNode);
  200. SDL3.audio_recording.scriptProcessorNode.connect(SDL3.audioContext.destination);
  201. SDL3.audio_recording.stream = stream;
  202. };
  203. var no_microphone = function(error) {
  204. //console.log('SDL audio recording: we DO NOT have a microphone! (' + error.name + ')...leaving silence callback running.');
  205. };
  206. // we write silence to the audio callback until the microphone is available (user approves use, etc).
  207. SDL3.audio_recording.silenceBuffer = SDL3.audioContext.createBuffer($0, $1, SDL3.audioContext.sampleRate);
  208. SDL3.audio_recording.silenceBuffer.getChannelData(0).fill(0.0);
  209. var silence_callback = function() {
  210. SDL3.audio_recording.currentRecordingBuffer = SDL3.audio_recording.silenceBuffer;
  211. dynCall('vi', $2, [$3]);
  212. };
  213. SDL3.audio_recording.silenceTimer = setInterval(silence_callback, ($1 / SDL3.audioContext.sampleRate) * 1000);
  214. if ((navigator.mediaDevices !== undefined) && (navigator.mediaDevices.getUserMedia !== undefined)) {
  215. navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(have_microphone).catch(no_microphone);
  216. } else if (navigator.webkitGetUserMedia !== undefined) {
  217. navigator.webkitGetUserMedia({ audio: true, video: false }, have_microphone, no_microphone);
  218. }
  219. }, device->spec.channels, device->sample_frames, SDL_RecordingAudioThreadIterate, device);
  220. } else {
  221. // setup a ScriptProcessorNode
  222. MAIN_THREAD_EM_ASM({
  223. var SDL3 = Module['SDL3'];
  224. SDL3.audio_playback.scriptProcessorNode = SDL3.audioContext['createScriptProcessor']($1, 0, $0);
  225. SDL3.audio_playback.scriptProcessorNode['onaudioprocess'] = function (e) {
  226. if ((SDL3 === undefined) || (SDL3.audio_playback === undefined)) { return; }
  227. // if we're actually running the node, we don't need the fake callback anymore, so kill it.
  228. if (SDL3.audio_playback.silenceTimer !== undefined) {
  229. clearInterval(SDL3.audio_playback.silenceTimer);
  230. SDL3.audio_playback.silenceTimer = undefined;
  231. SDL3.audio_playback.silenceBuffer = undefined;
  232. }
  233. SDL3.audio_playback.currentPlaybackBuffer = e['outputBuffer'];
  234. dynCall('vi', $2, [$3]);
  235. };
  236. SDL3.audio_playback.scriptProcessorNode['connect'](SDL3.audioContext['destination']);
  237. if (SDL3.audioContext.state === 'suspended') { // uhoh, autoplay is blocked.
  238. SDL3.audio_playback.silenceBuffer = SDL3.audioContext.createBuffer($0, $1, SDL3.audioContext.sampleRate);
  239. SDL3.audio_playback.silenceBuffer.getChannelData(0).fill(0.0);
  240. var silence_callback = function() {
  241. if ((typeof navigator.userActivation) !== 'undefined') { // Almost everything modern except Firefox (as of August 2023)
  242. if (navigator.userActivation.hasBeenActive) {
  243. SDL3.audioContext.resume();
  244. }
  245. }
  246. // the buffer that gets filled here just gets ignored, so the app can make progress
  247. // and/or avoid flooding audio queues until we can actually play audio.
  248. SDL3.audio_playback.currentPlaybackBuffer = SDL3.audio_playback.silenceBuffer;
  249. dynCall('vi', $2, [$3]);
  250. SDL3.audio_playback.currentPlaybackBuffer = undefined;
  251. };
  252. SDL3.audio_playback.silenceTimer = setInterval(silence_callback, ($1 / SDL3.audioContext.sampleRate) * 1000);
  253. }
  254. }, device->spec.channels, device->sample_frames, SDL_PlaybackAudioThreadIterate, device);
  255. }
  256. return 0;
  257. }
  258. static SDL_bool EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl *impl)
  259. {
  260. SDL_bool available, recording_available;
  261. impl->OpenDevice = EMSCRIPTENAUDIO_OpenDevice;
  262. impl->CloseDevice = EMSCRIPTENAUDIO_CloseDevice;
  263. impl->GetDeviceBuf = EMSCRIPTENAUDIO_GetDeviceBuf;
  264. impl->PlayDevice = EMSCRIPTENAUDIO_PlayDevice;
  265. impl->FlushRecording = EMSCRIPTENAUDIO_FlushRecording;
  266. impl->RecordDevice = EMSCRIPTENAUDIO_RecordDevice;
  267. impl->OnlyHasDefaultPlaybackDevice = SDL_TRUE;
  268. // technically, this is just runs in idle time in the main thread, but it's close enough to a "thread" for our purposes.
  269. impl->ProvidesOwnCallbackThread = SDL_TRUE;
  270. // check availability
  271. available = MAIN_THREAD_EM_ASM_INT({
  272. if (typeof(AudioContext) !== 'undefined') {
  273. return true;
  274. } else if (typeof(webkitAudioContext) !== 'undefined') {
  275. return true;
  276. }
  277. return false;
  278. });
  279. if (!available) {
  280. SDL_SetError("No audio context available");
  281. }
  282. recording_available = available && MAIN_THREAD_EM_ASM_INT({
  283. if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) {
  284. return true;
  285. } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') {
  286. return true;
  287. }
  288. return false;
  289. });
  290. impl->HasRecordingSupport = recording_available;
  291. impl->OnlyHasDefaultRecordingDevice = recording_available;
  292. return available;
  293. }
  294. AudioBootStrap EMSCRIPTENAUDIO_bootstrap = {
  295. "emscripten", "SDL emscripten audio driver", EMSCRIPTENAUDIO_Init, SDL_FALSE
  296. };
  297. /* *INDENT-ON* */ /* clang-format on */
  298. #endif // SDL_AUDIO_DRIVER_EMSCRIPTEN