audio_driver_javascript.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 = NULL;
  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() {
  160. /* clang-format off */
  161. EM_ASM({
  162. Module.IDHandler.remove($0);
  163. }, _driver_id);
  164. /* clang-format on */
  165. if (internal_buffer) {
  166. memdelete_arr(internal_buffer);
  167. internal_buffer = NULL;
  168. }
  169. _driver_id = 0;
  170. }
  171. Error AudioDriverJavaScript::capture_start() {
  172. input_buffer_init(buffer_length);
  173. /* clang-format off */
  174. EM_ASM({
  175. function gotMediaInput(stream) {
  176. var ref = Module.IDHandler.get($0);
  177. ref['stream'] = stream;
  178. ref['input'] = ref['context'].createMediaStreamSource(stream);
  179. ref['input'].connect(ref['script']);
  180. }
  181. function gotMediaInputError(e) {
  182. out(e);
  183. }
  184. if (navigator.mediaDevices.getUserMedia) {
  185. navigator.mediaDevices.getUserMedia({"audio": true}).then(gotMediaInput, gotMediaInputError);
  186. } else {
  187. if (!navigator.getUserMedia)
  188. navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  189. navigator.getUserMedia({"audio": true}, gotMediaInput, gotMediaInputError);
  190. }
  191. }, _driver_id);
  192. /* clang-format on */
  193. return OK;
  194. }
  195. Error AudioDriverJavaScript::capture_stop() {
  196. /* clang-format off */
  197. EM_ASM({
  198. var ref = Module.IDHandler.get($0);
  199. if (ref['stream']) {
  200. const tracks = ref['stream'].getTracks();
  201. for (var i = 0; i < tracks.length; i++) {
  202. tracks[i].stop();
  203. }
  204. ref['stream'] = null;
  205. }
  206. if (ref['input']) {
  207. ref['input'].disconnect();
  208. ref['input'] = null;
  209. }
  210. }, _driver_id);
  211. /* clang-format on */
  212. input_buffer.clear();
  213. return OK;
  214. }
  215. AudioDriverJavaScript::AudioDriverJavaScript() {
  216. _driver_id = 0;
  217. internal_buffer = NULL;
  218. buffer_length = 0;
  219. singleton = this;
  220. }