2
0

audio_driver_javascript.cpp 9.4 KB

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