library_godot_audio.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /**************************************************************************/
  2. /* library_godot_audio.js */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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_has_worklet__sig: 'i',
  156. godot_audio_has_worklet: function () {
  157. return (GodotAudio.ctx && GodotAudio.ctx.audioWorklet) ? 1 : 0;
  158. },
  159. godot_audio_has_script_processor__sig: 'i',
  160. godot_audio_has_script_processor: function () {
  161. return (GodotAudio.ctx && GodotAudio.ctx.createScriptProcessor) ? 1 : 0;
  162. },
  163. godot_audio_init__sig: 'iiiii',
  164. godot_audio_init: function (p_mix_rate, p_latency, p_state_change, p_latency_update) {
  165. const statechange = GodotRuntime.get_func(p_state_change);
  166. const latencyupdate = GodotRuntime.get_func(p_latency_update);
  167. const mix_rate = GodotRuntime.getHeapValue(p_mix_rate, 'i32');
  168. const channels = GodotAudio.init(mix_rate, p_latency, statechange, latencyupdate);
  169. GodotRuntime.setHeapValue(p_mix_rate, GodotAudio.ctx.sampleRate, 'i32');
  170. return channels;
  171. },
  172. godot_audio_resume__sig: 'v',
  173. godot_audio_resume: function () {
  174. if (GodotAudio.ctx && GodotAudio.ctx.state !== 'running') {
  175. GodotAudio.ctx.resume();
  176. }
  177. },
  178. godot_audio_capture_start__proxy: 'sync',
  179. godot_audio_capture_start__sig: 'i',
  180. godot_audio_capture_start: function () {
  181. return GodotAudio.create_input(function (input) {
  182. input.connect(GodotAudio.driver.get_node());
  183. });
  184. },
  185. godot_audio_capture_stop__proxy: 'sync',
  186. godot_audio_capture_stop__sig: 'v',
  187. godot_audio_capture_stop: function () {
  188. if (GodotAudio.input) {
  189. const tracks = GodotAudio.input['mediaStream']['getTracks']();
  190. for (let i = 0; i < tracks.length; i++) {
  191. tracks[i]['stop']();
  192. }
  193. GodotAudio.input.disconnect();
  194. GodotAudio.input = null;
  195. }
  196. },
  197. };
  198. autoAddDeps(GodotAudio, '$GodotAudio');
  199. mergeInto(LibraryManager.library, GodotAudio);
  200. /**
  201. * The AudioWorklet API driver, used when threads are available.
  202. */
  203. const GodotAudioWorklet = {
  204. $GodotAudioWorklet__deps: ['$GodotAudio', '$GodotConfig'],
  205. $GodotAudioWorklet: {
  206. promise: null,
  207. worklet: null,
  208. ring_buffer: null,
  209. create: function (channels) {
  210. const path = GodotConfig.locate_file('godot.audio.worklet.js');
  211. GodotAudioWorklet.promise = GodotAudio.ctx.audioWorklet.addModule(path).then(function () {
  212. GodotAudioWorklet.worklet = new AudioWorkletNode(
  213. GodotAudio.ctx,
  214. 'godot-processor',
  215. {
  216. 'outputChannelCount': [channels],
  217. }
  218. );
  219. return Promise.resolve();
  220. });
  221. GodotAudio.driver = GodotAudioWorklet;
  222. },
  223. start: function (in_buf, out_buf, state) {
  224. GodotAudioWorklet.promise.then(function () {
  225. const node = GodotAudioWorklet.worklet;
  226. node.connect(GodotAudio.ctx.destination);
  227. node.port.postMessage({
  228. 'cmd': 'start',
  229. 'data': [state, in_buf, out_buf],
  230. });
  231. node.port.onmessage = function (event) {
  232. GodotRuntime.error(event.data);
  233. };
  234. });
  235. },
  236. start_no_threads: function (p_out_buf, p_out_size, out_callback, p_in_buf, p_in_size, in_callback) {
  237. function RingBuffer() {
  238. let wpos = 0;
  239. let rpos = 0;
  240. let pending_samples = 0;
  241. const wbuf = new Float32Array(p_out_size);
  242. function send(port) {
  243. if (pending_samples === 0) {
  244. return;
  245. }
  246. const buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  247. const size = buffer.length;
  248. const tot_sent = pending_samples;
  249. out_callback(wpos, pending_samples);
  250. if (wpos + pending_samples >= size) {
  251. const high = size - wpos;
  252. wbuf.set(buffer.subarray(wpos, size));
  253. pending_samples -= high;
  254. wpos = 0;
  255. }
  256. if (pending_samples > 0) {
  257. wbuf.set(buffer.subarray(wpos, wpos + pending_samples), tot_sent - pending_samples);
  258. }
  259. port.postMessage({ 'cmd': 'chunk', 'data': wbuf.subarray(0, tot_sent) });
  260. wpos += pending_samples;
  261. pending_samples = 0;
  262. }
  263. this.receive = function (recv_buf) {
  264. const buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  265. const from = rpos;
  266. let to_write = recv_buf.length;
  267. let high = 0;
  268. if (rpos + to_write >= p_in_size) {
  269. high = p_in_size - rpos;
  270. buffer.set(recv_buf.subarray(0, high), rpos);
  271. to_write -= high;
  272. rpos = 0;
  273. }
  274. if (to_write) {
  275. buffer.set(recv_buf.subarray(high, to_write), rpos);
  276. }
  277. in_callback(from, recv_buf.length);
  278. rpos += to_write;
  279. };
  280. this.consumed = function (size, port) {
  281. pending_samples += size;
  282. send(port);
  283. };
  284. }
  285. GodotAudioWorklet.ring_buffer = new RingBuffer();
  286. GodotAudioWorklet.promise.then(function () {
  287. const node = GodotAudioWorklet.worklet;
  288. const buffer = GodotRuntime.heapSlice(HEAPF32, p_out_buf, p_out_size);
  289. node.connect(GodotAudio.ctx.destination);
  290. node.port.postMessage({
  291. 'cmd': 'start_nothreads',
  292. 'data': [buffer, p_in_size],
  293. });
  294. node.port.onmessage = function (event) {
  295. if (!GodotAudioWorklet.worklet) {
  296. return;
  297. }
  298. if (event.data['cmd'] === 'read') {
  299. const read = event.data['data'];
  300. GodotAudioWorklet.ring_buffer.consumed(read, GodotAudioWorklet.worklet.port);
  301. } else if (event.data['cmd'] === 'input') {
  302. const buf = event.data['data'];
  303. if (buf.length > p_in_size) {
  304. GodotRuntime.error('Input chunk is too big');
  305. return;
  306. }
  307. GodotAudioWorklet.ring_buffer.receive(buf);
  308. } else {
  309. GodotRuntime.error(event.data);
  310. }
  311. };
  312. });
  313. },
  314. get_node: function () {
  315. return GodotAudioWorklet.worklet;
  316. },
  317. close: function () {
  318. return new Promise(function (resolve, reject) {
  319. if (GodotAudioWorklet.promise === null) {
  320. return;
  321. }
  322. GodotAudioWorklet.promise.then(function () {
  323. GodotAudioWorklet.worklet.port.postMessage({
  324. 'cmd': 'stop',
  325. 'data': null,
  326. });
  327. GodotAudioWorklet.worklet.disconnect();
  328. GodotAudioWorklet.worklet = null;
  329. GodotAudioWorklet.promise = null;
  330. resolve();
  331. }).catch(function (err) { /* aborted? */ });
  332. });
  333. },
  334. },
  335. godot_audio_worklet_create__sig: 'ii',
  336. godot_audio_worklet_create: function (channels) {
  337. try {
  338. GodotAudioWorklet.create(channels);
  339. } catch (e) {
  340. GodotRuntime.error('Error starting AudioDriverWorklet', e);
  341. return 1;
  342. }
  343. return 0;
  344. },
  345. godot_audio_worklet_start__sig: 'viiiii',
  346. godot_audio_worklet_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_state) {
  347. const out_buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  348. const in_buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  349. const state = GodotRuntime.heapSub(HEAP32, p_state, 4);
  350. GodotAudioWorklet.start(in_buffer, out_buffer, state);
  351. },
  352. godot_audio_worklet_start_no_threads__sig: 'viiiiii',
  353. godot_audio_worklet_start_no_threads: function (p_out_buf, p_out_size, p_out_callback, p_in_buf, p_in_size, p_in_callback) {
  354. const out_callback = GodotRuntime.get_func(p_out_callback);
  355. const in_callback = GodotRuntime.get_func(p_in_callback);
  356. GodotAudioWorklet.start_no_threads(p_out_buf, p_out_size, out_callback, p_in_buf, p_in_size, in_callback);
  357. },
  358. godot_audio_worklet_state_wait__sig: 'iiii',
  359. godot_audio_worklet_state_wait: function (p_state, p_idx, p_expected, p_timeout) {
  360. Atomics.wait(HEAP32, (p_state >> 2) + p_idx, p_expected, p_timeout);
  361. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  362. },
  363. godot_audio_worklet_state_add__sig: 'iiii',
  364. godot_audio_worklet_state_add: function (p_state, p_idx, p_value) {
  365. return Atomics.add(HEAP32, (p_state >> 2) + p_idx, p_value);
  366. },
  367. godot_audio_worklet_state_get__sig: 'iii',
  368. godot_audio_worklet_state_get: function (p_state, p_idx) {
  369. return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
  370. },
  371. };
  372. autoAddDeps(GodotAudioWorklet, '$GodotAudioWorklet');
  373. mergeInto(LibraryManager.library, GodotAudioWorklet);
  374. /*
  375. * The deprecated ScriptProcessorNode API, used when threads are disabled.
  376. */
  377. const GodotAudioScript = {
  378. $GodotAudioScript__deps: ['$GodotAudio'],
  379. $GodotAudioScript: {
  380. script: null,
  381. create: function (buffer_length, channel_count) {
  382. GodotAudioScript.script = GodotAudio.ctx.createScriptProcessor(buffer_length, 2, channel_count);
  383. GodotAudio.driver = GodotAudioScript;
  384. return GodotAudioScript.script.bufferSize;
  385. },
  386. start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess) {
  387. GodotAudioScript.script.onaudioprocess = function (event) {
  388. // Read input
  389. const inb = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
  390. const input = event.inputBuffer;
  391. if (GodotAudio.input) {
  392. const inlen = input.getChannelData(0).length;
  393. for (let ch = 0; ch < 2; ch++) {
  394. const data = input.getChannelData(ch);
  395. for (let s = 0; s < inlen; s++) {
  396. inb[s * 2 + ch] = data[s];
  397. }
  398. }
  399. }
  400. // Let Godot process the input/output.
  401. onprocess();
  402. // Write the output.
  403. const outb = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
  404. const output = event.outputBuffer;
  405. const channels = output.numberOfChannels;
  406. for (let ch = 0; ch < channels; ch++) {
  407. const data = output.getChannelData(ch);
  408. // Loop through samples and assign computed values.
  409. for (let sample = 0; sample < data.length; sample++) {
  410. data[sample] = outb[sample * channels + ch];
  411. }
  412. }
  413. };
  414. GodotAudioScript.script.connect(GodotAudio.ctx.destination);
  415. },
  416. get_node: function () {
  417. return GodotAudioScript.script;
  418. },
  419. close: function () {
  420. return new Promise(function (resolve, reject) {
  421. GodotAudioScript.script.disconnect();
  422. GodotAudioScript.script.onaudioprocess = null;
  423. GodotAudioScript.script = null;
  424. resolve();
  425. });
  426. },
  427. },
  428. godot_audio_script_create__sig: 'iii',
  429. godot_audio_script_create: function (buffer_length, channel_count) {
  430. const buf_len = GodotRuntime.getHeapValue(buffer_length, 'i32');
  431. try {
  432. const out_len = GodotAudioScript.create(buf_len, channel_count);
  433. GodotRuntime.setHeapValue(buffer_length, out_len, 'i32');
  434. } catch (e) {
  435. GodotRuntime.error('Error starting AudioDriverScriptProcessor', e);
  436. return 1;
  437. }
  438. return 0;
  439. },
  440. godot_audio_script_start__sig: 'viiiii',
  441. godot_audio_script_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_cb) {
  442. const onprocess = GodotRuntime.get_func(p_cb);
  443. GodotAudioScript.start(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess);
  444. },
  445. };
  446. autoAddDeps(GodotAudioScript, '$GodotAudioScript');
  447. mergeInto(LibraryManager.library, GodotAudioScript);