audio_stream.cpp 25 KB

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