audio_stream.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /*************************************************************************/
  2. /* audio_stream.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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_stream.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/os/os.h"
  33. void AudioStreamPlayback::start(float p_from_pos) {
  34. if (GDVIRTUAL_CALL(_start, p_from_pos)) {
  35. return;
  36. }
  37. ERR_FAIL_MSG("AudioStreamPlayback::start unimplemented!");
  38. }
  39. void AudioStreamPlayback::stop() {
  40. if (GDVIRTUAL_CALL(_stop)) {
  41. return;
  42. }
  43. ERR_FAIL_MSG("AudioStreamPlayback::stop unimplemented!");
  44. }
  45. bool AudioStreamPlayback::is_playing() const {
  46. bool ret;
  47. if (GDVIRTUAL_CALL(_is_playing, ret)) {
  48. return ret;
  49. }
  50. ERR_FAIL_V_MSG(false, "AudioStreamPlayback::is_playing unimplemented!");
  51. }
  52. int AudioStreamPlayback::get_loop_count() const {
  53. int ret;
  54. if (GDVIRTUAL_CALL(_get_loop_count, ret)) {
  55. return ret;
  56. }
  57. return 0;
  58. }
  59. float AudioStreamPlayback::get_playback_position() const {
  60. float ret;
  61. if (GDVIRTUAL_CALL(_get_playback_position, ret)) {
  62. return ret;
  63. }
  64. ERR_FAIL_V_MSG(0, "AudioStreamPlayback::get_playback_position unimplemented!");
  65. }
  66. void AudioStreamPlayback::seek(float p_time) {
  67. if (GDVIRTUAL_CALL(_seek, p_time)) {
  68. return;
  69. }
  70. }
  71. int AudioStreamPlayback::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
  72. int ret;
  73. if (GDVIRTUAL_REQUIRED_CALL(_mix, p_buffer, p_rate_scale, p_frames, ret)) {
  74. return ret;
  75. }
  76. return 0;
  77. }
  78. void AudioStreamPlayback::tag_used_streams() {
  79. GDVIRTUAL_CALL(_tag_used_streams);
  80. }
  81. void AudioStreamPlayback::_bind_methods() {
  82. GDVIRTUAL_BIND(_start, "from_pos")
  83. GDVIRTUAL_BIND(_stop)
  84. GDVIRTUAL_BIND(_is_playing)
  85. GDVIRTUAL_BIND(_get_loop_count)
  86. GDVIRTUAL_BIND(_get_playback_position)
  87. GDVIRTUAL_BIND(_seek, "position")
  88. GDVIRTUAL_BIND(_mix, "buffer", "rate_scale", "frames");
  89. GDVIRTUAL_BIND(_tag_used_streams);
  90. }
  91. //////////////////////////////
  92. void AudioStreamPlaybackResampled::begin_resample() {
  93. //clear cubic interpolation history
  94. internal_buffer[0] = AudioFrame(0.0, 0.0);
  95. internal_buffer[1] = AudioFrame(0.0, 0.0);
  96. internal_buffer[2] = AudioFrame(0.0, 0.0);
  97. internal_buffer[3] = AudioFrame(0.0, 0.0);
  98. //mix buffer
  99. _mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
  100. mix_offset = 0;
  101. }
  102. int AudioStreamPlaybackResampled::_mix_internal(AudioFrame *p_buffer, int p_frames) {
  103. int ret;
  104. if (GDVIRTUAL_REQUIRED_CALL(_mix_resampled, p_buffer, p_frames, ret)) {
  105. return ret;
  106. }
  107. return 0;
  108. }
  109. float AudioStreamPlaybackResampled::get_stream_sampling_rate() {
  110. float ret;
  111. if (GDVIRTUAL_REQUIRED_CALL(_get_stream_sampling_rate, ret)) {
  112. return ret;
  113. }
  114. return 0;
  115. }
  116. void AudioStreamPlaybackResampled::_bind_methods() {
  117. ClassDB::bind_method(D_METHOD("begin_resample"), &AudioStreamPlaybackResampled::begin_resample);
  118. GDVIRTUAL_BIND(_mix_resampled, "dst_buffer", "frame_count");
  119. GDVIRTUAL_BIND(_get_stream_sampling_rate);
  120. }
  121. int AudioStreamPlaybackResampled::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
  122. float target_rate = AudioServer::get_singleton()->get_mix_rate();
  123. float playback_speed_scale = AudioServer::get_singleton()->get_playback_speed_scale();
  124. uint64_t mix_increment = uint64_t(((get_stream_sampling_rate() * p_rate_scale * playback_speed_scale) / double(target_rate)) * double(FP_LEN));
  125. int mixed_frames_total = -1;
  126. int i;
  127. for (i = 0; i < p_frames; i++) {
  128. uint32_t idx = CUBIC_INTERP_HISTORY + uint32_t(mix_offset >> FP_BITS);
  129. //standard cubic interpolation (great quality/performance ratio)
  130. //this used to be moved to a LUT for greater performance, but nowadays CPU speed is generally faster than memory.
  131. float mu = (mix_offset & FP_MASK) / float(FP_LEN);
  132. AudioFrame y0 = internal_buffer[idx - 3];
  133. AudioFrame y1 = internal_buffer[idx - 2];
  134. AudioFrame y2 = internal_buffer[idx - 1];
  135. AudioFrame y3 = internal_buffer[idx - 0];
  136. if (idx >= internal_buffer_end && mixed_frames_total == -1) {
  137. // The internal buffer ends somewhere in this range, and we haven't yet recorded the number of good frames we have.
  138. mixed_frames_total = i;
  139. }
  140. float mu2 = mu * mu;
  141. AudioFrame a0 = 3 * y1 - 3 * y2 + y3 - y0;
  142. AudioFrame a1 = 2 * y0 - 5 * y1 + 4 * y2 - y3;
  143. AudioFrame a2 = y2 - y0;
  144. AudioFrame a3 = 2 * y1;
  145. p_buffer[i] = (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3) / 2;
  146. mix_offset += mix_increment;
  147. while ((mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN) {
  148. internal_buffer[0] = internal_buffer[INTERNAL_BUFFER_LEN + 0];
  149. internal_buffer[1] = internal_buffer[INTERNAL_BUFFER_LEN + 1];
  150. internal_buffer[2] = internal_buffer[INTERNAL_BUFFER_LEN + 2];
  151. internal_buffer[3] = internal_buffer[INTERNAL_BUFFER_LEN + 3];
  152. int mixed_frames = _mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
  153. if (mixed_frames != INTERNAL_BUFFER_LEN) {
  154. // internal_buffer[mixed_frames] is the first frame of silence.
  155. internal_buffer_end = mixed_frames;
  156. } else {
  157. // The internal buffer does not contain the first frame of silence.
  158. internal_buffer_end = -1;
  159. }
  160. mix_offset -= (INTERNAL_BUFFER_LEN << FP_BITS);
  161. }
  162. }
  163. if (mixed_frames_total == -1 && i == p_frames) {
  164. mixed_frames_total = p_frames;
  165. }
  166. return mixed_frames_total;
  167. }
  168. ////////////////////////////////
  169. Ref<AudioStreamPlayback> AudioStream::instantiate_playback() {
  170. Ref<AudioStreamPlayback> ret;
  171. if (GDVIRTUAL_CALL(_instantiate_playback, ret)) {
  172. return ret;
  173. }
  174. ERR_FAIL_V_MSG(Ref<AudioStreamPlayback>(), "Method must be implemented!");
  175. }
  176. String AudioStream::get_stream_name() const {
  177. String ret;
  178. if (GDVIRTUAL_CALL(_get_stream_name, ret)) {
  179. return ret;
  180. }
  181. return String();
  182. }
  183. float AudioStream::get_length() const {
  184. float ret;
  185. if (GDVIRTUAL_CALL(_get_length, ret)) {
  186. return ret;
  187. }
  188. return 0;
  189. }
  190. bool AudioStream::is_monophonic() const {
  191. bool ret;
  192. if (GDVIRTUAL_CALL(_is_monophonic, ret)) {
  193. return ret;
  194. }
  195. return true;
  196. }
  197. double AudioStream::get_bpm() const {
  198. double ret = 0;
  199. if (GDVIRTUAL_CALL(_get_bpm, ret)) {
  200. return ret;
  201. }
  202. return 0;
  203. }
  204. bool AudioStream::has_loop() const {
  205. bool ret = 0;
  206. if (GDVIRTUAL_CALL(_has_loop, ret)) {
  207. return ret;
  208. }
  209. return 0;
  210. }
  211. int AudioStream::get_bar_beats() const {
  212. int ret = 0;
  213. if (GDVIRTUAL_CALL(_get_bar_beats, ret)) {
  214. return ret;
  215. }
  216. return 0;
  217. }
  218. int AudioStream::get_beat_count() const {
  219. int ret = 0;
  220. if (GDVIRTUAL_CALL(_get_beat_count, ret)) {
  221. return ret;
  222. }
  223. return 0;
  224. }
  225. void AudioStream::tag_used(float p_offset) {
  226. if (tagged_frame != AudioServer::get_singleton()->get_mixed_frames()) {
  227. offset_count = 0;
  228. tagged_frame = AudioServer::get_singleton()->get_mixed_frames();
  229. }
  230. if (offset_count < MAX_TAGGED_OFFSETS) {
  231. tagged_offsets[offset_count++] = p_offset;
  232. }
  233. }
  234. uint64_t AudioStream::get_tagged_frame() const {
  235. return tagged_frame;
  236. }
  237. uint32_t AudioStream::get_tagged_frame_count() const {
  238. return offset_count;
  239. }
  240. float AudioStream::get_tagged_frame_offset(int p_index) const {
  241. ERR_FAIL_INDEX_V(p_index, MAX_TAGGED_OFFSETS, 0);
  242. return tagged_offsets[p_index];
  243. }
  244. void AudioStream::_bind_methods() {
  245. ClassDB::bind_method(D_METHOD("get_length"), &AudioStream::get_length);
  246. ClassDB::bind_method(D_METHOD("is_monophonic"), &AudioStream::is_monophonic);
  247. ClassDB::bind_method(D_METHOD("instantiate_playback"), &AudioStream::instantiate_playback);
  248. GDVIRTUAL_BIND(_instantiate_playback);
  249. GDVIRTUAL_BIND(_get_stream_name);
  250. GDVIRTUAL_BIND(_get_length);
  251. GDVIRTUAL_BIND(_is_monophonic);
  252. GDVIRTUAL_BIND(_get_bpm)
  253. GDVIRTUAL_BIND(_get_beat_count)
  254. }
  255. ////////////////////////////////
  256. Ref<AudioStreamPlayback> AudioStreamMicrophone::instantiate_playback() {
  257. Ref<AudioStreamPlaybackMicrophone> playback;
  258. playback.instantiate();
  259. playbacks.insert(playback.ptr());
  260. playback->microphone = Ref<AudioStreamMicrophone>((AudioStreamMicrophone *)this);
  261. playback->active = false;
  262. return playback;
  263. }
  264. String AudioStreamMicrophone::get_stream_name() const {
  265. //if (audio_stream.is_valid()) {
  266. //return "Random: " + audio_stream->get_name();
  267. //}
  268. return "Microphone";
  269. }
  270. float AudioStreamMicrophone::get_length() const {
  271. return 0;
  272. }
  273. bool AudioStreamMicrophone::is_monophonic() const {
  274. return true;
  275. }
  276. void AudioStreamMicrophone::_bind_methods() {
  277. }
  278. AudioStreamMicrophone::AudioStreamMicrophone() {
  279. }
  280. int AudioStreamPlaybackMicrophone::_mix_internal(AudioFrame *p_buffer, int p_frames) {
  281. AudioDriver::get_singleton()->lock();
  282. Vector<int32_t> buf = AudioDriver::get_singleton()->get_input_buffer();
  283. unsigned int input_size = AudioDriver::get_singleton()->get_input_size();
  284. int mix_rate = AudioDriver::get_singleton()->get_mix_rate();
  285. unsigned int playback_delay = MIN(((50 * mix_rate) / 1000) * 2, buf.size() >> 1);
  286. #ifdef DEBUG_ENABLED
  287. unsigned int input_position = AudioDriver::get_singleton()->get_input_position();
  288. #endif
  289. int mixed_frames = p_frames;
  290. if (playback_delay > input_size) {
  291. for (int i = 0; i < p_frames; i++) {
  292. p_buffer[i] = AudioFrame(0.0f, 0.0f);
  293. }
  294. input_ofs = 0;
  295. } else {
  296. for (int i = 0; i < p_frames; i++) {
  297. if (input_size > input_ofs && (int)input_ofs < buf.size()) {
  298. float l = (buf[input_ofs++] >> 16) / 32768.f;
  299. if ((int)input_ofs >= buf.size()) {
  300. input_ofs = 0;
  301. }
  302. float r = (buf[input_ofs++] >> 16) / 32768.f;
  303. if ((int)input_ofs >= buf.size()) {
  304. input_ofs = 0;
  305. }
  306. p_buffer[i] = AudioFrame(l, r);
  307. } else {
  308. if (mixed_frames == p_frames) {
  309. mixed_frames = i;
  310. }
  311. p_buffer[i] = AudioFrame(0.0f, 0.0f);
  312. }
  313. }
  314. }
  315. #ifdef DEBUG_ENABLED
  316. if (input_ofs > input_position && (int)(input_ofs - input_position) < (p_frames * 2)) {
  317. print_verbose(String(get_class_name()) + " buffer underrun: input_position=" + itos(input_position) + " input_ofs=" + itos(input_ofs) + " input_size=" + itos(input_size));
  318. }
  319. #endif
  320. AudioDriver::get_singleton()->unlock();
  321. return mixed_frames;
  322. }
  323. int AudioStreamPlaybackMicrophone::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
  324. return AudioStreamPlaybackResampled::mix(p_buffer, p_rate_scale, p_frames);
  325. }
  326. float AudioStreamPlaybackMicrophone::get_stream_sampling_rate() {
  327. return AudioDriver::get_singleton()->get_mix_rate();
  328. }
  329. void AudioStreamPlaybackMicrophone::start(float p_from_pos) {
  330. if (active) {
  331. return;
  332. }
  333. if (!GLOBAL_GET("audio/driver/enable_input")) {
  334. WARN_PRINT("Need to enable Project settings > Audio > Enable Audio Input option to use capturing.");
  335. return;
  336. }
  337. input_ofs = 0;
  338. if (AudioDriver::get_singleton()->capture_start() == OK) {
  339. active = true;
  340. begin_resample();
  341. }
  342. }
  343. void AudioStreamPlaybackMicrophone::stop() {
  344. if (active) {
  345. AudioDriver::get_singleton()->capture_stop();
  346. active = false;
  347. }
  348. }
  349. bool AudioStreamPlaybackMicrophone::is_playing() const {
  350. return active;
  351. }
  352. int AudioStreamPlaybackMicrophone::get_loop_count() const {
  353. return 0;
  354. }
  355. float AudioStreamPlaybackMicrophone::get_playback_position() const {
  356. return 0;
  357. }
  358. void AudioStreamPlaybackMicrophone::seek(float p_time) {
  359. // Can't seek a microphone input
  360. }
  361. void AudioStreamPlaybackMicrophone::tag_used_streams() {
  362. microphone->tag_used(0);
  363. }
  364. AudioStreamPlaybackMicrophone::~AudioStreamPlaybackMicrophone() {
  365. microphone->playbacks.erase(this);
  366. stop();
  367. }
  368. AudioStreamPlaybackMicrophone::AudioStreamPlaybackMicrophone() {
  369. }
  370. ////////////////////////////////
  371. void AudioStreamRandomizer::add_stream(int p_index) {
  372. if (p_index < 0) {
  373. p_index = audio_stream_pool.size();
  374. }
  375. ERR_FAIL_COND(p_index > audio_stream_pool.size());
  376. PoolEntry entry{ nullptr, 1.0f };
  377. audio_stream_pool.insert(p_index, entry);
  378. emit_signal(SNAME("changed"));
  379. notify_property_list_changed();
  380. }
  381. // p_index_to is relative to the array prior to the removal of from.
  382. // Example: [0, 1, 2, 3], move(1, 3) => [0, 2, 1, 3]
  383. void AudioStreamRandomizer::move_stream(int p_index_from, int p_index_to) {
  384. ERR_FAIL_INDEX(p_index_from, audio_stream_pool.size());
  385. // p_index_to == audio_stream_pool.size() is valid (move to end).
  386. ERR_FAIL_COND(p_index_to < 0);
  387. ERR_FAIL_COND(p_index_to > audio_stream_pool.size());
  388. audio_stream_pool.insert(p_index_to, audio_stream_pool[p_index_from]);
  389. // If 'from' is strictly after 'to' we need to increment the index by one because of the insertion.
  390. if (p_index_from > p_index_to) {
  391. p_index_from++;
  392. }
  393. audio_stream_pool.remove_at(p_index_from);
  394. emit_signal(SNAME("changed"));
  395. notify_property_list_changed();
  396. }
  397. void AudioStreamRandomizer::remove_stream(int p_index) {
  398. ERR_FAIL_INDEX(p_index, audio_stream_pool.size());
  399. audio_stream_pool.remove_at(p_index);
  400. emit_signal(SNAME("changed"));
  401. notify_property_list_changed();
  402. }
  403. void AudioStreamRandomizer::set_stream(int p_index, Ref<AudioStream> p_stream) {
  404. ERR_FAIL_INDEX(p_index, audio_stream_pool.size());
  405. audio_stream_pool.write[p_index].stream = p_stream;
  406. emit_signal(SNAME("changed"));
  407. }
  408. Ref<AudioStream> AudioStreamRandomizer::get_stream(int p_index) const {
  409. ERR_FAIL_INDEX_V(p_index, audio_stream_pool.size(), nullptr);
  410. return audio_stream_pool[p_index].stream;
  411. }
  412. void AudioStreamRandomizer::set_stream_probability_weight(int p_index, float p_weight) {
  413. ERR_FAIL_INDEX(p_index, audio_stream_pool.size());
  414. audio_stream_pool.write[p_index].weight = p_weight;
  415. emit_signal(SNAME("changed"));
  416. }
  417. float AudioStreamRandomizer::get_stream_probability_weight(int p_index) const {
  418. ERR_FAIL_INDEX_V(p_index, audio_stream_pool.size(), 0);
  419. return audio_stream_pool[p_index].weight;
  420. }
  421. void AudioStreamRandomizer::set_streams_count(int p_count) {
  422. audio_stream_pool.resize(p_count);
  423. }
  424. int AudioStreamRandomizer::get_streams_count() const {
  425. return audio_stream_pool.size();
  426. }
  427. void AudioStreamRandomizer::set_random_pitch(float p_pitch) {
  428. if (p_pitch < 1) {
  429. p_pitch = 1;
  430. }
  431. random_pitch_scale = p_pitch;
  432. }
  433. float AudioStreamRandomizer::get_random_pitch() const {
  434. return random_pitch_scale;
  435. }
  436. void AudioStreamRandomizer::set_random_volume_offset_db(float p_volume_offset_db) {
  437. if (p_volume_offset_db < 0) {
  438. p_volume_offset_db = 0;
  439. }
  440. random_volume_offset_db = p_volume_offset_db;
  441. }
  442. float AudioStreamRandomizer::get_random_volume_offset_db() const {
  443. return random_volume_offset_db;
  444. }
  445. void AudioStreamRandomizer::set_playback_mode(PlaybackMode p_playback_mode) {
  446. playback_mode = p_playback_mode;
  447. }
  448. AudioStreamRandomizer::PlaybackMode AudioStreamRandomizer::get_playback_mode() const {
  449. return playback_mode;
  450. }
  451. Ref<AudioStreamPlayback> AudioStreamRandomizer::instance_playback_random() {
  452. Ref<AudioStreamPlaybackRandomizer> playback;
  453. playback.instantiate();
  454. playbacks.insert(playback.ptr());
  455. playback->randomizer = Ref<AudioStreamRandomizer>((AudioStreamRandomizer *)this);
  456. double total_weight = 0;
  457. Vector<PoolEntry> local_pool;
  458. for (const PoolEntry &entry : audio_stream_pool) {
  459. if (entry.stream.is_valid() && entry.weight > 0) {
  460. local_pool.push_back(entry);
  461. total_weight += entry.weight;
  462. }
  463. }
  464. if (local_pool.is_empty()) {
  465. return playback;
  466. }
  467. double chosen_cumulative_weight = Math::random(0.0, total_weight);
  468. double cumulative_weight = 0;
  469. for (PoolEntry &entry : local_pool) {
  470. cumulative_weight += entry.weight;
  471. if (cumulative_weight > chosen_cumulative_weight) {
  472. playback->playback = entry.stream->instantiate_playback();
  473. last_playback = entry.stream;
  474. break;
  475. }
  476. }
  477. if (playback->playback.is_null()) {
  478. // This indicates a floating point error. Take the last element.
  479. last_playback = local_pool[local_pool.size() - 1].stream;
  480. playback->playback = local_pool.write[local_pool.size() - 1].stream->instantiate_playback();
  481. }
  482. return playback;
  483. }
  484. Ref<AudioStreamPlayback> AudioStreamRandomizer::instance_playback_no_repeats() {
  485. Ref<AudioStreamPlaybackRandomizer> playback;
  486. double total_weight = 0;
  487. Vector<PoolEntry> local_pool;
  488. for (const PoolEntry &entry : audio_stream_pool) {
  489. if (entry.stream == last_playback) {
  490. continue;
  491. }
  492. if (entry.stream.is_valid() && entry.weight > 0) {
  493. local_pool.push_back(entry);
  494. total_weight += entry.weight;
  495. }
  496. }
  497. if (local_pool.is_empty()) {
  498. playback = instance_playback_random();
  499. WARN_PRINT("Playback stream pool is too small to prevent repeats.");
  500. return playback;
  501. }
  502. playback.instantiate();
  503. playbacks.insert(playback.ptr());
  504. playback->randomizer = Ref<AudioStreamRandomizer>((AudioStreamRandomizer *)this);
  505. double chosen_cumulative_weight = Math::random(0.0, total_weight);
  506. double cumulative_weight = 0;
  507. for (PoolEntry &entry : local_pool) {
  508. cumulative_weight += entry.weight;
  509. if (cumulative_weight > chosen_cumulative_weight) {
  510. last_playback = entry.stream;
  511. playback->playback = entry.stream->instantiate_playback();
  512. break;
  513. }
  514. }
  515. if (playback->playback.is_null()) {
  516. // This indicates a floating point error. Take the last element.
  517. last_playback = local_pool[local_pool.size() - 1].stream;
  518. playback->playback = local_pool.write[local_pool.size() - 1].stream->instantiate_playback();
  519. }
  520. return playback;
  521. }
  522. Ref<AudioStreamPlayback> AudioStreamRandomizer::instance_playback_sequential() {
  523. Ref<AudioStreamPlaybackRandomizer> playback;
  524. playback.instantiate();
  525. playbacks.insert(playback.ptr());
  526. playback->randomizer = Ref<AudioStreamRandomizer>((AudioStreamRandomizer *)this);
  527. Vector<Ref<AudioStream>> local_pool;
  528. for (const PoolEntry &entry : audio_stream_pool) {
  529. if (entry.stream.is_null()) {
  530. continue;
  531. }
  532. if (local_pool.find(entry.stream) != -1) {
  533. WARN_PRINT("Duplicate stream in sequential playback pool");
  534. continue;
  535. }
  536. local_pool.push_back(entry.stream);
  537. }
  538. if (local_pool.is_empty()) {
  539. return playback;
  540. }
  541. bool found_last_stream = false;
  542. for (Ref<AudioStream> &entry : local_pool) {
  543. if (found_last_stream) {
  544. last_playback = entry;
  545. playback->playback = entry->instantiate_playback();
  546. break;
  547. }
  548. if (entry == last_playback) {
  549. found_last_stream = true;
  550. }
  551. }
  552. if (playback->playback.is_null()) {
  553. // Wrap around
  554. last_playback = local_pool[0];
  555. playback->playback = local_pool.write[0]->instantiate_playback();
  556. }
  557. return playback;
  558. }
  559. Ref<AudioStreamPlayback> AudioStreamRandomizer::instantiate_playback() {
  560. switch (playback_mode) {
  561. case PLAYBACK_RANDOM:
  562. return instance_playback_random();
  563. case PLAYBACK_RANDOM_NO_REPEATS:
  564. return instance_playback_no_repeats();
  565. case PLAYBACK_SEQUENTIAL:
  566. return instance_playback_sequential();
  567. default:
  568. ERR_FAIL_V_MSG(nullptr, "Unhandled playback mode.");
  569. }
  570. }
  571. String AudioStreamRandomizer::get_stream_name() const {
  572. return "Randomizer";
  573. }
  574. float AudioStreamRandomizer::get_length() const {
  575. return 0;
  576. }
  577. bool AudioStreamRandomizer::is_monophonic() const {
  578. for (const PoolEntry &entry : audio_stream_pool) {
  579. if (entry.stream.is_valid() && entry.stream->is_monophonic()) {
  580. return true;
  581. }
  582. }
  583. return false;
  584. }
  585. bool AudioStreamRandomizer::_get(const StringName &p_name, Variant &r_ret) const {
  586. if (AudioStream::_get(p_name, r_ret)) {
  587. return true;
  588. }
  589. Vector<String> components = String(p_name).split("/", true, 2);
  590. if (components.size() == 2 && components[0].begins_with("stream_") && components[0].trim_prefix("stream_").is_valid_int()) {
  591. int index = components[0].trim_prefix("stream_").to_int();
  592. if (index < 0 || index >= (int)audio_stream_pool.size()) {
  593. return false;
  594. }
  595. if (components[1] == "stream") {
  596. r_ret = get_stream(index);
  597. return true;
  598. } else if (components[1] == "weight") {
  599. r_ret = get_stream_probability_weight(index);
  600. return true;
  601. } else {
  602. return false;
  603. }
  604. }
  605. return false;
  606. }
  607. bool AudioStreamRandomizer::_set(const StringName &p_name, const Variant &p_value) {
  608. if (AudioStream::_set(p_name, p_value)) {
  609. return true;
  610. }
  611. Vector<String> components = String(p_name).split("/", true, 2);
  612. if (components.size() == 2 && components[0].begins_with("stream_") && components[0].trim_prefix("stream_").is_valid_int()) {
  613. int index = components[0].trim_prefix("stream_").to_int();
  614. if (index < 0 || index >= (int)audio_stream_pool.size()) {
  615. return false;
  616. }
  617. if (components[1] == "stream") {
  618. set_stream(index, p_value);
  619. return true;
  620. } else if (components[1] == "weight") {
  621. set_stream_probability_weight(index, p_value);
  622. return true;
  623. } else {
  624. return false;
  625. }
  626. }
  627. return false;
  628. }
  629. void AudioStreamRandomizer::_get_property_list(List<PropertyInfo> *p_list) const {
  630. AudioStream::_get_property_list(p_list); // Define the trivial scalar properties.
  631. p_list->push_back(PropertyInfo(Variant::NIL, "Streams", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_GROUP));
  632. for (int i = 0; i < audio_stream_pool.size(); i++) {
  633. p_list->push_back(PropertyInfo(Variant::OBJECT, vformat("stream_%d/stream", i), PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"));
  634. p_list->push_back(PropertyInfo(Variant::FLOAT, vformat("stream_%d/weight", i), PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"));
  635. }
  636. }
  637. void AudioStreamRandomizer::_bind_methods() {
  638. ClassDB::bind_method(D_METHOD("add_stream", "index"), &AudioStreamRandomizer::add_stream);
  639. ClassDB::bind_method(D_METHOD("move_stream", "index_from", "index_to"), &AudioStreamRandomizer::move_stream);
  640. ClassDB::bind_method(D_METHOD("remove_stream", "index"), &AudioStreamRandomizer::remove_stream);
  641. ClassDB::bind_method(D_METHOD("set_stream", "index", "stream"), &AudioStreamRandomizer::set_stream);
  642. ClassDB::bind_method(D_METHOD("get_stream", "index"), &AudioStreamRandomizer::get_stream);
  643. ClassDB::bind_method(D_METHOD("set_stream_probability_weight", "index", "weight"), &AudioStreamRandomizer::set_stream_probability_weight);
  644. ClassDB::bind_method(D_METHOD("get_stream_probability_weight", "index"), &AudioStreamRandomizer::get_stream_probability_weight);
  645. ClassDB::bind_method(D_METHOD("set_streams_count", "count"), &AudioStreamRandomizer::set_streams_count);
  646. ClassDB::bind_method(D_METHOD("get_streams_count"), &AudioStreamRandomizer::get_streams_count);
  647. ClassDB::bind_method(D_METHOD("set_random_pitch", "scale"), &AudioStreamRandomizer::set_random_pitch);
  648. ClassDB::bind_method(D_METHOD("get_random_pitch"), &AudioStreamRandomizer::get_random_pitch);
  649. ClassDB::bind_method(D_METHOD("set_random_volume_offset_db", "db_offset"), &AudioStreamRandomizer::set_random_volume_offset_db);
  650. ClassDB::bind_method(D_METHOD("get_random_volume_offset_db"), &AudioStreamRandomizer::get_random_volume_offset_db);
  651. ClassDB::bind_method(D_METHOD("set_playback_mode", "mode"), &AudioStreamRandomizer::set_playback_mode);
  652. ClassDB::bind_method(D_METHOD("get_playback_mode"), &AudioStreamRandomizer::get_playback_mode);
  653. ADD_ARRAY("streams", "stream_");
  654. ADD_PROPERTY(PropertyInfo(Variant::INT, "streams_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_streams_count", "get_streams_count");
  655. ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_mode", PROPERTY_HINT_ENUM, "Random (Avoid Repeats),Random,Sequential"), "set_playback_mode", "get_playback_mode");
  656. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "random_pitch", PROPERTY_HINT_RANGE, "1,16,0.01"), "set_random_pitch", "get_random_pitch");
  657. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "random_volume_offset_db", PROPERTY_HINT_RANGE, "0,40,0.01,suffix:dB"), "set_random_volume_offset_db", "get_random_volume_offset_db");
  658. BIND_ENUM_CONSTANT(PLAYBACK_RANDOM_NO_REPEATS);
  659. BIND_ENUM_CONSTANT(PLAYBACK_RANDOM);
  660. BIND_ENUM_CONSTANT(PLAYBACK_SEQUENTIAL);
  661. }
  662. AudioStreamRandomizer::AudioStreamRandomizer() {}
  663. void AudioStreamPlaybackRandomizer::start(float p_from_pos) {
  664. playing = playback;
  665. {
  666. float range_from = 1.0 / randomizer->random_pitch_scale;
  667. float range_to = randomizer->random_pitch_scale;
  668. pitch_scale = range_from + Math::randf() * (range_to - range_from);
  669. }
  670. {
  671. float range_from = -randomizer->random_volume_offset_db;
  672. float range_to = randomizer->random_volume_offset_db;
  673. float volume_offset_db = range_from + Math::randf() * (range_to - range_from);
  674. volume_scale = Math::db_to_linear(volume_offset_db);
  675. }
  676. if (playing.is_valid()) {
  677. playing->start(p_from_pos);
  678. }
  679. }
  680. void AudioStreamPlaybackRandomizer::stop() {
  681. if (playing.is_valid()) {
  682. playing->stop();
  683. }
  684. }
  685. bool AudioStreamPlaybackRandomizer::is_playing() const {
  686. if (playing.is_valid()) {
  687. return playing->is_playing();
  688. }
  689. return false;
  690. }
  691. int AudioStreamPlaybackRandomizer::get_loop_count() const {
  692. if (playing.is_valid()) {
  693. return playing->get_loop_count();
  694. }
  695. return 0;
  696. }
  697. float AudioStreamPlaybackRandomizer::get_playback_position() const {
  698. if (playing.is_valid()) {
  699. return playing->get_playback_position();
  700. }
  701. return 0;
  702. }
  703. void AudioStreamPlaybackRandomizer::seek(float p_time) {
  704. if (playing.is_valid()) {
  705. playing->seek(p_time);
  706. }
  707. }
  708. void AudioStreamPlaybackRandomizer::tag_used_streams() {
  709. Ref<AudioStreamPlayback> p = playing; // Thread safety
  710. if (p.is_valid()) {
  711. p->tag_used_streams();
  712. }
  713. randomizer->tag_used(0);
  714. }
  715. int AudioStreamPlaybackRandomizer::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
  716. if (playing.is_valid()) {
  717. return playing->mix(p_buffer, p_rate_scale * pitch_scale, p_frames);
  718. } else {
  719. for (int i = 0; i < p_frames; i++) {
  720. p_buffer[i] = AudioFrame(0, 0);
  721. }
  722. return p_frames;
  723. }
  724. }
  725. AudioStreamPlaybackRandomizer::~AudioStreamPlaybackRandomizer() {
  726. randomizer->playbacks.erase(this);
  727. }
  728. /////////////////////////////////////////////