audio_stream.cpp 28 KB

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