audio_driver_javascript.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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. EM_ASM({
  58. _audioDriver_audioContext = new (window.AudioContext || window.webkitAudioContext);
  59. _audioDriver_audioInput = null;
  60. _audioDriver_inputStream = null;
  61. _audioDriver_scriptNode = null;
  62. });
  63. /* clang-format on */
  64. int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode());
  65. /* clang-format off */
  66. buffer_length = EM_ASM_INT({
  67. var CHANNEL_COUNT = $0;
  68. var channelCount = _audioDriver_audioContext.destination.channelCount;
  69. try {
  70. // Try letting the browser recommend a buffer length.
  71. _audioDriver_scriptNode = _audioDriver_audioContext.createScriptProcessor(0, 2, channelCount);
  72. } catch (e) {
  73. // ...otherwise, default to 4096.
  74. _audioDriver_scriptNode = _audioDriver_audioContext.createScriptProcessor(4096, 2, channelCount);
  75. }
  76. _audioDriver_scriptNode.connect(_audioDriver_audioContext.destination);
  77. return _audioDriver_scriptNode.bufferSize;
  78. }, channel_count);
  79. /* clang-format on */
  80. if (!buffer_length) {
  81. return FAILED;
  82. }
  83. if (!internal_buffer || memarr_len(internal_buffer) != buffer_length * channel_count) {
  84. if (internal_buffer)
  85. memdelete_arr(internal_buffer);
  86. internal_buffer = memnew_arr(float, buffer_length *channel_count);
  87. }
  88. return internal_buffer ? OK : ERR_OUT_OF_MEMORY;
  89. }
  90. void AudioDriverJavaScript::start() {
  91. /* clang-format off */
  92. EM_ASM({
  93. var INTERNAL_BUFFER_PTR = $0;
  94. var audioDriverMixFunction = cwrap('audio_driver_js_mix');
  95. var audioDriverProcessCapture = cwrap('audio_driver_process_capture', null, ['number']);
  96. _audioDriver_scriptNode.onaudioprocess = function(audioProcessingEvent) {
  97. audioDriverMixFunction();
  98. var input = audioProcessingEvent.inputBuffer;
  99. var output = audioProcessingEvent.outputBuffer;
  100. var internalBuffer = HEAPF32.subarray(
  101. INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT,
  102. INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT + output.length * output.numberOfChannels);
  103. for (var channel = 0; channel < output.numberOfChannels; channel++) {
  104. var outputData = output.getChannelData(channel);
  105. // Loop through samples.
  106. for (var sample = 0; sample < outputData.length; sample++) {
  107. outputData[sample] = internalBuffer[sample * output.numberOfChannels + channel];
  108. }
  109. }
  110. if (_audioDriver_audioInput) {
  111. var inputDataL = input.getChannelData(0);
  112. var inputDataR = input.getChannelData(1);
  113. for (var i = 0; i < inputDataL.length; i++) {
  114. audioDriverProcessCapture(inputDataL[i]);
  115. audioDriverProcessCapture(inputDataR[i]);
  116. }
  117. }
  118. };
  119. }, internal_buffer);
  120. /* clang-format on */
  121. }
  122. void AudioDriverJavaScript::resume() {
  123. /* clang-format off */
  124. EM_ASM({
  125. if (_audioDriver_audioContext.resume)
  126. _audioDriver_audioContext.resume();
  127. });
  128. /* clang-format on */
  129. }
  130. int AudioDriverJavaScript::get_mix_rate() const {
  131. /* clang-format off */
  132. return EM_ASM_INT_V({
  133. return _audioDriver_audioContext.sampleRate;
  134. });
  135. /* clang-format on */
  136. }
  137. AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const {
  138. /* clang-format off */
  139. return get_speaker_mode_by_total_channels(EM_ASM_INT_V({
  140. return _audioDriver_audioContext.destination.channelCount;
  141. }));
  142. /* clang-format on */
  143. }
  144. // No locking, as threads are not supported.
  145. void AudioDriverJavaScript::lock() {
  146. }
  147. void AudioDriverJavaScript::unlock() {
  148. }
  149. void AudioDriverJavaScript::finish() {
  150. /* clang-format off */
  151. EM_ASM({
  152. _audioDriver_audioContext = null;
  153. _audioDriver_audioInput = null;
  154. _audioDriver_scriptNode = null;
  155. });
  156. /* clang-format on */
  157. if (internal_buffer) {
  158. memdelete_arr(internal_buffer);
  159. internal_buffer = NULL;
  160. }
  161. }
  162. Error AudioDriverJavaScript::capture_start() {
  163. input_buffer_init(buffer_length);
  164. /* clang-format off */
  165. EM_ASM({
  166. function gotMediaInput(stream) {
  167. _audioDriver_inputStream = stream;
  168. _audioDriver_audioInput = _audioDriver_audioContext.createMediaStreamSource(stream);
  169. _audioDriver_audioInput.connect(_audioDriver_scriptNode);
  170. }
  171. function gotMediaInputError(e) {
  172. out(e);
  173. }
  174. if (navigator.mediaDevices.getUserMedia) {
  175. navigator.mediaDevices.getUserMedia({"audio": true}).then(gotMediaInput, gotMediaInputError);
  176. } else {
  177. if (!navigator.getUserMedia)
  178. navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  179. navigator.getUserMedia({"audio": true}, gotMediaInput, gotMediaInputError);
  180. }
  181. });
  182. /* clang-format on */
  183. return OK;
  184. }
  185. Error AudioDriverJavaScript::capture_stop() {
  186. /* clang-format off */
  187. EM_ASM({
  188. if (_audioDriver_inputStream) {
  189. const tracks = _audioDriver_inputStream.getTracks();
  190. for (var i = 0; i < tracks.length; i++) {
  191. tracks[i].stop();
  192. }
  193. _audioDriver_inputStream = null;
  194. }
  195. if (_audioDriver_audioInput) {
  196. _audioDriver_audioInput.disconnect();
  197. _audioDriver_audioInput = null;
  198. }
  199. });
  200. /* clang-format on */
  201. input_buffer.clear();
  202. return OK;
  203. }
  204. AudioDriverJavaScript::AudioDriverJavaScript() {
  205. internal_buffer = NULL;
  206. singleton = this;
  207. }