library_godot_audio.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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; // Already started.
  77. }
  78. function gotMediaInput(stream) {
  79. GodotAudio.input = GodotAudio.ctx.createMediaStreamSource(stream);
  80. callback(GodotAudio.input)
  81. }
  82. if (navigator.mediaDevices.getUserMedia) {
  83. navigator.mediaDevices.getUserMedia({
  84. "audio": true
  85. }).then(gotMediaInput, function(e) { GodotRuntime.print(e) });
  86. } else {
  87. if (!navigator.getUserMedia) {
  88. navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  89. }
  90. navigator.getUserMedia({
  91. "audio": true
  92. }, gotMediaInput, function(e) { GodotRuntime.print(e) });
  93. }
  94. },
  95. close_async: function(resolve, reject) {
  96. const ctx = GodotAudio.ctx;
  97. GodotAudio.ctx = null;
  98. // Audio was not initialized.
  99. if (!ctx) {
  100. resolve();
  101. return;
  102. }
  103. // Remove latency callback
  104. if (GodotAudio.interval) {
  105. clearInterval(GodotAudio.interval);
  106. GodotAudio.interval = 0;
  107. }
  108. // Disconnect input, if it was started.
  109. if (GodotAudio.input) {
  110. GodotAudio.input.disconnect();
  111. GodotAudio.input = null;
  112. }
  113. // Disconnect output
  114. let closed = Promise.resolve();
  115. if (GodotAudio.driver) {
  116. closed = GodotAudio.driver.close();
  117. }
  118. closed.then(function() {
  119. return ctx.close();
  120. }).then(function() {
  121. ctx.onstatechange = null;
  122. resolve();
  123. }).catch(function(e) {
  124. ctx.onstatechange = null;
  125. GodotRuntime.error("Error closing AudioContext", e);
  126. resolve();
  127. });
  128. },
  129. },
  130. godot_audio_is_available__proxy: 'sync',
  131. godot_audio_is_available: function () {
  132. if (!(window.AudioContext || window.webkitAudioContext)) {
  133. return 0;
  134. }
  135. return 1;
  136. },
  137. godot_audio_init: function(p_mix_rate, p_latency, p_state_change, p_latency_update) {
  138. const statechange = GodotRuntime.get_func(p_state_change);
  139. const latencyupdate = GodotRuntime.get_func(p_latency_update);
  140. return GodotAudio.init(p_mix_rate, p_latency, statechange, latencyupdate);
  141. },
  142. godot_audio_resume: function() {
  143. if (GodotAudio.ctx && GodotAudio.ctx.state !== 'running') {
  144. GodotAudio.ctx.resume();
  145. }
  146. },
  147. godot_audio_capture_start__proxy: 'sync',
  148. godot_audio_capture_start: function() {
  149. if (GodotAudio.input) {
  150. return; // Already started.
  151. }
  152. GodotAudio.create_input(function(input) {
  153. input.connect(GodotAudio.driver.get_node());
  154. });
  155. },
  156. godot_audio_capture_stop__proxy: 'sync',
  157. godot_audio_capture_stop: function() {
  158. if (GodotAudio.input) {
  159. const tracks = GodotAudio.input['mediaStream']['getTracks']();
  160. for (let i = 0; i < tracks.length; i++) {
  161. tracks[i]['stop']();
  162. }
  163. GodotAudio.input.disconnect();
  164. GodotAudio.input = null;
  165. }
  166. },
  167. };
  168. autoAddDeps(GodotAudio, "$GodotAudio");
  169. mergeInto(LibraryManager.library, GodotAudio);
  170. /**
  171. * The AudioWorklet API driver, used when threads are available.
  172. */
  173. const GodotAudioWorklet = {
  174. $GodotAudioWorklet__deps: ['$GodotAudio', '$GodotConfig'],
  175. $GodotAudioWorklet: {
  176. promise: null,
  177. worklet: null,
  178. create: function(channels) {
  179. const path = GodotConfig.locate_file('godot.audio.worklet.js');
  180. GodotAudioWorklet.promise = GodotAudio.ctx.audioWorklet.addModule(path).then(function() {
  181. GodotAudioWorklet.worklet = new AudioWorkletNode(
  182. GodotAudio.ctx,
  183. 'godot-processor',
  184. {
  185. 'outputChannelCount': [channels]
  186. }
  187. );
  188. return Promise.resolve();
  189. });
  190. GodotAudio.driver = GodotAudioWorklet;
  191. },
  192. start: function(in_buf, out_buf, state) {
  193. GodotAudioWorklet.promise.then(function() {
  194. const node = GodotAudioWorklet.worklet;
  195. node.connect(GodotAudio.ctx.destination);
  196. node.port.postMessage({
  197. 'cmd': 'start',
  198. 'data': [state, in_buf, out_buf],
  199. });
  200. node.port.onmessage = function(event) {
  201. GodotRuntime.error(event.data);
  202. };
  203. });
  204. },
  205. get_node: function() {
  206. return GodotAudioWorklet.worklet;
  207. },
  208. close: function() {
  209. return new Promise(function(resolve, reject) {
  210. GodotAudioWorklet.promise.then(function() {
  211. GodotAudioWorklet.worklet.port.postMessage({
  212. 'cmd': 'stop',
  213. 'data': null,
  214. });
  215. GodotAudioWorklet.worklet.disconnect();
  216. GodotAudioWorklet.worklet = null;
  217. GodotAudioWorklet.promise = null;
  218. resolve();
  219. });
  220. });
  221. },
  222. },
  223. godot_audio_worklet_create: function(channels) {
  224. GodotAudioWorklet.create(channels);
  225. },
  226. godot_audio_worklet_start: function(p_in_buf, p_in_size, p_out_buf, p_out_size, p_state) {
  227. const out_buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  228. const in_buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  229. const state = GodotRuntime.heapSub(HEAP32, p_state, 4);
  230. GodotAudioWorklet.start(in_buffer, out_buffer, state);
  231. },
  232. godot_audio_worklet_state_wait: function(p_state, p_idx, p_expected, p_timeout) {
  233. Atomics.wait(HEAP32, (p_state >> 2) + p_idx, p_expected, p_timeout);
  234. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  235. },
  236. godot_audio_worklet_state_add: function(p_state, p_idx, p_value) {
  237. return Atomics.add(HEAP32, (p_state >> 2) + p_idx, p_value);
  238. },
  239. godot_audio_worklet_state_get: function(p_state, p_idx) {
  240. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  241. },
  242. };
  243. autoAddDeps(GodotAudioWorklet, "$GodotAudioWorklet");
  244. mergeInto(LibraryManager.library, GodotAudioWorklet);
  245. /*
  246. * The deprecated ScriptProcessorNode API, used when threads are disabled.
  247. */
  248. const GodotAudioScript = {
  249. $GodotAudioScript__deps: ['$GodotAudio'],
  250. $GodotAudioScript: {
  251. script: null,
  252. create: function(buffer_length, channel_count) {
  253. GodotAudioScript.script = GodotAudio.ctx.createScriptProcessor(buffer_length, 2, channel_count);
  254. GodotAudio.driver = GodotAudioScript;
  255. return GodotAudioScript.script.bufferSize;
  256. },
  257. start: function(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess) {
  258. GodotAudioScript.script.onaudioprocess = function(event) {
  259. // Read input
  260. const inb = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  261. const input = event.inputBuffer;
  262. if (GodotAudio.input) {
  263. const inlen = input.getChannelData(0).length;
  264. for (let ch = 0; ch < 2; ch++) {
  265. const data = input.getChannelData(ch);
  266. for (let s = 0; s < inlen; s++) {
  267. inb[s * 2 + ch] = data[s];
  268. }
  269. }
  270. }
  271. // Let Godot process the input/output.
  272. onprocess();
  273. // Write the output.
  274. const outb = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  275. const output = event.outputBuffer;
  276. const channels = output.numberOfChannels;
  277. for (let ch = 0; ch < channels; ch++) {
  278. const data = output.getChannelData(ch);
  279. // Loop through samples and assign computed values.
  280. for (let sample = 0; sample < data.length; sample++) {
  281. data[sample] = outb[sample * channels + ch];
  282. }
  283. }
  284. };
  285. GodotAudioScript.script.connect(GodotAudio.ctx.destination);
  286. },
  287. get_node: function() {
  288. return GodotAudioScript.script;
  289. },
  290. close: function() {
  291. return new Promise(function(resolve, reject) {
  292. GodotAudioScript.script.disconnect();
  293. GodotAudioScript.script.onaudioprocess = null;
  294. GodotAudioScript.script = null;
  295. resolve();
  296. });
  297. },
  298. },
  299. godot_audio_script_create: function(buffer_length, channel_count) {
  300. return GodotAudioScript.create(buffer_length, channel_count);
  301. },
  302. godot_audio_script_start: function(p_in_buf, p_in_size, p_out_buf, p_out_size, p_cb) {
  303. const onprocess = GodotRuntime.get_func(p_cb);
  304. GodotAudioScript.start(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess);
  305. },
  306. };
  307. autoAddDeps(GodotAudioScript, "$GodotAudioScript");
  308. mergeInto(LibraryManager.library, GodotAudioScript);