library_godot_audio.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 ctx = new (window.AudioContext || window.webkitAudioContext)({
  39. sampleRate: mix_rate,
  40. // latencyHint: latency / 1000 // Do not specify, leave 'interactive' for good performance.
  41. });
  42. GodotAudio.ctx = ctx;
  43. ctx.onstatechange = function () {
  44. let state = 0;
  45. switch (ctx.state) {
  46. case 'suspended':
  47. state = 0;
  48. break;
  49. case 'running':
  50. state = 1;
  51. break;
  52. case 'closed':
  53. state = 2;
  54. break;
  55. // no default
  56. }
  57. onstatechange(state);
  58. };
  59. ctx.onstatechange(); // Immeditately notify state.
  60. // Update computed latency
  61. GodotAudio.interval = setInterval(function () {
  62. let computed_latency = 0;
  63. if (ctx.baseLatency) {
  64. computed_latency += GodotAudio.ctx.baseLatency;
  65. }
  66. if (ctx.outputLatency) {
  67. computed_latency += GodotAudio.ctx.outputLatency;
  68. }
  69. onlatencyupdate(computed_latency);
  70. }, 1000);
  71. GodotOS.atexit(GodotAudio.close_async);
  72. return ctx.destination.channelCount;
  73. },
  74. create_input: function (callback) {
  75. if (GodotAudio.input) {
  76. return 0; // Already started.
  77. }
  78. function gotMediaInput(stream) {
  79. try {
  80. GodotAudio.input = GodotAudio.ctx.createMediaStreamSource(stream);
  81. callback(GodotAudio.input);
  82. } catch (e) {
  83. GodotRuntime.error('Failed creaating input.', e);
  84. }
  85. }
  86. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  87. navigator.mediaDevices.getUserMedia({
  88. 'audio': true,
  89. }).then(gotMediaInput, function (e) {
  90. GodotRuntime.error('Error getting user media.', e);
  91. });
  92. } else {
  93. if (!navigator.getUserMedia) {
  94. navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  95. }
  96. if (!navigator.getUserMedia) {
  97. GodotRuntime.error('getUserMedia not available.');
  98. return 1;
  99. }
  100. navigator.getUserMedia({
  101. 'audio': true,
  102. }, gotMediaInput, function (e) {
  103. GodotRuntime.print(e);
  104. });
  105. }
  106. return 0;
  107. },
  108. close_async: function (resolve, reject) {
  109. const ctx = GodotAudio.ctx;
  110. GodotAudio.ctx = null;
  111. // Audio was not initialized.
  112. if (!ctx) {
  113. resolve();
  114. return;
  115. }
  116. // Remove latency callback
  117. if (GodotAudio.interval) {
  118. clearInterval(GodotAudio.interval);
  119. GodotAudio.interval = 0;
  120. }
  121. // Disconnect input, if it was started.
  122. if (GodotAudio.input) {
  123. GodotAudio.input.disconnect();
  124. GodotAudio.input = null;
  125. }
  126. // Disconnect output
  127. let closed = Promise.resolve();
  128. if (GodotAudio.driver) {
  129. closed = GodotAudio.driver.close();
  130. }
  131. closed.then(function () {
  132. return ctx.close();
  133. }).then(function () {
  134. ctx.onstatechange = null;
  135. resolve();
  136. }).catch(function (e) {
  137. ctx.onstatechange = null;
  138. GodotRuntime.error('Error closing AudioContext', e);
  139. resolve();
  140. });
  141. },
  142. },
  143. godot_audio_is_available__sig: 'i',
  144. godot_audio_is_available__proxy: 'sync',
  145. godot_audio_is_available: function () {
  146. if (!(window.AudioContext || window.webkitAudioContext)) {
  147. return 0;
  148. }
  149. return 1;
  150. },
  151. godot_audio_init__sig: 'iiiii',
  152. godot_audio_init: function (p_mix_rate, p_latency, p_state_change, p_latency_update) {
  153. const statechange = GodotRuntime.get_func(p_state_change);
  154. const latencyupdate = GodotRuntime.get_func(p_latency_update);
  155. return GodotAudio.init(p_mix_rate, p_latency, statechange, latencyupdate);
  156. },
  157. godot_audio_resume__sig: 'v',
  158. godot_audio_resume: function () {
  159. if (GodotAudio.ctx && GodotAudio.ctx.state !== 'running') {
  160. GodotAudio.ctx.resume();
  161. }
  162. },
  163. godot_audio_capture_start__proxy: 'sync',
  164. godot_audio_capture_start__sig: 'i',
  165. godot_audio_capture_start: function () {
  166. return GodotAudio.create_input(function (input) {
  167. input.connect(GodotAudio.driver.get_node());
  168. });
  169. },
  170. godot_audio_capture_stop__proxy: 'sync',
  171. godot_audio_capture_stop__sig: 'v',
  172. godot_audio_capture_stop: function () {
  173. if (GodotAudio.input) {
  174. const tracks = GodotAudio.input['mediaStream']['getTracks']();
  175. for (let i = 0; i < tracks.length; i++) {
  176. tracks[i]['stop']();
  177. }
  178. GodotAudio.input.disconnect();
  179. GodotAudio.input = null;
  180. }
  181. },
  182. };
  183. autoAddDeps(GodotAudio, '$GodotAudio');
  184. mergeInto(LibraryManager.library, GodotAudio);
  185. /**
  186. * The AudioWorklet API driver, used when threads are available.
  187. */
  188. const GodotAudioWorklet = {
  189. $GodotAudioWorklet__deps: ['$GodotAudio', '$GodotConfig'],
  190. $GodotAudioWorklet: {
  191. promise: null,
  192. worklet: null,
  193. create: function (channels) {
  194. const path = GodotConfig.locate_file('godot.audio.worklet.js');
  195. GodotAudioWorklet.promise = GodotAudio.ctx.audioWorklet.addModule(path).then(function () {
  196. GodotAudioWorklet.worklet = new AudioWorkletNode(
  197. GodotAudio.ctx,
  198. 'godot-processor',
  199. {
  200. 'outputChannelCount': [channels],
  201. },
  202. );
  203. return Promise.resolve();
  204. });
  205. GodotAudio.driver = GodotAudioWorklet;
  206. },
  207. start: function (in_buf, out_buf, state) {
  208. GodotAudioWorklet.promise.then(function () {
  209. const node = GodotAudioWorklet.worklet;
  210. node.connect(GodotAudio.ctx.destination);
  211. node.port.postMessage({
  212. 'cmd': 'start',
  213. 'data': [state, in_buf, out_buf],
  214. });
  215. node.port.onmessage = function (event) {
  216. GodotRuntime.error(event.data);
  217. };
  218. });
  219. },
  220. get_node: function () {
  221. return GodotAudioWorklet.worklet;
  222. },
  223. close: function () {
  224. return new Promise(function (resolve, reject) {
  225. GodotAudioWorklet.promise.then(function () {
  226. GodotAudioWorklet.worklet.port.postMessage({
  227. 'cmd': 'stop',
  228. 'data': null,
  229. });
  230. GodotAudioWorklet.worklet.disconnect();
  231. GodotAudioWorklet.worklet = null;
  232. GodotAudioWorklet.promise = null;
  233. resolve();
  234. });
  235. });
  236. },
  237. },
  238. godot_audio_worklet_create__sig: 'vi',
  239. godot_audio_worklet_create: function (channels) {
  240. GodotAudioWorklet.create(channels);
  241. },
  242. godot_audio_worklet_start__sig: 'viiiii',
  243. godot_audio_worklet_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_state) {
  244. const out_buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  245. const in_buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  246. const state = GodotRuntime.heapSub(HEAP32, p_state, 4);
  247. GodotAudioWorklet.start(in_buffer, out_buffer, state);
  248. },
  249. godot_audio_worklet_state_wait__sig: 'iiii',
  250. godot_audio_worklet_state_wait: function (p_state, p_idx, p_expected, p_timeout) {
  251. Atomics.wait(HEAP32, (p_state >> 2) + p_idx, p_expected, p_timeout);
  252. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  253. },
  254. godot_audio_worklet_state_add__sig: 'iiii',
  255. godot_audio_worklet_state_add: function (p_state, p_idx, p_value) {
  256. return Atomics.add(HEAP32, (p_state >> 2) + p_idx, p_value);
  257. },
  258. godot_audio_worklet_state_get__sig: 'iii',
  259. godot_audio_worklet_state_get: function (p_state, p_idx) {
  260. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  261. },
  262. };
  263. autoAddDeps(GodotAudioWorklet, '$GodotAudioWorklet');
  264. mergeInto(LibraryManager.library, GodotAudioWorklet);
  265. /*
  266. * The deprecated ScriptProcessorNode API, used when threads are disabled.
  267. */
  268. const GodotAudioScript = {
  269. $GodotAudioScript__deps: ['$GodotAudio'],
  270. $GodotAudioScript: {
  271. script: null,
  272. create: function (buffer_length, channel_count) {
  273. GodotAudioScript.script = GodotAudio.ctx.createScriptProcessor(buffer_length, 2, channel_count);
  274. GodotAudio.driver = GodotAudioScript;
  275. return GodotAudioScript.script.bufferSize;
  276. },
  277. start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess) {
  278. GodotAudioScript.script.onaudioprocess = function (event) {
  279. // Read input
  280. const inb = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  281. const input = event.inputBuffer;
  282. if (GodotAudio.input) {
  283. const inlen = input.getChannelData(0).length;
  284. for (let ch = 0; ch < 2; ch++) {
  285. const data = input.getChannelData(ch);
  286. for (let s = 0; s < inlen; s++) {
  287. inb[s * 2 + ch] = data[s];
  288. }
  289. }
  290. }
  291. // Let Godot process the input/output.
  292. onprocess();
  293. // Write the output.
  294. const outb = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  295. const output = event.outputBuffer;
  296. const channels = output.numberOfChannels;
  297. for (let ch = 0; ch < channels; ch++) {
  298. const data = output.getChannelData(ch);
  299. // Loop through samples and assign computed values.
  300. for (let sample = 0; sample < data.length; sample++) {
  301. data[sample] = outb[sample * channels + ch];
  302. }
  303. }
  304. };
  305. GodotAudioScript.script.connect(GodotAudio.ctx.destination);
  306. },
  307. get_node: function () {
  308. return GodotAudioScript.script;
  309. },
  310. close: function () {
  311. return new Promise(function (resolve, reject) {
  312. GodotAudioScript.script.disconnect();
  313. GodotAudioScript.script.onaudioprocess = null;
  314. GodotAudioScript.script = null;
  315. resolve();
  316. });
  317. },
  318. },
  319. godot_audio_script_create__sig: 'iii',
  320. godot_audio_script_create: function (buffer_length, channel_count) {
  321. return GodotAudioScript.create(buffer_length, channel_count);
  322. },
  323. godot_audio_script_start__sig: 'viiiii',
  324. godot_audio_script_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_cb) {
  325. const onprocess = GodotRuntime.get_func(p_cb);
  326. GodotAudioScript.start(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess);
  327. },
  328. };
  329. autoAddDeps(GodotAudioScript, '$GodotAudioScript');
  330. mergeInto(LibraryManager.library, GodotAudioScript);