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