library_godot_audio.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*************************************************************************/
  2. /* library_godot_audio.js */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. const GodotAudio = {
  31. $GodotAudio__deps: ['$GodotRuntime', '$GodotOS'],
  32. $GodotAudio: {
  33. ctx: null,
  34. input: null,
  35. driver: null,
  36. interval: 0,
  37. init: function (mix_rate, latency, onstatechange, onlatencyupdate) {
  38. const opts = {};
  39. // If mix_rate is 0, let the browser choose.
  40. if (mix_rate) {
  41. opts['sampleRate'] = mix_rate;
  42. }
  43. // Do not specify, leave 'interactive' for good performance.
  44. // opts['latencyHint'] = latency / 1000;
  45. const ctx = new (window.AudioContext || window.webkitAudioContext)(opts);
  46. GodotAudio.ctx = ctx;
  47. ctx.onstatechange = function () {
  48. let state = 0;
  49. switch (ctx.state) {
  50. case 'suspended':
  51. state = 0;
  52. break;
  53. case 'running':
  54. state = 1;
  55. break;
  56. case 'closed':
  57. state = 2;
  58. break;
  59. // no default
  60. }
  61. onstatechange(state);
  62. };
  63. ctx.onstatechange(); // Immediately notify state.
  64. // Update computed latency
  65. GodotAudio.interval = setInterval(function () {
  66. let computed_latency = 0;
  67. if (ctx.baseLatency) {
  68. computed_latency += GodotAudio.ctx.baseLatency;
  69. }
  70. if (ctx.outputLatency) {
  71. computed_latency += GodotAudio.ctx.outputLatency;
  72. }
  73. onlatencyupdate(computed_latency);
  74. }, 1000);
  75. GodotOS.atexit(GodotAudio.close_async);
  76. return ctx.destination.channelCount;
  77. },
  78. create_input: function (callback) {
  79. if (GodotAudio.input) {
  80. return 0; // Already started.
  81. }
  82. function gotMediaInput(stream) {
  83. try {
  84. GodotAudio.input = GodotAudio.ctx.createMediaStreamSource(stream);
  85. callback(GodotAudio.input);
  86. } catch (e) {
  87. GodotRuntime.error('Failed creaating input.', e);
  88. }
  89. }
  90. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  91. navigator.mediaDevices.getUserMedia({
  92. 'audio': true,
  93. }).then(gotMediaInput, function (e) {
  94. GodotRuntime.error('Error getting user media.', e);
  95. });
  96. } else {
  97. if (!navigator.getUserMedia) {
  98. navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  99. }
  100. if (!navigator.getUserMedia) {
  101. GodotRuntime.error('getUserMedia not available.');
  102. return 1;
  103. }
  104. navigator.getUserMedia({
  105. 'audio': true,
  106. }, gotMediaInput, function (e) {
  107. GodotRuntime.print(e);
  108. });
  109. }
  110. return 0;
  111. },
  112. close_async: function (resolve, reject) {
  113. const ctx = GodotAudio.ctx;
  114. GodotAudio.ctx = null;
  115. // Audio was not initialized.
  116. if (!ctx) {
  117. resolve();
  118. return;
  119. }
  120. // Remove latency callback
  121. if (GodotAudio.interval) {
  122. clearInterval(GodotAudio.interval);
  123. GodotAudio.interval = 0;
  124. }
  125. // Disconnect input, if it was started.
  126. if (GodotAudio.input) {
  127. GodotAudio.input.disconnect();
  128. GodotAudio.input = null;
  129. }
  130. // Disconnect output
  131. let closed = Promise.resolve();
  132. if (GodotAudio.driver) {
  133. closed = GodotAudio.driver.close();
  134. }
  135. closed.then(function () {
  136. return ctx.close();
  137. }).then(function () {
  138. ctx.onstatechange = null;
  139. resolve();
  140. }).catch(function (e) {
  141. ctx.onstatechange = null;
  142. GodotRuntime.error('Error closing AudioContext', e);
  143. resolve();
  144. });
  145. },
  146. },
  147. godot_audio_is_available__sig: 'i',
  148. godot_audio_is_available__proxy: 'sync',
  149. godot_audio_is_available: function () {
  150. if (!(window.AudioContext || window.webkitAudioContext)) {
  151. return 0;
  152. }
  153. return 1;
  154. },
  155. godot_audio_init__sig: 'iiiii',
  156. godot_audio_init: function (p_mix_rate, p_latency, p_state_change, p_latency_update) {
  157. const statechange = GodotRuntime.get_func(p_state_change);
  158. const latencyupdate = GodotRuntime.get_func(p_latency_update);
  159. const mix_rate = GodotRuntime.getHeapValue(p_mix_rate, 'i32');
  160. const channels = GodotAudio.init(mix_rate, p_latency, statechange, latencyupdate);
  161. GodotRuntime.setHeapValue(p_mix_rate, GodotAudio.ctx.sampleRate, 'i32');
  162. return channels;
  163. },
  164. godot_audio_resume__sig: 'v',
  165. godot_audio_resume: function () {
  166. if (GodotAudio.ctx && GodotAudio.ctx.state !== 'running') {
  167. GodotAudio.ctx.resume();
  168. }
  169. },
  170. godot_audio_capture_start__proxy: 'sync',
  171. godot_audio_capture_start__sig: 'i',
  172. godot_audio_capture_start: function () {
  173. return GodotAudio.create_input(function (input) {
  174. input.connect(GodotAudio.driver.get_node());
  175. });
  176. },
  177. godot_audio_capture_stop__proxy: 'sync',
  178. godot_audio_capture_stop__sig: 'v',
  179. godot_audio_capture_stop: function () {
  180. if (GodotAudio.input) {
  181. const tracks = GodotAudio.input['mediaStream']['getTracks']();
  182. for (let i = 0; i < tracks.length; i++) {
  183. tracks[i]['stop']();
  184. }
  185. GodotAudio.input.disconnect();
  186. GodotAudio.input = null;
  187. }
  188. },
  189. };
  190. autoAddDeps(GodotAudio, '$GodotAudio');
  191. mergeInto(LibraryManager.library, GodotAudio);
  192. /**
  193. * The AudioWorklet API driver, used when threads are available.
  194. */
  195. const GodotAudioWorklet = {
  196. $GodotAudioWorklet__deps: ['$GodotAudio', '$GodotConfig'],
  197. $GodotAudioWorklet: {
  198. promise: null,
  199. worklet: null,
  200. create: function (channels) {
  201. const path = GodotConfig.locate_file('godot.audio.worklet.js');
  202. GodotAudioWorklet.promise = GodotAudio.ctx.audioWorklet.addModule(path).then(function () {
  203. GodotAudioWorklet.worklet = new AudioWorkletNode(
  204. GodotAudio.ctx,
  205. 'godot-processor',
  206. {
  207. 'outputChannelCount': [channels],
  208. },
  209. );
  210. return Promise.resolve();
  211. });
  212. GodotAudio.driver = GodotAudioWorklet;
  213. },
  214. start: function (in_buf, out_buf, state) {
  215. GodotAudioWorklet.promise.then(function () {
  216. const node = GodotAudioWorklet.worklet;
  217. node.connect(GodotAudio.ctx.destination);
  218. node.port.postMessage({
  219. 'cmd': 'start',
  220. 'data': [state, in_buf, out_buf],
  221. });
  222. node.port.onmessage = function (event) {
  223. GodotRuntime.error(event.data);
  224. };
  225. });
  226. },
  227. get_node: function () {
  228. return GodotAudioWorklet.worklet;
  229. },
  230. close: function () {
  231. return new Promise(function (resolve, reject) {
  232. if (GodotAudioWorklet.promise === null) {
  233. return;
  234. }
  235. GodotAudioWorklet.promise.then(function () {
  236. GodotAudioWorklet.worklet.port.postMessage({
  237. 'cmd': 'stop',
  238. 'data': null,
  239. });
  240. GodotAudioWorklet.worklet.disconnect();
  241. GodotAudioWorklet.worklet = null;
  242. GodotAudioWorklet.promise = null;
  243. resolve();
  244. }).catch(function (err) { /* aborted? */ });
  245. });
  246. },
  247. },
  248. godot_audio_worklet_create__sig: 'vi',
  249. godot_audio_worklet_create: function (channels) {
  250. GodotAudioWorklet.create(channels);
  251. },
  252. godot_audio_worklet_start__sig: 'viiiii',
  253. godot_audio_worklet_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_state) {
  254. const out_buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  255. const in_buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  256. const state = GodotRuntime.heapSub(HEAP32, p_state, 4);
  257. GodotAudioWorklet.start(in_buffer, out_buffer, state);
  258. },
  259. godot_audio_worklet_state_wait__sig: 'iiii',
  260. godot_audio_worklet_state_wait: function (p_state, p_idx, p_expected, p_timeout) {
  261. Atomics.wait(HEAP32, (p_state >> 2) + p_idx, p_expected, p_timeout);
  262. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  263. },
  264. godot_audio_worklet_state_add__sig: 'iiii',
  265. godot_audio_worklet_state_add: function (p_state, p_idx, p_value) {
  266. return Atomics.add(HEAP32, (p_state >> 2) + p_idx, p_value);
  267. },
  268. godot_audio_worklet_state_get__sig: 'iii',
  269. godot_audio_worklet_state_get: function (p_state, p_idx) {
  270. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  271. },
  272. };
  273. autoAddDeps(GodotAudioWorklet, '$GodotAudioWorklet');
  274. mergeInto(LibraryManager.library, GodotAudioWorklet);
  275. /*
  276. * The deprecated ScriptProcessorNode API, used when threads are disabled.
  277. */
  278. const GodotAudioScript = {
  279. $GodotAudioScript__deps: ['$GodotAudio'],
  280. $GodotAudioScript: {
  281. script: null,
  282. create: function (buffer_length, channel_count) {
  283. GodotAudioScript.script = GodotAudio.ctx.createScriptProcessor(buffer_length, 2, channel_count);
  284. GodotAudio.driver = GodotAudioScript;
  285. return GodotAudioScript.script.bufferSize;
  286. },
  287. start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess) {
  288. GodotAudioScript.script.onaudioprocess = function (event) {
  289. // Read input
  290. const inb = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  291. const input = event.inputBuffer;
  292. if (GodotAudio.input) {
  293. const inlen = input.getChannelData(0).length;
  294. for (let ch = 0; ch < 2; ch++) {
  295. const data = input.getChannelData(ch);
  296. for (let s = 0; s < inlen; s++) {
  297. inb[s * 2 + ch] = data[s];
  298. }
  299. }
  300. }
  301. // Let Godot process the input/output.
  302. onprocess();
  303. // Write the output.
  304. const outb = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  305. const output = event.outputBuffer;
  306. const channels = output.numberOfChannels;
  307. for (let ch = 0; ch < channels; ch++) {
  308. const data = output.getChannelData(ch);
  309. // Loop through samples and assign computed values.
  310. for (let sample = 0; sample < data.length; sample++) {
  311. data[sample] = outb[sample * channels + ch];
  312. }
  313. }
  314. };
  315. GodotAudioScript.script.connect(GodotAudio.ctx.destination);
  316. },
  317. get_node: function () {
  318. return GodotAudioScript.script;
  319. },
  320. close: function () {
  321. return new Promise(function (resolve, reject) {
  322. GodotAudioScript.script.disconnect();
  323. GodotAudioScript.script.onaudioprocess = null;
  324. GodotAudioScript.script = null;
  325. resolve();
  326. });
  327. },
  328. },
  329. godot_audio_script_create__sig: 'iii',
  330. godot_audio_script_create: function (buffer_length, channel_count) {
  331. return GodotAudioScript.create(buffer_length, channel_count);
  332. },
  333. godot_audio_script_start__sig: 'viiiii',
  334. godot_audio_script_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_cb) {
  335. const onprocess = GodotRuntime.get_func(p_cb);
  336. GodotAudioScript.start(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess);
  337. },
  338. };
  339. autoAddDeps(GodotAudioScript, '$GodotAudioScript');
  340. mergeInto(LibraryManager.library, GodotAudioScript);