audio_driver_web.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /**************************************************************************/
  2. /* audio_driver_web.cpp */
  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. #include "audio_driver_web.h"
  31. #include "godot_audio.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/object/object.h"
  34. #include "scene/main/node.h"
  35. #include "servers/audio/audio_stream.h"
  36. #include <emscripten.h>
  37. AudioDriverWeb::AudioContext AudioDriverWeb::audio_context;
  38. bool AudioDriverWeb::is_available() {
  39. return godot_audio_is_available() != 0;
  40. }
  41. void AudioDriverWeb::_state_change_callback(int p_state) {
  42. AudioDriverWeb::audio_context.state = p_state;
  43. }
  44. void AudioDriverWeb::_latency_update_callback(float p_latency) {
  45. AudioDriverWeb::audio_context.output_latency = p_latency;
  46. }
  47. void AudioDriverWeb::_sample_playback_finished_callback(const char *p_playback_object_id) {
  48. const ObjectID playback_id = ObjectID(String::to_int(p_playback_object_id));
  49. Object *playback_object = ObjectDB::get_instance(playback_id);
  50. if (playback_object == nullptr) {
  51. return;
  52. }
  53. Ref<AudioSamplePlayback> playback = Object::cast_to<AudioSamplePlayback>(playback_object);
  54. if (playback.is_null()) {
  55. return;
  56. }
  57. AudioServer::get_singleton()->stop_sample_playback(playback);
  58. }
  59. void AudioDriverWeb::_audio_driver_process(int p_from, int p_samples) {
  60. int32_t *stream_buffer = reinterpret_cast<int32_t *>(output_rb);
  61. const int max_samples = memarr_len(output_rb);
  62. int write_pos = p_from;
  63. int to_write = p_samples;
  64. if (to_write == 0) {
  65. to_write = max_samples;
  66. }
  67. // High part
  68. if (write_pos + to_write > max_samples) {
  69. const int samples_high = max_samples - write_pos;
  70. audio_server_process(samples_high / channel_count, &stream_buffer[write_pos]);
  71. for (int i = write_pos; i < max_samples; i++) {
  72. output_rb[i] = float(stream_buffer[i] >> 16) / 32768.f;
  73. }
  74. to_write -= samples_high;
  75. write_pos = 0;
  76. }
  77. // Leftover
  78. audio_server_process(to_write / channel_count, &stream_buffer[write_pos]);
  79. for (int i = write_pos; i < write_pos + to_write; i++) {
  80. output_rb[i] = float(stream_buffer[i] >> 16) / 32768.f;
  81. }
  82. }
  83. void AudioDriverWeb::_audio_driver_capture(int p_from, int p_samples) {
  84. if (get_input_buffer().size() == 0) {
  85. return; // Input capture stopped.
  86. }
  87. const int max_samples = memarr_len(input_rb);
  88. int read_pos = p_from;
  89. int to_read = p_samples;
  90. if (to_read == 0) {
  91. to_read = max_samples;
  92. }
  93. // High part
  94. if (read_pos + to_read > max_samples) {
  95. const int samples_high = max_samples - read_pos;
  96. for (int i = read_pos; i < max_samples; i++) {
  97. input_buffer_write(int32_t(input_rb[i] * 32768.f) * (1U << 16));
  98. }
  99. to_read -= samples_high;
  100. read_pos = 0;
  101. }
  102. // Leftover
  103. for (int i = read_pos; i < read_pos + to_read; i++) {
  104. input_buffer_write(int32_t(input_rb[i] * 32768.f) * (1U << 16));
  105. }
  106. }
  107. Error AudioDriverWeb::init() {
  108. int latency = Engine::get_singleton()->get_audio_output_latency();
  109. if (!audio_context.inited) {
  110. audio_context.mix_rate = _get_configured_mix_rate();
  111. audio_context.channel_count = godot_audio_init(&audio_context.mix_rate, latency, &_state_change_callback, &_latency_update_callback);
  112. audio_context.inited = true;
  113. }
  114. mix_rate = audio_context.mix_rate;
  115. channel_count = audio_context.channel_count;
  116. buffer_length = closest_power_of_2((latency * mix_rate / 1000));
  117. Error err = create(buffer_length, channel_count);
  118. if (err != OK) {
  119. return err;
  120. }
  121. if (output_rb) {
  122. memdelete_arr(output_rb);
  123. }
  124. const size_t array_size = buffer_length * (size_t)channel_count;
  125. output_rb = memnew_arr(float, array_size);
  126. if (!output_rb) {
  127. return ERR_OUT_OF_MEMORY;
  128. }
  129. if (input_rb) {
  130. memdelete_arr(input_rb);
  131. }
  132. input_rb = memnew_arr(float, array_size);
  133. if (!input_rb) {
  134. return ERR_OUT_OF_MEMORY;
  135. }
  136. godot_audio_sample_set_finished_callback(&_sample_playback_finished_callback);
  137. return OK;
  138. }
  139. void AudioDriverWeb::start() {
  140. start(output_rb, memarr_len(output_rb), input_rb, memarr_len(input_rb));
  141. }
  142. void AudioDriverWeb::resume() {
  143. if (audio_context.state == 0) { // 'suspended'
  144. godot_audio_resume();
  145. }
  146. }
  147. float AudioDriverWeb::get_latency() {
  148. return audio_context.output_latency + (float(buffer_length) / mix_rate);
  149. }
  150. int AudioDriverWeb::get_mix_rate() const {
  151. return mix_rate;
  152. }
  153. AudioDriver::SpeakerMode AudioDriverWeb::get_speaker_mode() const {
  154. return get_speaker_mode_by_total_channels(channel_count);
  155. }
  156. void AudioDriverWeb::finish() {
  157. finish_driver();
  158. if (output_rb) {
  159. memdelete_arr(output_rb);
  160. output_rb = nullptr;
  161. }
  162. if (input_rb) {
  163. memdelete_arr(input_rb);
  164. input_rb = nullptr;
  165. }
  166. }
  167. Error AudioDriverWeb::input_start() {
  168. lock();
  169. input_buffer_init(buffer_length);
  170. unlock();
  171. if (godot_audio_input_start()) {
  172. return FAILED;
  173. }
  174. return OK;
  175. }
  176. Error AudioDriverWeb::input_stop() {
  177. godot_audio_input_stop();
  178. lock();
  179. input_buffer.clear();
  180. unlock();
  181. return OK;
  182. }
  183. bool AudioDriverWeb::is_stream_registered_as_sample(const Ref<AudioStream> &p_stream) const {
  184. ERR_FAIL_COND_V_MSG(p_stream.is_null(), false, "Parameter p_stream is null.");
  185. return godot_audio_sample_stream_is_registered(itos(p_stream->get_instance_id()).utf8().get_data()) != 0;
  186. }
  187. void AudioDriverWeb::register_sample(const Ref<AudioSample> &p_sample) {
  188. ERR_FAIL_COND_MSG(p_sample.is_null(), "Parameter p_sample is null.");
  189. ERR_FAIL_COND_MSG(p_sample->stream.is_null(), "Parameter p_sample->stream is null.");
  190. String loop_mode;
  191. switch (p_sample->loop_mode) {
  192. case AudioSample::LoopMode::LOOP_DISABLED: {
  193. loop_mode = "disabled";
  194. } break;
  195. case AudioSample::LoopMode::LOOP_FORWARD: {
  196. loop_mode = "forward";
  197. } break;
  198. case AudioSample::LoopMode::LOOP_PINGPONG: {
  199. loop_mode = "pingpong";
  200. } break;
  201. case AudioSample::LoopMode::LOOP_BACKWARD: {
  202. loop_mode = "backward";
  203. } break;
  204. }
  205. double length = p_sample->stream->get_length();
  206. Vector<AudioFrame> frames;
  207. int frames_total = mix_rate * length;
  208. {
  209. Ref<AudioStreamPlayback> stream_playback = p_sample->stream->instantiate_playback();
  210. frames.resize(frames_total);
  211. AudioFrame *frames_ptr = frames.ptrw();
  212. stream_playback->start();
  213. stream_playback->mix(frames_ptr, 1.0f, frames_total);
  214. }
  215. PackedFloat32Array data;
  216. data.resize(frames_total * 2);
  217. float *data_ptrw = data.ptrw();
  218. for (int i = 0; i < frames_total; i++) {
  219. data_ptrw[i] = frames[i].left;
  220. data_ptrw[i + frames_total] = frames[i].right;
  221. }
  222. godot_audio_sample_register_stream(
  223. itos(p_sample->stream->get_instance_id()).utf8().get_data(),
  224. data_ptrw,
  225. frames_total,
  226. loop_mode.utf8().get_data(),
  227. p_sample->loop_begin,
  228. p_sample->loop_end);
  229. }
  230. void AudioDriverWeb::unregister_sample(const Ref<AudioSample> &p_sample) {
  231. ERR_FAIL_COND_MSG(p_sample.is_null(), "Parameter p_sample is null.");
  232. ERR_FAIL_COND_MSG(p_sample->stream.is_null(), "Parameter p_sample->stream is null.");
  233. godot_audio_sample_unregister_stream(itos(p_sample->stream->get_instance_id()).utf8().get_data());
  234. }
  235. void AudioDriverWeb::start_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
  236. ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
  237. ERR_FAIL_COND_MSG(p_playback->stream.is_null(), "Parameter p_playback->stream is null.");
  238. constexpr int real_max_channels = AudioServer::MAX_CHANNELS_PER_BUS * 2;
  239. PackedFloat32Array volume;
  240. volume.resize(real_max_channels);
  241. float *volume_ptrw = volume.ptrw();
  242. for (int i = 0; i < real_max_channels; i += 2) {
  243. if (p_playback->volume_vector.is_empty()) {
  244. volume_ptrw[i] = 0;
  245. volume_ptrw[i + 1] = 0;
  246. } else {
  247. const AudioFrame &frame = p_playback->volume_vector[i / 2];
  248. volume_ptrw[i] = frame.left;
  249. volume_ptrw[i + 1] = frame.right;
  250. }
  251. }
  252. godot_audio_sample_start(
  253. itos(p_playback->get_instance_id()).utf8().get_data(),
  254. itos(p_playback->stream->get_instance_id()).utf8().get_data(),
  255. AudioServer::get_singleton()->get_bus_index(p_playback->bus),
  256. p_playback->offset,
  257. p_playback->pitch_scale,
  258. volume_ptrw);
  259. }
  260. void AudioDriverWeb::stop_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
  261. ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
  262. godot_audio_sample_stop(itos(p_playback->get_instance_id()).utf8().get_data());
  263. }
  264. void AudioDriverWeb::set_sample_playback_pause(const Ref<AudioSamplePlayback> &p_playback, bool p_paused) {
  265. ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
  266. godot_audio_sample_set_pause(itos(p_playback->get_instance_id()).utf8().get_data(), p_paused);
  267. }
  268. bool AudioDriverWeb::is_sample_playback_active(const Ref<AudioSamplePlayback> &p_playback) {
  269. ERR_FAIL_COND_V_MSG(p_playback.is_null(), false, "Parameter p_playback is null.");
  270. return godot_audio_sample_is_active(itos(p_playback->get_instance_id()).utf8().get_data()) != 0;
  271. }
  272. double AudioDriverWeb::get_sample_playback_position(const Ref<AudioSamplePlayback> &p_playback) {
  273. ERR_FAIL_COND_V_MSG(p_playback.is_null(), false, "Parameter p_playback is null.");
  274. return godot_audio_get_sample_playback_position(itos(p_playback->get_instance_id()).utf8().get_data());
  275. }
  276. void AudioDriverWeb::update_sample_playback_pitch_scale(const Ref<AudioSamplePlayback> &p_playback, float p_pitch_scale) {
  277. ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
  278. godot_audio_sample_update_pitch_scale(
  279. itos(p_playback->get_instance_id()).utf8().get_data(),
  280. p_pitch_scale);
  281. }
  282. void AudioDriverWeb::set_sample_playback_bus_volumes_linear(const Ref<AudioSamplePlayback> &p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes) {
  283. ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
  284. constexpr int real_max_channels = AudioServer::MAX_CHANNELS_PER_BUS * 2;
  285. PackedInt32Array buses;
  286. buses.resize(p_bus_volumes.size());
  287. int32_t *buses_ptrw = buses.ptrw();
  288. PackedFloat32Array values;
  289. values.resize(p_bus_volumes.size() * AudioServer::MAX_CHANNELS_PER_BUS * 2);
  290. float *values_ptrw = values.ptrw();
  291. int idx = 0;
  292. for (KeyValue<StringName, Vector<AudioFrame>> pair : p_bus_volumes) {
  293. int bus_index = AudioServer::get_singleton()->get_bus_index(pair.key);
  294. buses_ptrw[idx] = bus_index;
  295. ERR_FAIL_COND(pair.value.size() != AudioServer::MAX_CHANNELS_PER_BUS);
  296. for (int i = 0; i < real_max_channels; i += 2) {
  297. const AudioFrame &frame = pair.value[i / 2];
  298. values_ptrw[(idx * real_max_channels) + i] = frame.left;
  299. values_ptrw[(idx * real_max_channels) + i + 1] = frame.right;
  300. }
  301. idx++;
  302. }
  303. godot_audio_sample_set_volumes_linear(
  304. itos(p_playback->get_instance_id()).utf8().get_data(),
  305. buses_ptrw,
  306. buses.size(),
  307. values_ptrw,
  308. values.size());
  309. }
  310. void AudioDriverWeb::set_sample_bus_count(int p_count) {
  311. godot_audio_sample_bus_set_count(p_count);
  312. }
  313. void AudioDriverWeb::remove_sample_bus(int p_index) {
  314. godot_audio_sample_bus_remove(p_index);
  315. }
  316. void AudioDriverWeb::add_sample_bus(int p_at_pos) {
  317. godot_audio_sample_bus_add(p_at_pos);
  318. }
  319. void AudioDriverWeb::move_sample_bus(int p_bus, int p_to_pos) {
  320. godot_audio_sample_bus_move(p_bus, p_to_pos);
  321. }
  322. void AudioDriverWeb::set_sample_bus_send(int p_bus, const StringName &p_send) {
  323. godot_audio_sample_bus_set_send(p_bus, AudioServer::get_singleton()->get_bus_index(p_send));
  324. }
  325. void AudioDriverWeb::set_sample_bus_volume_db(int p_bus, float p_volume_db) {
  326. godot_audio_sample_bus_set_volume_db(p_bus, p_volume_db);
  327. }
  328. void AudioDriverWeb::set_sample_bus_solo(int p_bus, bool p_enable) {
  329. godot_audio_sample_bus_set_solo(p_bus, p_enable);
  330. }
  331. void AudioDriverWeb::set_sample_bus_mute(int p_bus, bool p_enable) {
  332. godot_audio_sample_bus_set_mute(p_bus, p_enable);
  333. }
  334. #ifdef THREADS_ENABLED
  335. /// AudioWorkletNode implementation (threads)
  336. void AudioDriverWorklet::_audio_thread_func(void *p_data) {
  337. AudioDriverWorklet *driver = static_cast<AudioDriverWorklet *>(p_data);
  338. const int out_samples = memarr_len(driver->get_output_rb());
  339. const int in_samples = memarr_len(driver->get_input_rb());
  340. int wpos = 0;
  341. int to_write = out_samples;
  342. int rpos = 0;
  343. int to_read = 0;
  344. int32_t step = 0;
  345. while (!driver->quit) {
  346. if (to_read) {
  347. driver->lock();
  348. driver->_audio_driver_capture(rpos, to_read);
  349. godot_audio_worklet_state_add(driver->state, STATE_SAMPLES_IN, -to_read);
  350. driver->unlock();
  351. rpos += to_read;
  352. if (rpos >= in_samples) {
  353. rpos -= in_samples;
  354. }
  355. }
  356. if (to_write) {
  357. driver->lock();
  358. driver->_audio_driver_process(wpos, to_write);
  359. godot_audio_worklet_state_add(driver->state, STATE_SAMPLES_OUT, to_write);
  360. driver->unlock();
  361. wpos += to_write;
  362. if (wpos >= out_samples) {
  363. wpos -= out_samples;
  364. }
  365. }
  366. step = godot_audio_worklet_state_wait(driver->state, STATE_PROCESS, step, 1);
  367. to_write = out_samples - godot_audio_worklet_state_get(driver->state, STATE_SAMPLES_OUT);
  368. to_read = godot_audio_worklet_state_get(driver->state, STATE_SAMPLES_IN);
  369. }
  370. }
  371. Error AudioDriverWorklet::create(int &p_buffer_size, int p_channels) {
  372. if (!godot_audio_has_worklet()) {
  373. return ERR_UNAVAILABLE;
  374. }
  375. return (Error)godot_audio_worklet_create(p_channels);
  376. }
  377. void AudioDriverWorklet::start(float *p_out_buf, int p_out_buf_size, float *p_in_buf, int p_in_buf_size) {
  378. godot_audio_worklet_start(p_in_buf, p_in_buf_size, p_out_buf, p_out_buf_size, state);
  379. thread.start(_audio_thread_func, this);
  380. }
  381. void AudioDriverWorklet::lock() {
  382. mutex.lock();
  383. }
  384. void AudioDriverWorklet::unlock() {
  385. mutex.unlock();
  386. }
  387. void AudioDriverWorklet::finish_driver() {
  388. quit = true; // Ask thread to quit.
  389. thread.wait_to_finish();
  390. }
  391. #else // No threads.
  392. /// AudioWorkletNode implementation (no threads)
  393. AudioDriverWorklet *AudioDriverWorklet::singleton = nullptr;
  394. Error AudioDriverWorklet::create(int &p_buffer_size, int p_channels) {
  395. if (!godot_audio_has_worklet()) {
  396. return ERR_UNAVAILABLE;
  397. }
  398. return (Error)godot_audio_worklet_create(p_channels);
  399. }
  400. void AudioDriverWorklet::start(float *p_out_buf, int p_out_buf_size, float *p_in_buf, int p_in_buf_size) {
  401. _audio_driver_process();
  402. godot_audio_worklet_start_no_threads(p_out_buf, p_out_buf_size, &_process_callback, p_in_buf, p_in_buf_size, &_capture_callback);
  403. }
  404. void AudioDriverWorklet::_process_callback(int p_pos, int p_samples) {
  405. AudioDriverWorklet *driver = AudioDriverWorklet::get_singleton();
  406. driver->_audio_driver_process(p_pos, p_samples);
  407. }
  408. void AudioDriverWorklet::_capture_callback(int p_pos, int p_samples) {
  409. AudioDriverWorklet *driver = AudioDriverWorklet::get_singleton();
  410. driver->_audio_driver_capture(p_pos, p_samples);
  411. }
  412. /// ScriptProcessorNode implementation
  413. AudioDriverScriptProcessor *AudioDriverScriptProcessor::singleton = nullptr;
  414. void AudioDriverScriptProcessor::_process_callback() {
  415. AudioDriverScriptProcessor::get_singleton()->_audio_driver_capture();
  416. AudioDriverScriptProcessor::get_singleton()->_audio_driver_process();
  417. }
  418. Error AudioDriverScriptProcessor::create(int &p_buffer_samples, int p_channels) {
  419. if (!godot_audio_has_script_processor()) {
  420. return ERR_UNAVAILABLE;
  421. }
  422. return (Error)godot_audio_script_create(&p_buffer_samples, p_channels);
  423. }
  424. void AudioDriverScriptProcessor::start(float *p_out_buf, int p_out_buf_size, float *p_in_buf, int p_in_buf_size) {
  425. godot_audio_script_start(p_in_buf, p_in_buf_size, p_out_buf, p_out_buf_size, &_process_callback);
  426. }
  427. #endif // THREADS_ENABLED