Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/servers/audio/audio_stream.cpp
11352 views
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
if (!GLOBAL_GET_CACHED(bool, "audio/driver/enable_input")) {
446
WARN_PRINT("You must enable the project setting \"audio/driver/enable_input\" to use audio capture.");
447
return;
448
}
449
450
input_ofs = 0;
451
452
if (AudioDriver::get_singleton()->input_start() == OK) {
453
active = true;
454
begin_resample();
455
}
456
}
457
458
void AudioStreamPlaybackMicrophone::stop() {
459
if (active) {
460
AudioDriver::get_singleton()->input_stop();
461
active = false;
462
}
463
}
464
465
bool AudioStreamPlaybackMicrophone::is_playing() const {
466
return active;
467
}
468
469
int AudioStreamPlaybackMicrophone::get_loop_count() const {
470
return 0;
471
}
472
473
double AudioStreamPlaybackMicrophone::get_playback_position() const {
474
return 0;
475
}
476
477
void AudioStreamPlaybackMicrophone::seek(double p_time) {
478
// Can't seek a microphone input
479
}
480
481
void AudioStreamPlaybackMicrophone::tag_used_streams() {
482
microphone->tag_used(0);
483
}
484
485
AudioStreamPlaybackMicrophone::~AudioStreamPlaybackMicrophone() {
486
microphone->playbacks.erase(this);
487
stop();
488
}
489
490
AudioStreamPlaybackMicrophone::AudioStreamPlaybackMicrophone() {
491
}
492
493
////////////////////////////////
494
495
void AudioStreamRandomizer::add_stream(int p_index, Ref<AudioStream> p_stream, float p_weight) {
496
if (p_index < 0) {
497
p_index = audio_stream_pool.size();
498
}
499
ERR_FAIL_COND(p_index > audio_stream_pool.size());
500
PoolEntry entry{ p_stream, p_weight };
501
audio_stream_pool.insert(p_index, entry);
502
emit_signal(CoreStringName(changed));
503
notify_property_list_changed();
504
}
505
506
// p_index_to is relative to the array prior to the removal of from.
507
// Example: [0, 1, 2, 3], move(1, 3) => [0, 2, 1, 3]
508
void AudioStreamRandomizer::move_stream(int p_index_from, int p_index_to) {
509
ERR_FAIL_INDEX(p_index_from, audio_stream_pool.size());
510
// p_index_to == audio_stream_pool.size() is valid (move to end).
511
ERR_FAIL_COND(p_index_to < 0);
512
ERR_FAIL_COND(p_index_to > audio_stream_pool.size());
513
audio_stream_pool.insert(p_index_to, audio_stream_pool[p_index_from]);
514
// If 'from' is strictly after 'to' we need to increment the index by one because of the insertion.
515
if (p_index_from > p_index_to) {
516
p_index_from++;
517
}
518
audio_stream_pool.remove_at(p_index_from);
519
emit_signal(CoreStringName(changed));
520
notify_property_list_changed();
521
}
522
523
void AudioStreamRandomizer::remove_stream(int p_index) {
524
ERR_FAIL_INDEX(p_index, audio_stream_pool.size());
525
audio_stream_pool.remove_at(p_index);
526
emit_signal(CoreStringName(changed));
527
notify_property_list_changed();
528
}
529
530
void AudioStreamRandomizer::set_stream(int p_index, Ref<AudioStream> p_stream) {
531
ERR_FAIL_INDEX(p_index, audio_stream_pool.size());
532
audio_stream_pool.write[p_index].stream = p_stream;
533
emit_signal(CoreStringName(changed));
534
}
535
536
Ref<AudioStream> AudioStreamRandomizer::get_stream(int p_index) const {
537
ERR_FAIL_INDEX_V(p_index, audio_stream_pool.size(), nullptr);
538
return audio_stream_pool[p_index].stream;
539
}
540
541
void AudioStreamRandomizer::set_stream_probability_weight(int p_index, float p_weight) {
542
ERR_FAIL_INDEX(p_index, audio_stream_pool.size());
543
audio_stream_pool.write[p_index].weight = p_weight;
544
emit_signal(CoreStringName(changed));
545
}
546
547
float AudioStreamRandomizer::get_stream_probability_weight(int p_index) const {
548
ERR_FAIL_INDEX_V(p_index, audio_stream_pool.size(), 0);
549
return audio_stream_pool[p_index].weight;
550
}
551
552
void AudioStreamRandomizer::set_streams_count(int p_count) {
553
audio_stream_pool.resize(p_count);
554
}
555
556
int AudioStreamRandomizer::get_streams_count() const {
557
return audio_stream_pool.size();
558
}
559
560
void AudioStreamRandomizer::set_random_pitch(float p_pitch) {
561
if (p_pitch < 1) {
562
p_pitch = 1;
563
}
564
random_pitch_scale = p_pitch;
565
}
566
567
float AudioStreamRandomizer::get_random_pitch() const {
568
return random_pitch_scale;
569
}
570
571
void AudioStreamRandomizer::set_random_volume_offset_db(float p_volume_offset_db) {
572
if (p_volume_offset_db < 0) {
573
p_volume_offset_db = 0;
574
}
575
random_volume_offset_db = p_volume_offset_db;
576
}
577
578
float AudioStreamRandomizer::get_random_volume_offset_db() const {
579
return random_volume_offset_db;
580
}
581
582
void AudioStreamRandomizer::set_playback_mode(PlaybackMode p_playback_mode) {
583
playback_mode = p_playback_mode;
584
}
585
586
AudioStreamRandomizer::PlaybackMode AudioStreamRandomizer::get_playback_mode() const {
587
return playback_mode;
588
}
589
590
Ref<AudioStreamPlayback> AudioStreamRandomizer::instance_playback_random() {
591
Ref<AudioStreamPlaybackRandomizer> playback;
592
playback.instantiate();
593
playbacks.insert(playback.ptr());
594
playback->randomizer = Ref<AudioStreamRandomizer>((AudioStreamRandomizer *)this);
595
596
double total_weight = 0;
597
Vector<PoolEntry> local_pool;
598
for (const PoolEntry &entry : audio_stream_pool) {
599
if (entry.stream.is_valid() && entry.weight > 0) {
600
local_pool.push_back(entry);
601
total_weight += entry.weight;
602
}
603
}
604
if (local_pool.is_empty()) {
605
return playback;
606
}
607
double chosen_cumulative_weight = Math::random(0.0, total_weight);
608
double cumulative_weight = 0;
609
for (PoolEntry &entry : local_pool) {
610
cumulative_weight += entry.weight;
611
if (cumulative_weight > chosen_cumulative_weight) {
612
playback->playback = entry.stream->instantiate_playback();
613
last_playback = entry.stream;
614
break;
615
}
616
}
617
if (playback->playback.is_null()) {
618
// This indicates a floating point error. Take the last element.
619
last_playback = local_pool[local_pool.size() - 1].stream;
620
playback->playback = local_pool.write[local_pool.size() - 1].stream->instantiate_playback();
621
}
622
return playback;
623
}
624
625
Ref<AudioStreamPlayback> AudioStreamRandomizer::instance_playback_no_repeats() {
626
Ref<AudioStreamPlaybackRandomizer> playback;
627
628
double total_weight = 0;
629
Vector<PoolEntry> local_pool;
630
for (const PoolEntry &entry : audio_stream_pool) {
631
if (entry.stream == last_playback) {
632
continue;
633
}
634
if (entry.stream.is_valid() && entry.weight > 0) {
635
local_pool.push_back(entry);
636
total_weight += entry.weight;
637
}
638
}
639
if (local_pool.is_empty()) {
640
// There is only one sound to choose from.
641
// Always play a random sound while allowing repeats (which always plays the same sound).
642
playback = instance_playback_random();
643
return playback;
644
}
645
646
playback.instantiate();
647
playbacks.insert(playback.ptr());
648
playback->randomizer = Ref<AudioStreamRandomizer>((AudioStreamRandomizer *)this);
649
double chosen_cumulative_weight = Math::random(0.0, total_weight);
650
double cumulative_weight = 0;
651
for (PoolEntry &entry : local_pool) {
652
cumulative_weight += entry.weight;
653
if (cumulative_weight > chosen_cumulative_weight) {
654
last_playback = entry.stream;
655
playback->playback = entry.stream->instantiate_playback();
656
break;
657
}
658
}
659
if (playback->playback.is_null()) {
660
// This indicates a floating point error. Take the last element.
661
last_playback = local_pool[local_pool.size() - 1].stream;
662
playback->playback = local_pool.write[local_pool.size() - 1].stream->instantiate_playback();
663
}
664
return playback;
665
}
666
667
Ref<AudioStreamPlayback> AudioStreamRandomizer::instance_playback_sequential() {
668
Ref<AudioStreamPlaybackRandomizer> playback;
669
playback.instantiate();
670
playbacks.insert(playback.ptr());
671
playback->randomizer = Ref<AudioStreamRandomizer>((AudioStreamRandomizer *)this);
672
673
Vector<Ref<AudioStream>> local_pool;
674
for (const PoolEntry &entry : audio_stream_pool) {
675
if (entry.stream.is_null()) {
676
continue;
677
}
678
if (local_pool.has(entry.stream)) {
679
WARN_PRINT("Duplicate stream in sequential playback pool");
680
continue;
681
}
682
local_pool.push_back(entry.stream);
683
}
684
if (local_pool.is_empty()) {
685
return playback;
686
}
687
bool found_last_stream = false;
688
for (Ref<AudioStream> &entry : local_pool) {
689
if (found_last_stream) {
690
last_playback = entry;
691
playback->playback = entry->instantiate_playback();
692
break;
693
}
694
if (entry == last_playback) {
695
found_last_stream = true;
696
}
697
}
698
if (playback->playback.is_null()) {
699
// Wrap around
700
last_playback = local_pool[0];
701
playback->playback = local_pool.write[0]->instantiate_playback();
702
}
703
return playback;
704
}
705
706
Ref<AudioStreamPlayback> AudioStreamRandomizer::instantiate_playback() {
707
switch (playback_mode) {
708
case PLAYBACK_RANDOM:
709
return instance_playback_random();
710
case PLAYBACK_RANDOM_NO_REPEATS:
711
return instance_playback_no_repeats();
712
case PLAYBACK_SEQUENTIAL:
713
return instance_playback_sequential();
714
default:
715
ERR_FAIL_V_MSG(nullptr, "Unhandled playback mode.");
716
}
717
}
718
719
String AudioStreamRandomizer::get_stream_name() const {
720
return "Randomizer";
721
}
722
723
double AudioStreamRandomizer::get_length() const {
724
if (!last_playback.is_valid()) {
725
return 0;
726
}
727
return last_playback->get_length();
728
}
729
730
bool AudioStreamRandomizer::is_monophonic() const {
731
for (const PoolEntry &entry : audio_stream_pool) {
732
if (entry.stream.is_valid() && entry.stream->is_monophonic()) {
733
return true;
734
}
735
}
736
return false;
737
}
738
739
void AudioStreamRandomizer::_bind_methods() {
740
ClassDB::bind_method(D_METHOD("add_stream", "index", "stream", "weight"), &AudioStreamRandomizer::add_stream, DEFVAL(1.0));
741
ClassDB::bind_method(D_METHOD("move_stream", "index_from", "index_to"), &AudioStreamRandomizer::move_stream);
742
ClassDB::bind_method(D_METHOD("remove_stream", "index"), &AudioStreamRandomizer::remove_stream);
743
744
ClassDB::bind_method(D_METHOD("set_stream", "index", "stream"), &AudioStreamRandomizer::set_stream);
745
ClassDB::bind_method(D_METHOD("get_stream", "index"), &AudioStreamRandomizer::get_stream);
746
ClassDB::bind_method(D_METHOD("set_stream_probability_weight", "index", "weight"), &AudioStreamRandomizer::set_stream_probability_weight);
747
ClassDB::bind_method(D_METHOD("get_stream_probability_weight", "index"), &AudioStreamRandomizer::get_stream_probability_weight);
748
749
ClassDB::bind_method(D_METHOD("set_streams_count", "count"), &AudioStreamRandomizer::set_streams_count);
750
ClassDB::bind_method(D_METHOD("get_streams_count"), &AudioStreamRandomizer::get_streams_count);
751
752
ClassDB::bind_method(D_METHOD("set_random_pitch", "scale"), &AudioStreamRandomizer::set_random_pitch);
753
ClassDB::bind_method(D_METHOD("get_random_pitch"), &AudioStreamRandomizer::get_random_pitch);
754
755
ClassDB::bind_method(D_METHOD("set_random_volume_offset_db", "db_offset"), &AudioStreamRandomizer::set_random_volume_offset_db);
756
ClassDB::bind_method(D_METHOD("get_random_volume_offset_db"), &AudioStreamRandomizer::get_random_volume_offset_db);
757
758
ClassDB::bind_method(D_METHOD("set_playback_mode", "mode"), &AudioStreamRandomizer::set_playback_mode);
759
ClassDB::bind_method(D_METHOD("get_playback_mode"), &AudioStreamRandomizer::get_playback_mode);
760
761
ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_mode", PROPERTY_HINT_ENUM, "Random (Avoid Repeats),Random,Sequential"), "set_playback_mode", "get_playback_mode");
762
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "random_pitch", PROPERTY_HINT_RANGE, "1,16,0.01"), "set_random_pitch", "get_random_pitch");
763
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");
764
ADD_ARRAY("streams", "stream_");
765
ADD_PROPERTY(PropertyInfo(Variant::INT, "streams_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_streams_count", "get_streams_count");
766
767
BIND_ENUM_CONSTANT(PLAYBACK_RANDOM_NO_REPEATS);
768
BIND_ENUM_CONSTANT(PLAYBACK_RANDOM);
769
BIND_ENUM_CONSTANT(PLAYBACK_SEQUENTIAL);
770
771
PoolEntry defaults;
772
773
base_property_helper.set_prefix("stream_");
774
base_property_helper.set_array_length_getter(&AudioStreamRandomizer::get_streams_count);
775
base_property_helper.register_property(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), defaults.stream, &AudioStreamRandomizer::set_stream, &AudioStreamRandomizer::get_stream);
776
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);
777
PropertyListHelper::register_base_helper(&base_property_helper);
778
}
779
780
AudioStreamRandomizer::AudioStreamRandomizer() {
781
property_helper.setup_for_instance(base_property_helper, this);
782
}
783
784
void AudioStreamPlaybackRandomizer::start(double p_from_pos) {
785
playing = playback;
786
{
787
// GH-10238 : Pitch_scale is multiplicative, so picking a random number for it without log
788
// conversion will bias it towards higher pitches (0.5 is down one octave, 2.0 is up one octave).
789
// See: https://pressbooks.pub/sound/chapter/pitch-and-frequency-in-music/
790
float range_from = Math::log(1.0f / randomizer->random_pitch_scale);
791
float range_to = Math::log(randomizer->random_pitch_scale);
792
793
pitch_scale = Math::exp(range_from + Math::randf() * (range_to - range_from));
794
}
795
{
796
float range_from = -randomizer->random_volume_offset_db;
797
float range_to = randomizer->random_volume_offset_db;
798
799
float volume_offset_db = range_from + Math::randf() * (range_to - range_from);
800
volume_scale = Math::db_to_linear(volume_offset_db);
801
}
802
803
if (playing.is_valid()) {
804
playing->start(p_from_pos);
805
}
806
}
807
808
void AudioStreamPlaybackRandomizer::stop() {
809
if (playing.is_valid()) {
810
playing->stop();
811
}
812
}
813
814
bool AudioStreamPlaybackRandomizer::is_playing() const {
815
if (playing.is_valid()) {
816
return playing->is_playing();
817
}
818
819
return false;
820
}
821
822
int AudioStreamPlaybackRandomizer::get_loop_count() const {
823
if (playing.is_valid()) {
824
return playing->get_loop_count();
825
}
826
827
return 0;
828
}
829
830
double AudioStreamPlaybackRandomizer::get_playback_position() const {
831
if (playing.is_valid()) {
832
return playing->get_playback_position();
833
}
834
835
return 0;
836
}
837
838
void AudioStreamPlaybackRandomizer::seek(double p_time) {
839
if (playing.is_valid()) {
840
playing->seek(p_time);
841
}
842
}
843
844
void AudioStreamPlaybackRandomizer::tag_used_streams() {
845
Ref<AudioStreamPlayback> p = playing; // Thread safety
846
if (p.is_valid()) {
847
p->tag_used_streams();
848
}
849
randomizer->tag_used(0);
850
}
851
852
int AudioStreamPlaybackRandomizer::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
853
if (playing.is_valid()) {
854
int mixed_samples = playing->mix(p_buffer, p_rate_scale * pitch_scale, p_frames);
855
for (int samp = 0; samp < mixed_samples; samp++) {
856
p_buffer[samp] *= volume_scale;
857
}
858
return mixed_samples;
859
} else {
860
for (int i = 0; i < p_frames; i++) {
861
p_buffer[i] = AudioFrame(0, 0);
862
}
863
return p_frames;
864
}
865
}
866
867
AudioStreamPlaybackRandomizer::~AudioStreamPlaybackRandomizer() {
868
randomizer->playbacks.erase(this);
869
}
870
/////////////////////////////////////////////
871
872