audio_stream.cpp 26 KB

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