audio_stream.cpp 29 KB

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