audio_driver_javascript.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*************************************************************************/
  2. /* audio_driver_javascript.cpp */
  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. #include "audio_driver_javascript.h"
  31. #include <emscripten.h>
  32. AudioDriverJavaScript *AudioDriverJavaScript::singleton = nullptr;
  33. const char *AudioDriverJavaScript::get_name() const {
  34. return "JavaScript";
  35. }
  36. extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_js_mix() {
  37. AudioDriverJavaScript::singleton->mix_to_js();
  38. }
  39. extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_process_capture(float sample) {
  40. AudioDriverJavaScript::singleton->process_capture(sample);
  41. }
  42. void AudioDriverJavaScript::mix_to_js() {
  43. int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode());
  44. int sample_count = memarr_len(internal_buffer) / channel_count;
  45. int32_t *stream_buffer = reinterpret_cast<int32_t *>(internal_buffer);
  46. audio_server_process(sample_count, stream_buffer);
  47. for (int i = 0; i < sample_count * channel_count; i++) {
  48. internal_buffer[i] = float(stream_buffer[i] >> 16) / 32768.f;
  49. }
  50. }
  51. void AudioDriverJavaScript::process_capture(float sample) {
  52. int32_t sample32 = int32_t(sample * 32768.f) * (1U << 16);
  53. input_buffer_write(sample32);
  54. }
  55. Error AudioDriverJavaScript::init() {
  56. /* clang-format off */
  57. _driver_id = EM_ASM_INT({
  58. return Module.IDHandler.add({
  59. 'context': new (window.AudioContext || window.webkitAudioContext),
  60. 'input': null,
  61. 'stream': null,
  62. 'script': null
  63. });
  64. });
  65. /* clang-format on */
  66. int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode());
  67. /* clang-format off */
  68. buffer_length = EM_ASM_INT({
  69. var ref = Module.IDHandler.get($0);
  70. var ctx = ref['context'];
  71. var CHANNEL_COUNT = $1;
  72. var channelCount = ctx.destination.channelCount;
  73. var script = null;
  74. try {
  75. // Try letting the browser recommend a buffer length.
  76. script = ctx.createScriptProcessor(0, 2, channelCount);
  77. } catch (e) {
  78. // ...otherwise, default to 4096.
  79. script = ctx.createScriptProcessor(4096, 2, channelCount);
  80. }
  81. script.connect(ctx.destination);
  82. ref['script'] = script;
  83. return script.bufferSize;
  84. }, _driver_id, channel_count);
  85. /* clang-format on */
  86. if (!buffer_length) {
  87. return FAILED;
  88. }
  89. if (!internal_buffer || (int)memarr_len(internal_buffer) != buffer_length * channel_count) {
  90. if (internal_buffer)
  91. memdelete_arr(internal_buffer);
  92. internal_buffer = memnew_arr(float, buffer_length *channel_count);
  93. }
  94. return internal_buffer ? OK : ERR_OUT_OF_MEMORY;
  95. }
  96. void AudioDriverJavaScript::start() {
  97. /* clang-format off */
  98. EM_ASM({
  99. const ref = Module.IDHandler.get($0);
  100. var INTERNAL_BUFFER_PTR = $1;
  101. var audioDriverMixFunction = cwrap('audio_driver_js_mix');
  102. var audioDriverProcessCapture = cwrap('audio_driver_process_capture', null, ['number']);
  103. ref['script'].onaudioprocess = function(audioProcessingEvent) {
  104. audioDriverMixFunction();
  105. var input = audioProcessingEvent.inputBuffer;
  106. var output = audioProcessingEvent.outputBuffer;
  107. var internalBuffer = HEAPF32.subarray(
  108. INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT,
  109. INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT + output.length * output.numberOfChannels);
  110. for (var channel = 0; channel < output.numberOfChannels; channel++) {
  111. var outputData = output.getChannelData(channel);
  112. // Loop through samples.
  113. for (var sample = 0; sample < outputData.length; sample++) {
  114. outputData[sample] = internalBuffer[sample * output.numberOfChannels + channel];
  115. }
  116. }
  117. if (ref['input']) {
  118. var inputDataL = input.getChannelData(0);
  119. var inputDataR = input.getChannelData(1);
  120. for (var i = 0; i < inputDataL.length; i++) {
  121. audioDriverProcessCapture(inputDataL[i]);
  122. audioDriverProcessCapture(inputDataR[i]);
  123. }
  124. }
  125. };
  126. }, _driver_id, internal_buffer);
  127. /* clang-format on */
  128. }
  129. void AudioDriverJavaScript::resume() {
  130. /* clang-format off */
  131. EM_ASM({
  132. const ref = Module.IDHandler.get($0);
  133. if (ref && ref['context'] && ref['context'].resume)
  134. ref['context'].resume();
  135. }, _driver_id);
  136. /* clang-format on */
  137. }
  138. int AudioDriverJavaScript::get_mix_rate() const {
  139. /* clang-format off */
  140. return EM_ASM_INT({
  141. const ref = Module.IDHandler.get($0);
  142. return ref && ref['context'] ? ref['context'].sampleRate : 0;
  143. }, _driver_id);
  144. /* clang-format on */
  145. }
  146. AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const {
  147. /* clang-format off */
  148. return get_speaker_mode_by_total_channels(EM_ASM_INT({
  149. const ref = Module.IDHandler.get($0);
  150. return ref && ref['context'] ? ref['context'].destination.channelCount : 0;
  151. }, _driver_id));
  152. /* clang-format on */
  153. }
  154. // No locking, as threads are not supported.
  155. void AudioDriverJavaScript::lock() {
  156. }
  157. void AudioDriverJavaScript::unlock() {
  158. }
  159. void AudioDriverJavaScript::finish_async() {
  160. // Close the context, add the operation to the async_finish list in module.
  161. int id = _driver_id;
  162. _driver_id = 0;
  163. /* clang-format off */
  164. EM_ASM({
  165. var ref = Module.IDHandler.get($0);
  166. Module.async_finish.push(new Promise(function(accept, reject) {
  167. if (!ref) {
  168. console.log("Ref not found!", $0, Module.IDHandler);
  169. setTimeout(accept, 0);
  170. } else {
  171. const context = ref['context'];
  172. // Disconnect script and input.
  173. ref['script'].disconnect();
  174. if (ref['input'])
  175. ref['input'].disconnect();
  176. ref = null;
  177. context.close().then(function() {
  178. accept();
  179. }).catch(function(e) {
  180. accept();
  181. });
  182. }
  183. }));
  184. Module.IDHandler.remove($0);
  185. }, id);
  186. /* clang-format on */
  187. }
  188. void AudioDriverJavaScript::finish() {
  189. if (internal_buffer) {
  190. memdelete_arr(internal_buffer);
  191. internal_buffer = nullptr;
  192. }
  193. }
  194. Error AudioDriverJavaScript::capture_start() {
  195. input_buffer_init(buffer_length);
  196. /* clang-format off */
  197. EM_ASM({
  198. function gotMediaInput(stream) {
  199. var ref = Module.IDHandler.get($0);
  200. ref['stream'] = stream;
  201. ref['input'] = ref['context'].createMediaStreamSource(stream);
  202. ref['input'].connect(ref['script']);
  203. }
  204. function gotMediaInputError(e) {
  205. out(e);
  206. }
  207. if (navigator.mediaDevices.getUserMedia) {
  208. navigator.mediaDevices.getUserMedia({"audio": true}).then(gotMediaInput, gotMediaInputError);
  209. } else {
  210. if (!navigator.getUserMedia)
  211. navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  212. navigator.getUserMedia({"audio": true}, gotMediaInput, gotMediaInputError);
  213. }
  214. }, _driver_id);
  215. /* clang-format on */
  216. return OK;
  217. }
  218. Error AudioDriverJavaScript::capture_stop() {
  219. /* clang-format off */
  220. EM_ASM({
  221. var ref = Module.IDHandler.get($0);
  222. if (ref['stream']) {
  223. const tracks = ref['stream'].getTracks();
  224. for (var i = 0; i < tracks.length; i++) {
  225. tracks[i].stop();
  226. }
  227. ref['stream'] = null;
  228. }
  229. if (ref['input']) {
  230. ref['input'].disconnect();
  231. ref['input'] = null;
  232. }
  233. }, _driver_id);
  234. /* clang-format on */
  235. input_buffer.clear();
  236. return OK;
  237. }
  238. AudioDriverJavaScript::AudioDriverJavaScript() {
  239. _driver_id = 0;
  240. internal_buffer = nullptr;
  241. buffer_length = 0;
  242. singleton = this;
  243. }