Debian Codegraph @

servers/audio/audio_stream.cpp

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