SDL_emscriptenaudio.c 16 KB

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