Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/servers/audio_server.cpp
9887 views
1
/**************************************************************************/
2
/* audio_server.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_server.h"
32
33
#include "core/config/project_settings.h"
34
#include "core/debugger/engine_debugger.h"
35
#include "core/error/error_macros.h"
36
#include "core/io/resource_loader.h"
37
#include "core/math/audio_frame.h"
38
#include "core/os/os.h"
39
#include "core/string/string_name.h"
40
#include "core/templates/pair.h"
41
#include "scene/scene_string_names.h"
42
#include "servers/audio/audio_driver_dummy.h"
43
#include "servers/audio/audio_stream.h"
44
#include "servers/audio/effects/audio_effect_compressor.h"
45
46
#ifdef TOOLS_ENABLED
47
#define MARK_EDITED set_edited(true);
48
#else
49
#define MARK_EDITED
50
#endif
51
52
AudioDriver *AudioDriver::singleton = nullptr;
53
AudioDriver *AudioDriver::get_singleton() {
54
return singleton;
55
}
56
57
void AudioDriver::set_singleton() {
58
singleton = this;
59
}
60
61
void AudioDriver::audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time) {
62
if (p_update_mix_time) {
63
update_mix_time(p_frames);
64
}
65
66
if (AudioServer::get_singleton()) {
67
AudioServer::get_singleton()->_driver_process(p_frames, p_buffer);
68
}
69
}
70
71
void AudioDriver::update_mix_time(int p_frames) {
72
_last_mix_frames = p_frames;
73
if (OS::get_singleton()) {
74
_last_mix_time = OS::get_singleton()->get_ticks_usec();
75
}
76
}
77
78
double AudioDriver::get_time_since_last_mix() {
79
lock();
80
uint64_t last_mix_time = _last_mix_time;
81
unlock();
82
return (OS::get_singleton()->get_ticks_usec() - last_mix_time) / 1000000.0;
83
}
84
85
double AudioDriver::get_time_to_next_mix() {
86
lock();
87
uint64_t last_mix_time = _last_mix_time;
88
uint64_t last_mix_frames = _last_mix_frames;
89
unlock();
90
double total = (OS::get_singleton()->get_ticks_usec() - last_mix_time) / 1000000.0;
91
double mix_buffer = last_mix_frames / (double)get_mix_rate();
92
return mix_buffer - total;
93
}
94
95
void AudioDriver::input_buffer_init(int driver_buffer_frames) {
96
const int input_buffer_channels = 2;
97
input_buffer.resize(driver_buffer_frames * input_buffer_channels * 4);
98
input_position = 0;
99
input_size = 0;
100
}
101
102
void AudioDriver::input_buffer_write(int32_t sample) {
103
if ((int)input_position < input_buffer.size()) {
104
input_buffer.write[input_position++] = sample;
105
if ((int)input_position >= input_buffer.size()) {
106
input_position = 0;
107
}
108
if ((int)input_size < input_buffer.size()) {
109
input_size++;
110
}
111
} else {
112
WARN_PRINT("input_buffer_write: Invalid input_position=" + itos(input_position) + " input_buffer.size()=" + itos(input_buffer.size()));
113
}
114
}
115
116
int AudioDriver::_get_configured_mix_rate() {
117
StringName audio_driver_setting = "audio/driver/mix_rate";
118
int mix_rate = GLOBAL_GET(audio_driver_setting);
119
120
#ifdef WEB_ENABLED
121
// `0` is an acceptable value (resorts to the browser's default).
122
return MAX(0, mix_rate);
123
#else // !WEB_ENABLED
124
// In the case of invalid mix rate, let's default to a sensible value..
125
if (mix_rate <= 0) {
126
WARN_PRINT(vformat("Invalid mix rate of %d, consider reassigning setting \'%s\'. \nDefaulting mix rate to value %d.",
127
mix_rate, audio_driver_setting, AudioDriverManager::DEFAULT_MIX_RATE));
128
mix_rate = AudioDriverManager::DEFAULT_MIX_RATE;
129
}
130
return mix_rate;
131
#endif
132
}
133
134
AudioDriver::SpeakerMode AudioDriver::get_speaker_mode_by_total_channels(int p_channels) const {
135
switch (p_channels) {
136
case 4:
137
return SPEAKER_SURROUND_31;
138
case 6:
139
return SPEAKER_SURROUND_51;
140
case 8:
141
return SPEAKER_SURROUND_71;
142
}
143
144
// Default to STEREO
145
return SPEAKER_MODE_STEREO;
146
}
147
148
int AudioDriver::get_total_channels_by_speaker_mode(AudioDriver::SpeakerMode p_mode) const {
149
switch (p_mode) {
150
case SPEAKER_MODE_STEREO:
151
return 2;
152
case SPEAKER_SURROUND_31:
153
return 4;
154
case SPEAKER_SURROUND_51:
155
return 6;
156
case SPEAKER_SURROUND_71:
157
return 8;
158
}
159
160
ERR_FAIL_V(2);
161
}
162
163
PackedStringArray AudioDriver::get_output_device_list() {
164
PackedStringArray list;
165
166
list.push_back("Default");
167
168
return list;
169
}
170
171
String AudioDriver::get_output_device() {
172
return "Default";
173
}
174
175
PackedStringArray AudioDriver::get_input_device_list() {
176
PackedStringArray list;
177
178
list.push_back("Default");
179
180
return list;
181
}
182
183
void AudioDriver::start_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
184
if (p_playback.is_valid()) {
185
if (p_playback->stream.is_valid()) {
186
WARN_PRINT_ED(vformat(R"(Trying to play stream (%s) as a sample (%s), but the driver doesn't support sample playback.)", p_playback->get_instance_id(), p_playback->stream->get_instance_id()));
187
} else {
188
WARN_PRINT_ED(vformat(R"(Trying to play stream (%s) as a null sample, but the driver doesn't support sample playback.)", p_playback->get_instance_id()));
189
}
190
} else {
191
WARN_PRINT_ED("Trying to play a null sample playback from a driver that don't support sample playback.");
192
}
193
}
194
195
AudioDriverDummy AudioDriverManager::dummy_driver;
196
AudioDriver *AudioDriverManager::drivers[MAX_DRIVERS] = {
197
&AudioDriverManager::dummy_driver,
198
};
199
int AudioDriverManager::driver_count = 1;
200
201
void AudioDriverManager::add_driver(AudioDriver *p_driver) {
202
ERR_FAIL_COND(driver_count >= MAX_DRIVERS);
203
drivers[driver_count - 1] = p_driver;
204
205
// Last driver is always our dummy driver
206
drivers[driver_count++] = &AudioDriverManager::dummy_driver;
207
}
208
209
int AudioDriverManager::get_driver_count() {
210
return driver_count;
211
}
212
213
void AudioDriverManager::initialize(int p_driver) {
214
GLOBAL_DEF_RST("audio/driver/enable_input", false);
215
GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "audio/driver/mix_rate", PROPERTY_HINT_RANGE, "11025,192000,1,or_greater,suffix:Hz"), DEFAULT_MIX_RATE);
216
GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "audio/driver/mix_rate.web", PROPERTY_HINT_RANGE, "0,192000,1,or_greater,suffix:Hz"), 0); // Safer default output_latency for web (use browser default).
217
218
int failed_driver = -1;
219
220
// Check if there is a selected driver
221
if (p_driver >= 0 && p_driver < driver_count) {
222
if (drivers[p_driver]->init() == OK) {
223
drivers[p_driver]->set_singleton();
224
return;
225
} else {
226
failed_driver = p_driver;
227
}
228
}
229
230
// No selected driver, try them all in order
231
for (int i = 0; i < driver_count; i++) {
232
// Don't re-init the driver if it failed above
233
if (i == failed_driver) {
234
continue;
235
}
236
237
if (drivers[i]->init() == OK) {
238
drivers[i]->set_singleton();
239
break;
240
}
241
}
242
243
if (driver_count > 1 && String(AudioDriver::get_singleton()->get_name()) == "Dummy") {
244
WARN_PRINT("All audio drivers failed, falling back to the dummy driver.");
245
}
246
}
247
248
AudioDriver *AudioDriverManager::get_driver(int p_driver) {
249
ERR_FAIL_INDEX_V(p_driver, driver_count, nullptr);
250
return drivers[p_driver];
251
}
252
253
//////////////////////////////////////////////
254
//////////////////////////////////////////////
255
//////////////////////////////////////////////
256
//////////////////////////////////////////////
257
258
void AudioServer::_driver_process(int p_frames, int32_t *p_buffer) {
259
mix_count++;
260
int todo = p_frames;
261
262
#ifdef DEBUG_ENABLED
263
uint64_t prof_ticks = OS::get_singleton()->get_ticks_usec();
264
#endif
265
266
if (channel_count != get_channel_count()) {
267
// Amount of channels changed due to a output_device change
268
// reinitialize the buses channels and buffers
269
init_channels_and_buffers();
270
}
271
272
ERR_FAIL_COND_MSG(buses.is_empty() && todo, "AudioServer bus count is less than 1.");
273
while (todo) {
274
if (to_mix == 0) {
275
_mix_step();
276
}
277
278
int to_copy = MIN(to_mix, todo);
279
280
Bus *master = buses[0];
281
282
int from = buffer_size - to_mix;
283
int from_buf = p_frames - todo;
284
285
//master master, send to output
286
int cs = master->channels.size();
287
288
// Take away 1 from the stride, as we are manually incrementing by 1 for stereo.
289
uintptr_t stride_minus_one = (cs * 2) - 1;
290
291
for (int k = 0; k < cs; k++) {
292
// The destination start for data will be the same in all cases.
293
int32_t *dest = &p_buffer[from_buf * (cs * 2) + (k * 2)];
294
295
#ifdef DEBUG_ENABLED
296
if (!debug_mute && master->channels[k].active) {
297
#else
298
if (master->channels[k].active) {
299
#endif // DEBUG_ENABLED
300
const AudioFrame *buf = master->channels[k].buffer.ptr();
301
302
for (int j = 0; j < to_copy; j++) {
303
float l = CLAMP(buf[from + j].left, -1.0, 1.0);
304
int32_t vl = l * ((1 << 20) - 1);
305
int32_t vl2 = (vl < 0 ? -1 : 1) * (Math::abs(vl) << 11);
306
*dest = vl2;
307
dest++;
308
309
float r = CLAMP(buf[from + j].right, -1.0, 1.0);
310
int32_t vr = r * ((1 << 20) - 1);
311
int32_t vr2 = (vr < 0 ? -1 : 1) * (Math::abs(vr) << 11);
312
*dest = vr2;
313
dest += stride_minus_one;
314
}
315
316
} else {
317
// Bizarrely, profiling indicates that detecting the common case of cs == 1,
318
// k == 0, and using memset is SLOWER than setting them individually.
319
// Perhaps it gets optimized to a faster instruction than memset.
320
for (int j = 0; j < to_copy; j++) {
321
*dest = 0;
322
dest++;
323
*dest = 0;
324
dest += stride_minus_one;
325
}
326
}
327
}
328
329
todo -= to_copy;
330
to_mix -= to_copy;
331
}
332
333
#ifdef DEBUG_ENABLED
334
prof_time.add(OS::get_singleton()->get_ticks_usec() - prof_ticks);
335
#endif
336
}
337
338
void AudioServer::_mix_step() {
339
bool solo_mode = false;
340
341
for (int i = 0; i < buses.size(); i++) {
342
Bus *bus = buses[i];
343
bus->index_cache = i; //might be moved around by editor, so..
344
for (int k = 0; k < bus->channels.size(); k++) {
345
bus->channels.write[k].used = false;
346
}
347
348
if (bus->solo) {
349
//solo chain
350
solo_mode = true;
351
bus->soloed = true;
352
do {
353
if (bus != buses[0]) {
354
//everything has a send save for master bus
355
if (!bus_map.has(bus->send)) {
356
bus = buses[0]; //send to master
357
} else {
358
int prev_index_cache = bus->index_cache;
359
bus = bus_map[bus->send];
360
if (prev_index_cache >= bus->index_cache) { //invalid, send to master
361
bus = buses[0];
362
}
363
}
364
365
bus->soloed = true;
366
} else {
367
bus = nullptr;
368
}
369
370
} while (bus);
371
} else {
372
bus->soloed = false;
373
}
374
}
375
// This is legacy code from 3.x that allows video players and other audio sources that do not implement AudioStreamPlayback to output audio.
376
for (CallbackItem *ci : mix_callback_list) {
377
ci->callback(ci->userdata);
378
}
379
380
// Main mixing loop for audio streams.
381
// The basic idea here is to copy the samples returned by the AudioStreamPlayback's mix function into the audio buffers,
382
// while always maintaining a lookahead buffer of size LOOKAHEAD_BUFFER_SIZE to allow fade-outs for sudden stoppages.
383
for (AudioStreamPlaybackListNode *playback : playback_list) {
384
// Paused streams are no-ops. Don't even mix audio from the stream playback.
385
if (playback->state.load() == AudioStreamPlaybackListNode::PAUSED) {
386
continue;
387
}
388
389
if (playback->stream_playback->get_is_sample()) {
390
continue;
391
}
392
393
// If `fading_out` is true, we're in the process of fading out the stream playback.
394
// TODO: Currently this sets the volume of the stream to 0 which creates a linear interpolation between its previous volume and silence.
395
// A more punchy option for fading out could be to just use the lookahead buffer.
396
bool fading_out = playback->state.load() == AudioStreamPlaybackListNode::FADE_OUT_TO_DELETION || playback->state.load() == AudioStreamPlaybackListNode::FADE_OUT_TO_PAUSE;
397
398
AudioFrame *buf = mix_buffer.ptrw();
399
400
// Copy the old contents of the lookahead buffer into the beginning of the mix buffer.
401
for (int i = 0; i < LOOKAHEAD_BUFFER_SIZE; i++) {
402
buf[i] = playback->lookahead[i];
403
}
404
405
// Mix the audio stream.
406
unsigned int mixed_frames = playback->stream_playback->mix(&buf[LOOKAHEAD_BUFFER_SIZE], playback->pitch_scale.get(), buffer_size);
407
408
if (tag_used_audio_streams && playback->stream_playback->is_playing()) {
409
playback->stream_playback->tag_used_streams();
410
}
411
412
// Check to see if the stream has run out of samples.
413
if (mixed_frames != buffer_size) {
414
// We know we have at least the size of our lookahead buffer for fade-out purposes.
415
416
float fadeout_base = 0.94;
417
float fadeout_coefficient = 1;
418
static_assert(LOOKAHEAD_BUFFER_SIZE == 64, "Update fadeout_base and comment here if you change LOOKAHEAD_BUFFER_SIZE.");
419
// 0.94 ^ 64 = 0.01906. There might still be a pop but it'll be way better than if we didn't do this.
420
for (unsigned int idx = mixed_frames; idx < buffer_size; idx++) {
421
fadeout_coefficient *= fadeout_base;
422
buf[idx] *= fadeout_coefficient;
423
}
424
AudioStreamPlaybackListNode::PlaybackState new_state;
425
new_state = AudioStreamPlaybackListNode::AWAITING_DELETION;
426
playback->state.store(new_state);
427
} else {
428
// Move the last little bit of what we just mixed into our lookahead buffer for the next call to _mix_step.
429
for (int i = 0; i < LOOKAHEAD_BUFFER_SIZE; i++) {
430
playback->lookahead[i] = buf[buffer_size + i];
431
}
432
}
433
434
// Get the bus details for this playback. This contains information about which buses the playback is assigned to and the volume of the playback on each bus.
435
AudioStreamPlaybackBusDetails *bus_details_ptr = playback->bus_details.load();
436
ERR_FAIL_NULL(bus_details_ptr);
437
// Make a copy of the bus details so we can modify it without worrying about other threads.
438
AudioStreamPlaybackBusDetails bus_details = *bus_details_ptr;
439
440
// Mix to any active buses.
441
for (int idx = 0; idx < MAX_BUSES_PER_PLAYBACK; idx++) {
442
if (!bus_details.bus_active[idx]) {
443
continue;
444
}
445
// This is the AudioServer-internal index of the bus we're mixing to in this step of the loop. Not to be confused with `idx` which is an index into `AudioStreamPlaybackBusDetails` member var arrays.
446
int bus_idx = thread_find_bus_index(bus_details.bus[idx]);
447
448
// It's important to know whether or not this bus was active in the previous mix step of this stream. If it was, we need to perform volume interpolation to avoid pops.
449
int prev_bus_idx = -1;
450
for (int search_idx = 0; search_idx < MAX_BUSES_PER_PLAYBACK; search_idx++) {
451
if (!playback->prev_bus_details->bus_active[search_idx]) {
452
continue;
453
}
454
// If the StringNames of the buses match, we've found the previous bus index. This indicates that this playback mixed to `prev_bus_details->bus[prev_bus_index]` in the previous mix step, which gives us a way to look up the playback's previous volume.
455
if (playback->prev_bus_details->bus[search_idx].hash() == bus_details.bus[idx].hash()) {
456
prev_bus_idx = search_idx;
457
break;
458
}
459
}
460
461
// It's now time to mix to the bus. We do this by going through each channel of the bus and mixing to it.
462
// The channels correspond to output channels of the audio device, e.g. stereo or 5.1. To reduce needless nesting, this is done with a helper method named `_mix_step_for_channel`.
463
for (int channel_idx = 0; channel_idx < channel_count; channel_idx++) {
464
AudioFrame *channel_buf = thread_get_channel_mix_buffer(bus_idx, channel_idx);
465
// TODO: This `fading_out` check could be replaced with with an exponential fadeout of the samples from the lookahead buffer for more punchy results.
466
if (fading_out) {
467
bus_details.volume[idx][channel_idx] = AudioFrame(0, 0);
468
}
469
AudioFrame channel_vol = bus_details.volume[idx][channel_idx];
470
471
// If this bus was not active in the previous mix step, we want to start playback at the full volume to avoid crushing transients.
472
AudioFrame prev_channel_vol = channel_vol;
473
// If this bus was active in the previous mix step, we need to interpolate between the previous volume and the current volume to avoid pops. Set `prev_channel_volume` accordingly.
474
if (prev_bus_idx != -1) {
475
prev_channel_vol = playback->prev_bus_details->volume[prev_bus_idx][channel_idx];
476
}
477
_mix_step_for_channel(channel_buf, buf, prev_channel_vol, channel_vol, playback->attenuation_filter_cutoff_hz.get(), playback->highshelf_gain.get(), &playback->filter_process[channel_idx * 2], &playback->filter_process[channel_idx * 2 + 1]);
478
}
479
}
480
481
// Now go through and fade-out any buses that were being played to previously that we missed by going through current data.
482
for (int idx = 0; idx < MAX_BUSES_PER_PLAYBACK; idx++) {
483
if (!playback->prev_bus_details->bus_active[idx]) {
484
continue;
485
}
486
int bus_idx = thread_find_bus_index(playback->prev_bus_details->bus[idx]);
487
488
int current_bus_idx = -1;
489
for (int search_idx = 0; search_idx < MAX_BUSES_PER_PLAYBACK; search_idx++) {
490
if (bus_details.bus[search_idx] == playback->prev_bus_details->bus[idx]) {
491
current_bus_idx = search_idx;
492
}
493
}
494
if (current_bus_idx != -1) {
495
// If we found a corresponding bus in the current bus assignments, we've already mixed to this bus.
496
continue;
497
}
498
499
for (int channel_idx = 0; channel_idx < channel_count; channel_idx++) {
500
AudioFrame *channel_buf = thread_get_channel_mix_buffer(bus_idx, channel_idx);
501
AudioFrame prev_channel_vol = playback->prev_bus_details->volume[idx][channel_idx];
502
// Fade out to silence. This could be replaced with an exponential fadeout of the samples from the lookahead buffer for more punchy results.
503
_mix_step_for_channel(channel_buf, buf, prev_channel_vol, AudioFrame(0, 0), playback->attenuation_filter_cutoff_hz.get(), playback->highshelf_gain.get(), &playback->filter_process[channel_idx * 2], &playback->filter_process[channel_idx * 2 + 1]);
504
}
505
}
506
507
// Copy the bus details we mixed with to the previous bus details to maintain volume ramps.
508
for (int i = 0; i < MAX_BUSES_PER_PLAYBACK; i++) {
509
playback->prev_bus_details->bus_active[i] = bus_details.bus_active[i];
510
}
511
for (int i = 0; i < MAX_BUSES_PER_PLAYBACK; i++) {
512
playback->prev_bus_details->bus[i] = bus_details.bus[i];
513
}
514
for (int i = 0; i < MAX_BUSES_PER_PLAYBACK; i++) {
515
for (int j = 0; j < MAX_CHANNELS_PER_BUS; j++) {
516
playback->prev_bus_details->volume[i][j] = bus_details.volume[i][j];
517
}
518
}
519
520
switch (playback->state.load()) {
521
case AudioStreamPlaybackListNode::AWAITING_DELETION:
522
case AudioStreamPlaybackListNode::FADE_OUT_TO_DELETION:
523
// Remove the playback from the list.
524
_delete_stream_playback_list_node(playback);
525
break;
526
case AudioStreamPlaybackListNode::FADE_OUT_TO_PAUSE: {
527
// Pause the stream.
528
playback->state.store(AudioStreamPlaybackListNode::PAUSED);
529
} break;
530
case AudioStreamPlaybackListNode::PLAYING:
531
case AudioStreamPlaybackListNode::PAUSED:
532
// No-op!
533
break;
534
}
535
}
536
537
// Now that all of the buses have their audio sources mixed into them, we can process the effects and bus sends.
538
for (int i = buses.size() - 1; i >= 0; i--) {
539
Bus *bus = buses[i];
540
541
for (int k = 0; k < bus->channels.size(); k++) {
542
if (bus->channels[k].active && !bus->channels[k].used) {
543
// Buffer was not used, but it's still active, so it must be cleaned.
544
AudioFrame *buf = bus->channels.write[k].buffer.ptrw();
545
546
for (uint32_t j = 0; j < buffer_size; j++) {
547
buf[j] = AudioFrame(0, 0);
548
}
549
}
550
}
551
552
// Process effects.
553
if (!bus->bypass) {
554
for (int j = 0; j < bus->effects.size(); j++) {
555
if (!bus->effects[j].enabled) {
556
continue;
557
}
558
559
#ifdef DEBUG_ENABLED
560
uint64_t ticks = OS::get_singleton()->get_ticks_usec();
561
#endif
562
563
for (int k = 0; k < bus->channels.size(); k++) {
564
if (!(bus->channels[k].active || bus->channels[k].effect_instances[j]->process_silence())) {
565
continue;
566
}
567
bus->channels.write[k].effect_instances.write[j]->process(bus->channels[k].buffer.ptr(), temp_buffer.write[k].ptrw(), buffer_size);
568
}
569
570
// Swap buffers, so internal buffer always has the right data.
571
for (int k = 0; k < bus->channels.size(); k++) {
572
if (!(buses[i]->channels[k].active || bus->channels[k].effect_instances[j]->process_silence())) {
573
continue;
574
}
575
SWAP(bus->channels.write[k].buffer, temp_buffer.write[k]);
576
}
577
578
#ifdef DEBUG_ENABLED
579
bus->effects.write[j].prof_time += OS::get_singleton()->get_ticks_usec() - ticks;
580
#endif
581
}
582
}
583
584
// Process send.
585
586
Bus *send = nullptr;
587
588
if (i > 0) {
589
// Everything has a send except for the master bus.
590
if (!bus_map.has(bus->send)) {
591
send = buses[0];
592
} else {
593
send = bus_map[bus->send];
594
if (send->index_cache >= bus->index_cache) { // Invalid, send to master.
595
send = buses[0];
596
}
597
}
598
}
599
600
for (int k = 0; k < bus->channels.size(); k++) {
601
if (!bus->channels[k].active) {
602
bus->channels.write[k].peak_volume = AudioFrame(AUDIO_MIN_PEAK_DB, AUDIO_MIN_PEAK_DB);
603
continue;
604
}
605
606
AudioFrame *buf = bus->channels.write[k].buffer.ptrw();
607
608
AudioFrame peak = AudioFrame(0, 0);
609
610
float volume = Math::db_to_linear(bus->volume_db);
611
612
if (solo_mode) {
613
if (!bus->soloed) {
614
volume = 0.0;
615
}
616
} else {
617
if (bus->mute) {
618
volume = 0.0;
619
}
620
}
621
622
// Apply volume and compute peak.
623
for (uint32_t j = 0; j < buffer_size; j++) {
624
buf[j] *= volume;
625
626
float l = Math::abs(buf[j].left);
627
if (l > peak.left) {
628
peak.left = l;
629
}
630
float r = Math::abs(buf[j].right);
631
if (r > peak.right) {
632
peak.right = r;
633
}
634
}
635
636
bus->channels.write[k].peak_volume = AudioFrame(Math::linear_to_db(peak.left + AUDIO_PEAK_OFFSET), Math::linear_to_db(peak.right + AUDIO_PEAK_OFFSET));
637
638
if (!bus->channels[k].used) {
639
// See if any audio is contained, because channel was not used.
640
641
if (MAX(peak.right, peak.left) > Math::db_to_linear(channel_disable_threshold_db)) {
642
bus->channels.write[k].last_mix_with_audio = mix_frames;
643
} else if (mix_frames - bus->channels[k].last_mix_with_audio > channel_disable_frames) {
644
bus->channels.write[k].active = false;
645
continue; //went inactive, don't mix.
646
}
647
}
648
649
if (send) {
650
// If not master bus, send.
651
AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache, k);
652
653
for (uint32_t j = 0; j < buffer_size; j++) {
654
target_buf[j] += buf[j];
655
}
656
}
657
}
658
}
659
660
mix_frames += buffer_size;
661
to_mix = buffer_size;
662
}
663
664
void AudioServer::_mix_step_for_channel(AudioFrame *p_out_buf, AudioFrame *p_source_buf, AudioFrame p_vol_start, AudioFrame p_vol_final, float p_attenuation_filter_cutoff_hz, float p_highshelf_gain, AudioFilterSW::Processor *p_processor_l, AudioFilterSW::Processor *p_processor_r) {
665
// TODO: In the future it could be nice to replace all of these hardcoded effects with something a bit cleaner and more flexible, but for now this is what we do to support 3D audio players.
666
if (p_highshelf_gain != 0) {
667
AudioFilterSW filter;
668
filter.set_mode(AudioFilterSW::HIGHSHELF);
669
filter.set_sampling_rate(AudioServer::get_singleton()->get_mix_rate());
670
filter.set_cutoff(p_attenuation_filter_cutoff_hz);
671
filter.set_resonance(1);
672
filter.set_stages(1);
673
filter.set_gain(p_highshelf_gain);
674
675
ERR_FAIL_NULL(p_processor_l);
676
ERR_FAIL_NULL(p_processor_r);
677
678
bool is_just_started = p_vol_start.left == 0 && p_vol_start.right == 0;
679
p_processor_l->set_filter(&filter, /* clear_history= */ is_just_started);
680
p_processor_l->update_coeffs(buffer_size);
681
p_processor_r->set_filter(&filter, /* clear_history= */ is_just_started);
682
p_processor_r->update_coeffs(buffer_size);
683
684
for (unsigned int frame_idx = 0; frame_idx < buffer_size; frame_idx++) {
685
// TODO: Make lerp speed buffer-size-invariant if buffer_size ever becomes a project setting to avoid very small buffer sizes causing pops due to too-fast lerps.
686
float lerp_param = (float)frame_idx / buffer_size;
687
AudioFrame vol = p_vol_final * lerp_param + (1 - lerp_param) * p_vol_start;
688
AudioFrame mixed = vol * p_source_buf[frame_idx];
689
p_processor_l->process_one_interp(mixed.left);
690
p_processor_r->process_one_interp(mixed.right);
691
p_out_buf[frame_idx] += mixed;
692
}
693
694
} else {
695
for (unsigned int frame_idx = 0; frame_idx < buffer_size; frame_idx++) {
696
// TODO: Make lerp speed buffer-size-invariant if buffer_size ever becomes a project setting to avoid very small buffer sizes causing pops due to too-fast lerps.
697
float lerp_param = (float)frame_idx / buffer_size;
698
p_out_buf[frame_idx] += (p_vol_final * lerp_param + (1 - lerp_param) * p_vol_start) * p_source_buf[frame_idx];
699
}
700
}
701
}
702
703
AudioServer::AudioStreamPlaybackListNode *AudioServer::_find_playback_list_node(Ref<AudioStreamPlayback> p_playback) {
704
for (AudioStreamPlaybackListNode *playback_list_node : playback_list) {
705
if (playback_list_node->stream_playback == p_playback) {
706
return playback_list_node;
707
}
708
}
709
return nullptr;
710
}
711
712
void AudioServer::_delete_stream_playback(Ref<AudioStreamPlayback> p_playback) {
713
ERR_FAIL_COND(p_playback.is_null());
714
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
715
if (playback_node) {
716
_delete_stream_playback_list_node(playback_node);
717
}
718
}
719
720
void AudioServer::_delete_stream_playback_list_node(AudioStreamPlaybackListNode *p_playback_node) {
721
// Remove the playback from the list, registering a destructor to be run on the main thread.
722
playback_list.erase(p_playback_node, [](AudioStreamPlaybackListNode *p) {
723
delete p->prev_bus_details;
724
delete p->bus_details.load();
725
p->stream_playback.unref();
726
delete p;
727
});
728
}
729
730
bool AudioServer::thread_has_channel_mix_buffer(int p_bus, int p_buffer) const {
731
if (p_bus < 0 || p_bus >= buses.size()) {
732
return false;
733
}
734
if (p_buffer < 0 || p_buffer >= buses[p_bus]->channels.size()) {
735
return false;
736
}
737
return true;
738
}
739
740
AudioFrame *AudioServer::thread_get_channel_mix_buffer(int p_bus, int p_buffer) {
741
ERR_FAIL_INDEX_V(p_bus, buses.size(), nullptr);
742
ERR_FAIL_INDEX_V(p_buffer, buses[p_bus]->channels.size(), nullptr);
743
744
AudioFrame *data = buses.write[p_bus]->channels.write[p_buffer].buffer.ptrw();
745
746
if (!buses[p_bus]->channels[p_buffer].used) {
747
buses.write[p_bus]->channels.write[p_buffer].used = true;
748
buses.write[p_bus]->channels.write[p_buffer].active = true;
749
buses.write[p_bus]->channels.write[p_buffer].last_mix_with_audio = mix_frames;
750
for (uint32_t i = 0; i < buffer_size; i++) {
751
data[i] = AudioFrame(0, 0);
752
}
753
}
754
755
return data;
756
}
757
758
int AudioServer::thread_get_mix_buffer_size() const {
759
return buffer_size;
760
}
761
762
int AudioServer::thread_find_bus_index(const StringName &p_name) {
763
if (bus_map.has(p_name)) {
764
return bus_map[p_name]->index_cache;
765
} else {
766
return 0;
767
}
768
}
769
770
#ifdef DEBUG_ENABLED
771
void AudioServer::set_debug_mute(bool p_mute) {
772
debug_mute = p_mute;
773
}
774
775
bool AudioServer::get_debug_mute() const {
776
return debug_mute;
777
}
778
#endif // DEBUG_ENABLED
779
780
void AudioServer::set_bus_count(int p_count) {
781
ERR_FAIL_COND(p_count < 1);
782
ERR_FAIL_INDEX(p_count, 256);
783
784
MARK_EDITED
785
786
lock();
787
int cb = buses.size();
788
789
if (p_count < buses.size()) {
790
for (int i = p_count; i < buses.size(); i++) {
791
bus_map.erase(buses[i]->name);
792
memdelete(buses[i]);
793
}
794
}
795
796
buses.resize(p_count);
797
798
for (int i = cb; i < buses.size(); i++) {
799
String attempt = "New Bus";
800
int attempts = 1;
801
while (true) {
802
bool name_free = true;
803
for (int j = 0; j < i; j++) {
804
if (buses[j]->name == attempt) {
805
name_free = false;
806
break;
807
}
808
}
809
810
if (!name_free) {
811
attempts++;
812
attempt = "New Bus " + itos(attempts);
813
} else {
814
break;
815
}
816
}
817
818
buses.write[i] = memnew(Bus);
819
buses.write[i]->channels.resize(channel_count);
820
for (int j = 0; j < channel_count; j++) {
821
buses.write[i]->channels.write[j].buffer.resize(buffer_size);
822
}
823
buses[i]->name = attempt;
824
buses[i]->solo = false;
825
buses[i]->mute = false;
826
buses[i]->bypass = false;
827
buses[i]->volume_db = 0;
828
if (i > 0) {
829
buses[i]->send = SceneStringName(Master);
830
}
831
832
bus_map[attempt] = buses[i];
833
}
834
835
unlock();
836
837
AudioDriver::get_singleton()->set_sample_bus_count(p_count);
838
839
emit_signal(SNAME("bus_layout_changed"));
840
}
841
842
void AudioServer::remove_bus(int p_index) {
843
ERR_FAIL_INDEX(p_index, buses.size());
844
ERR_FAIL_COND(p_index == 0);
845
846
MARK_EDITED
847
848
lock();
849
bus_map.erase(buses[p_index]->name);
850
memdelete(buses[p_index]);
851
buses.remove_at(p_index);
852
unlock();
853
854
AudioDriver::get_singleton()->remove_sample_bus(p_index);
855
856
emit_signal(SNAME("bus_layout_changed"));
857
}
858
859
void AudioServer::add_bus(int p_at_pos) {
860
MARK_EDITED
861
862
if (p_at_pos >= buses.size()) {
863
p_at_pos = -1;
864
} else if (p_at_pos == 0) {
865
if (buses.size() > 1) {
866
p_at_pos = 1;
867
} else {
868
p_at_pos = -1;
869
}
870
}
871
872
String attempt = "New Bus";
873
int attempts = 1;
874
while (true) {
875
bool name_free = true;
876
for (int j = 0; j < buses.size(); j++) {
877
if (buses[j]->name == attempt) {
878
name_free = false;
879
break;
880
}
881
}
882
883
if (!name_free) {
884
attempts++;
885
attempt = "New Bus " + itos(attempts);
886
} else {
887
break;
888
}
889
}
890
891
Bus *bus = memnew(Bus);
892
bus->channels.resize(channel_count);
893
for (int j = 0; j < channel_count; j++) {
894
bus->channels.write[j].buffer.resize(buffer_size);
895
}
896
bus->name = attempt;
897
bus->solo = false;
898
bus->mute = false;
899
bus->bypass = false;
900
bus->volume_db = 0;
901
902
bus_map[attempt] = bus;
903
904
if (p_at_pos == -1) {
905
buses.push_back(bus);
906
} else {
907
buses.insert(p_at_pos, bus);
908
}
909
910
AudioDriver::get_singleton()->add_sample_bus(p_at_pos);
911
912
emit_signal(SNAME("bus_layout_changed"));
913
}
914
915
void AudioServer::move_bus(int p_bus, int p_to_pos) {
916
ERR_FAIL_COND(p_bus < 1 || p_bus >= buses.size());
917
ERR_FAIL_COND(p_to_pos != -1 && (p_to_pos < 1 || p_to_pos > buses.size()));
918
919
MARK_EDITED
920
921
if (p_bus == p_to_pos) {
922
return;
923
}
924
925
Bus *bus = buses[p_bus];
926
buses.remove_at(p_bus);
927
928
if (p_to_pos == -1) {
929
buses.push_back(bus);
930
} else if (p_to_pos < p_bus) {
931
buses.insert(p_to_pos, bus);
932
} else {
933
buses.insert(p_to_pos - 1, bus);
934
}
935
936
AudioDriver::get_singleton()->move_sample_bus(p_bus, p_to_pos);
937
938
emit_signal(SNAME("bus_layout_changed"));
939
}
940
941
int AudioServer::get_bus_count() const {
942
return buses.size();
943
}
944
945
void AudioServer::set_bus_name(int p_bus, const String &p_name) {
946
ERR_FAIL_INDEX(p_bus, buses.size());
947
if (p_bus == 0 && p_name != "Master") {
948
return; // Bus 0 is always "Master".
949
}
950
951
MARK_EDITED
952
953
lock();
954
955
StringName old_name = buses[p_bus]->name;
956
957
if (old_name == p_name) {
958
unlock();
959
return;
960
}
961
962
String attempt = p_name;
963
int attempts = 1;
964
965
while (true) {
966
bool name_free = true;
967
for (int i = 0; i < buses.size(); i++) {
968
if (buses[i]->name == attempt) {
969
name_free = false;
970
break;
971
}
972
}
973
974
if (name_free) {
975
break;
976
}
977
978
attempts++;
979
attempt = p_name + " " + itos(attempts);
980
}
981
bus_map.erase(old_name);
982
buses[p_bus]->name = attempt;
983
bus_map[attempt] = buses[p_bus];
984
unlock();
985
986
emit_signal(SNAME("bus_renamed"), p_bus, old_name, attempt);
987
}
988
989
String AudioServer::get_bus_name(int p_bus) const {
990
ERR_FAIL_INDEX_V(p_bus, buses.size(), String());
991
return buses[p_bus]->name;
992
}
993
994
int AudioServer::get_bus_index(const StringName &p_bus_name) const {
995
for (int i = 0; i < buses.size(); ++i) {
996
if (buses[i]->name == p_bus_name) {
997
return i;
998
}
999
}
1000
return -1;
1001
}
1002
1003
void AudioServer::set_bus_volume_db(int p_bus, float p_volume_db) {
1004
ERR_FAIL_INDEX(p_bus, buses.size());
1005
1006
MARK_EDITED
1007
1008
buses[p_bus]->volume_db = p_volume_db;
1009
1010
AudioDriver::get_singleton()->set_sample_bus_volume_db(p_bus, p_volume_db);
1011
}
1012
1013
float AudioServer::get_bus_volume_db(int p_bus) const {
1014
ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
1015
return buses[p_bus]->volume_db;
1016
}
1017
1018
void AudioServer::set_bus_volume_linear(int p_bus, float p_volume_linear) {
1019
set_bus_volume_db(p_bus, Math::linear_to_db(p_volume_linear));
1020
}
1021
1022
float AudioServer::get_bus_volume_linear(int p_bus) const {
1023
return Math::db_to_linear(get_bus_volume_db(p_bus));
1024
}
1025
1026
int AudioServer::get_bus_channels(int p_bus) const {
1027
ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
1028
return buses[p_bus]->channels.size();
1029
}
1030
1031
void AudioServer::set_bus_send(int p_bus, const StringName &p_send) {
1032
ERR_FAIL_INDEX(p_bus, buses.size());
1033
1034
MARK_EDITED
1035
1036
buses[p_bus]->send = p_send;
1037
1038
AudioDriver::get_singleton()->set_sample_bus_send(p_bus, p_send);
1039
}
1040
1041
StringName AudioServer::get_bus_send(int p_bus) const {
1042
ERR_FAIL_INDEX_V(p_bus, buses.size(), StringName());
1043
return buses[p_bus]->send;
1044
}
1045
1046
void AudioServer::set_bus_solo(int p_bus, bool p_enable) {
1047
ERR_FAIL_INDEX(p_bus, buses.size());
1048
1049
MARK_EDITED
1050
1051
buses[p_bus]->solo = p_enable;
1052
1053
AudioDriver::get_singleton()->set_sample_bus_solo(p_bus, p_enable);
1054
}
1055
1056
bool AudioServer::is_bus_solo(int p_bus) const {
1057
ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
1058
1059
return buses[p_bus]->solo;
1060
}
1061
1062
void AudioServer::set_bus_mute(int p_bus, bool p_enable) {
1063
ERR_FAIL_INDEX(p_bus, buses.size());
1064
1065
MARK_EDITED
1066
1067
buses[p_bus]->mute = p_enable;
1068
1069
AudioDriver::get_singleton()->set_sample_bus_mute(p_bus, p_enable);
1070
}
1071
1072
bool AudioServer::is_bus_mute(int p_bus) const {
1073
ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
1074
1075
return buses[p_bus]->mute;
1076
}
1077
1078
void AudioServer::set_bus_bypass_effects(int p_bus, bool p_enable) {
1079
ERR_FAIL_INDEX(p_bus, buses.size());
1080
1081
MARK_EDITED
1082
1083
buses[p_bus]->bypass = p_enable;
1084
}
1085
1086
bool AudioServer::is_bus_bypassing_effects(int p_bus) const {
1087
ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
1088
1089
return buses[p_bus]->bypass;
1090
}
1091
1092
void AudioServer::_update_bus_effects(int p_bus) {
1093
for (int i = 0; i < buses[p_bus]->channels.size(); i++) {
1094
buses.write[p_bus]->channels.write[i].effect_instances.resize(buses[p_bus]->effects.size());
1095
for (int j = 0; j < buses[p_bus]->effects.size(); j++) {
1096
Ref<AudioEffectInstance> fx = buses.write[p_bus]->effects.write[j].effect->instantiate();
1097
if (Object::cast_to<AudioEffectCompressorInstance>(*fx)) {
1098
Object::cast_to<AudioEffectCompressorInstance>(*fx)->set_current_channel(i);
1099
}
1100
buses.write[p_bus]->channels.write[i].effect_instances.write[j] = fx;
1101
}
1102
}
1103
}
1104
1105
void AudioServer::add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos) {
1106
ERR_FAIL_COND(p_effect.is_null());
1107
ERR_FAIL_INDEX(p_bus, buses.size());
1108
1109
MARK_EDITED
1110
1111
lock();
1112
1113
Bus::Effect fx;
1114
fx.effect = p_effect;
1115
//fx.instance=p_effect->instantiate();
1116
fx.enabled = true;
1117
#ifdef DEBUG_ENABLED
1118
fx.prof_time = 0;
1119
#endif
1120
1121
if (p_at_pos >= buses[p_bus]->effects.size() || p_at_pos < 0) {
1122
buses[p_bus]->effects.push_back(fx);
1123
} else {
1124
buses[p_bus]->effects.insert(p_at_pos, fx);
1125
}
1126
1127
_update_bus_effects(p_bus);
1128
1129
unlock();
1130
}
1131
1132
void AudioServer::remove_bus_effect(int p_bus, int p_effect) {
1133
ERR_FAIL_INDEX(p_bus, buses.size());
1134
1135
MARK_EDITED
1136
1137
lock();
1138
1139
buses[p_bus]->effects.remove_at(p_effect);
1140
_update_bus_effects(p_bus);
1141
1142
unlock();
1143
}
1144
1145
int AudioServer::get_bus_effect_count(int p_bus) {
1146
ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
1147
1148
return buses[p_bus]->effects.size();
1149
}
1150
1151
Ref<AudioEffectInstance> AudioServer::get_bus_effect_instance(int p_bus, int p_effect, int p_channel) {
1152
ERR_FAIL_INDEX_V(p_bus, buses.size(), Ref<AudioEffectInstance>());
1153
ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), Ref<AudioEffectInstance>());
1154
ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), Ref<AudioEffectInstance>());
1155
1156
return buses[p_bus]->channels[p_channel].effect_instances[p_effect];
1157
}
1158
1159
Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus, int p_effect) {
1160
ERR_FAIL_INDEX_V(p_bus, buses.size(), Ref<AudioEffect>());
1161
ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), Ref<AudioEffect>());
1162
1163
return buses[p_bus]->effects[p_effect].effect;
1164
}
1165
1166
void AudioServer::swap_bus_effects(int p_bus, int p_effect, int p_by_effect) {
1167
ERR_FAIL_INDEX(p_bus, buses.size());
1168
ERR_FAIL_INDEX(p_effect, buses[p_bus]->effects.size());
1169
ERR_FAIL_INDEX(p_by_effect, buses[p_bus]->effects.size());
1170
1171
MARK_EDITED
1172
1173
lock();
1174
SWAP(buses.write[p_bus]->effects.write[p_effect], buses.write[p_bus]->effects.write[p_by_effect]);
1175
_update_bus_effects(p_bus);
1176
unlock();
1177
}
1178
1179
void AudioServer::set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled) {
1180
ERR_FAIL_INDEX(p_bus, buses.size());
1181
ERR_FAIL_INDEX(p_effect, buses[p_bus]->effects.size());
1182
1183
MARK_EDITED
1184
1185
buses.write[p_bus]->effects.write[p_effect].enabled = p_enabled;
1186
}
1187
1188
bool AudioServer::is_bus_effect_enabled(int p_bus, int p_effect) const {
1189
ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
1190
ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), false);
1191
return buses[p_bus]->effects[p_effect].enabled;
1192
}
1193
1194
float AudioServer::get_bus_peak_volume_left_db(int p_bus, int p_channel) const {
1195
ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
1196
ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), 0);
1197
1198
return buses[p_bus]->channels[p_channel].peak_volume.left;
1199
}
1200
1201
float AudioServer::get_bus_peak_volume_right_db(int p_bus, int p_channel) const {
1202
ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
1203
ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), 0);
1204
1205
return buses[p_bus]->channels[p_channel].peak_volume.right;
1206
}
1207
1208
bool AudioServer::is_bus_channel_active(int p_bus, int p_channel) const {
1209
ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
1210
ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), false);
1211
1212
return buses[p_bus]->channels[p_channel].active;
1213
}
1214
1215
void AudioServer::set_playback_speed_scale(float p_scale) {
1216
ERR_FAIL_COND(p_scale <= 0);
1217
1218
playback_speed_scale = p_scale;
1219
}
1220
1221
float AudioServer::get_playback_speed_scale() const {
1222
return playback_speed_scale;
1223
}
1224
1225
void AudioServer::start_playback_stream(Ref<AudioStreamPlayback> p_playback, const StringName &p_bus, Vector<AudioFrame> p_volume_db_vector, float p_start_time, float p_pitch_scale) {
1226
ERR_FAIL_COND(p_playback.is_null());
1227
1228
HashMap<StringName, Vector<AudioFrame>> map;
1229
map[p_bus] = p_volume_db_vector;
1230
1231
start_playback_stream(p_playback, map, p_start_time, p_pitch_scale);
1232
}
1233
1234
void AudioServer::start_playback_stream(Ref<AudioStreamPlayback> p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes, float p_start_time, float p_pitch_scale, float p_highshelf_gain, float p_attenuation_cutoff_hz) {
1235
ERR_FAIL_COND(p_playback.is_null());
1236
1237
AudioStreamPlaybackListNode *playback_node = new AudioStreamPlaybackListNode();
1238
playback_node->stream_playback = p_playback;
1239
playback_node->stream_playback->start(p_start_time);
1240
1241
AudioStreamPlaybackBusDetails *new_bus_details = new AudioStreamPlaybackBusDetails();
1242
int idx = 0;
1243
for (KeyValue<StringName, Vector<AudioFrame>> pair : p_bus_volumes) {
1244
if (pair.value.size() < channel_count || pair.value.size() != MAX_CHANNELS_PER_BUS) {
1245
delete playback_node;
1246
delete new_bus_details;
1247
ERR_FAIL();
1248
}
1249
1250
new_bus_details->bus_active[idx] = true;
1251
new_bus_details->bus[idx] = pair.key;
1252
for (int channel_idx = 0; channel_idx < MAX_CHANNELS_PER_BUS; channel_idx++) {
1253
new_bus_details->volume[idx][channel_idx] = pair.value[channel_idx];
1254
}
1255
idx++;
1256
}
1257
playback_node->bus_details.store(new_bus_details);
1258
playback_node->prev_bus_details = new AudioStreamPlaybackBusDetails();
1259
1260
playback_node->pitch_scale.set(p_pitch_scale);
1261
playback_node->highshelf_gain.set(p_highshelf_gain);
1262
playback_node->attenuation_filter_cutoff_hz.set(p_attenuation_cutoff_hz);
1263
1264
memset(playback_node->prev_bus_details->volume, 0, sizeof(playback_node->prev_bus_details->volume));
1265
1266
for (AudioFrame &frame : playback_node->lookahead) {
1267
frame = AudioFrame(0, 0);
1268
}
1269
1270
playback_node->state.store(AudioStreamPlaybackListNode::PLAYING);
1271
1272
playback_list.insert(playback_node);
1273
}
1274
1275
void AudioServer::stop_playback_stream(Ref<AudioStreamPlayback> p_playback) {
1276
ERR_FAIL_COND(p_playback.is_null());
1277
1278
// Handle sample playback.
1279
if (p_playback->get_is_sample()) {
1280
if (p_playback->get_sample_playback().is_valid()) {
1281
AudioServer::get_singleton()->stop_sample_playback(p_playback->get_sample_playback());
1282
} else {
1283
_delete_stream_playback(p_playback);
1284
}
1285
return;
1286
}
1287
1288
if (!p_playback->is_playing()) {
1289
p_playback->stop();
1290
}
1291
1292
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1293
if (!playback_node) {
1294
return;
1295
}
1296
1297
AudioStreamPlaybackListNode::PlaybackState new_state, old_state;
1298
do {
1299
old_state = playback_node->state.load();
1300
if (old_state == AudioStreamPlaybackListNode::AWAITING_DELETION) {
1301
break; // Don't fade out again.
1302
}
1303
new_state = AudioStreamPlaybackListNode::FADE_OUT_TO_DELETION;
1304
1305
} while (!playback_node->state.compare_exchange_strong(old_state, new_state));
1306
}
1307
1308
void AudioServer::set_playback_bus_exclusive(Ref<AudioStreamPlayback> p_playback, const StringName &p_bus, Vector<AudioFrame> p_volumes) {
1309
ERR_FAIL_COND(p_volumes.size() != MAX_CHANNELS_PER_BUS);
1310
1311
HashMap<StringName, Vector<AudioFrame>> map;
1312
map[p_bus] = p_volumes;
1313
1314
set_playback_bus_volumes_linear(p_playback, map);
1315
}
1316
1317
void AudioServer::set_playback_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes) {
1318
ERR_FAIL_COND(p_bus_volumes.size() > MAX_BUSES_PER_PLAYBACK);
1319
1320
// Samples.
1321
if (p_playback->get_is_sample() && p_playback->get_sample_playback().is_valid()) {
1322
Ref<AudioSamplePlayback> sample_playback = p_playback->get_sample_playback();
1323
AudioDriver::get_singleton()->set_sample_playback_bus_volumes_linear(sample_playback, p_bus_volumes);
1324
return;
1325
}
1326
1327
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1328
if (!playback_node) {
1329
return;
1330
}
1331
AudioStreamPlaybackBusDetails *old_bus_details, *new_bus_details = new AudioStreamPlaybackBusDetails();
1332
1333
int idx = 0;
1334
for (KeyValue<StringName, Vector<AudioFrame>> pair : p_bus_volumes) {
1335
if (idx >= MAX_BUSES_PER_PLAYBACK) {
1336
break;
1337
}
1338
if (pair.value.size() < channel_count || pair.value.size() != MAX_CHANNELS_PER_BUS) {
1339
delete new_bus_details;
1340
ERR_FAIL();
1341
}
1342
1343
new_bus_details->bus_active[idx] = true;
1344
new_bus_details->bus[idx] = pair.key;
1345
for (int channel_idx = 0; channel_idx < MAX_CHANNELS_PER_BUS; channel_idx++) {
1346
new_bus_details->volume[idx][channel_idx] = pair.value[channel_idx];
1347
}
1348
idx++;
1349
}
1350
1351
do {
1352
old_bus_details = playback_node->bus_details.load();
1353
} while (!playback_node->bus_details.compare_exchange_strong(old_bus_details, new_bus_details));
1354
1355
bus_details_graveyard.insert(old_bus_details);
1356
}
1357
1358
void AudioServer::set_playback_all_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, Vector<AudioFrame> p_volumes) {
1359
ERR_FAIL_COND(p_playback.is_null());
1360
ERR_FAIL_COND(p_volumes.size() != MAX_CHANNELS_PER_BUS);
1361
1362
HashMap<StringName, Vector<AudioFrame>> map;
1363
1364
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1365
if (!playback_node) {
1366
return;
1367
}
1368
for (int bus_idx = 0; bus_idx < MAX_BUSES_PER_PLAYBACK; bus_idx++) {
1369
if (playback_node->bus_details.load()->bus_active[bus_idx]) {
1370
map[playback_node->bus_details.load()->bus[bus_idx]] = p_volumes;
1371
}
1372
}
1373
1374
set_playback_bus_volumes_linear(p_playback, map);
1375
}
1376
1377
void AudioServer::set_playback_pitch_scale(Ref<AudioStreamPlayback> p_playback, float p_pitch_scale) {
1378
ERR_FAIL_COND(p_playback.is_null());
1379
1380
// Samples.
1381
if (p_playback->get_is_sample() && p_playback->get_sample_playback().is_valid()) {
1382
Ref<AudioSamplePlayback> sample_playback = p_playback->get_sample_playback();
1383
AudioServer::get_singleton()->update_sample_playback_pitch_scale(sample_playback, p_pitch_scale);
1384
return;
1385
}
1386
1387
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1388
if (!playback_node) {
1389
return;
1390
}
1391
1392
playback_node->pitch_scale.set(p_pitch_scale);
1393
}
1394
1395
void AudioServer::set_playback_paused(Ref<AudioStreamPlayback> p_playback, bool p_paused) {
1396
ERR_FAIL_COND(p_playback.is_null());
1397
1398
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1399
if (!playback_node) {
1400
return;
1401
}
1402
1403
AudioStreamPlaybackListNode::PlaybackState new_state, old_state;
1404
do {
1405
old_state = playback_node->state.load();
1406
new_state = p_paused ? AudioStreamPlaybackListNode::FADE_OUT_TO_PAUSE : AudioStreamPlaybackListNode::PLAYING;
1407
if (!p_paused && old_state == AudioStreamPlaybackListNode::PLAYING) {
1408
return; // No-op.
1409
}
1410
if (p_paused && (old_state == AudioStreamPlaybackListNode::PAUSED || old_state == AudioStreamPlaybackListNode::FADE_OUT_TO_PAUSE)) {
1411
return; // No-op.
1412
}
1413
1414
} while (!playback_node->state.compare_exchange_strong(old_state, new_state));
1415
}
1416
1417
void AudioServer::set_playback_highshelf_params(Ref<AudioStreamPlayback> p_playback, float p_gain, float p_attenuation_cutoff_hz) {
1418
ERR_FAIL_COND(p_playback.is_null());
1419
1420
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1421
if (!playback_node) {
1422
return;
1423
}
1424
1425
playback_node->attenuation_filter_cutoff_hz.set(p_attenuation_cutoff_hz);
1426
playback_node->highshelf_gain.set(p_gain);
1427
}
1428
1429
bool AudioServer::is_playback_active(Ref<AudioStreamPlayback> p_playback) {
1430
ERR_FAIL_COND_V(p_playback.is_null(), false);
1431
1432
if (p_playback->get_is_sample()) {
1433
if (p_playback->get_sample_playback().is_valid()) {
1434
return sample_playback_list.has(p_playback->get_sample_playback());
1435
} else {
1436
return false;
1437
}
1438
}
1439
1440
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1441
if (!playback_node) {
1442
return false;
1443
}
1444
1445
return playback_node->state.load() == AudioStreamPlaybackListNode::PLAYING;
1446
}
1447
1448
float AudioServer::get_playback_position(Ref<AudioStreamPlayback> p_playback) {
1449
ERR_FAIL_COND_V(p_playback.is_null(), 0);
1450
1451
// Samples.
1452
if (p_playback->get_is_sample() && p_playback->get_sample_playback().is_valid()) {
1453
Ref<AudioSamplePlayback> sample_playback = p_playback->get_sample_playback();
1454
return AudioServer::get_singleton()->get_sample_playback_position(sample_playback);
1455
}
1456
1457
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1458
if (!playback_node) {
1459
return 0;
1460
}
1461
1462
return playback_node->stream_playback->get_playback_position();
1463
}
1464
1465
bool AudioServer::is_playback_paused(Ref<AudioStreamPlayback> p_playback) {
1466
ERR_FAIL_COND_V(p_playback.is_null(), false);
1467
1468
AudioStreamPlaybackListNode *playback_node = _find_playback_list_node(p_playback);
1469
if (!playback_node) {
1470
return false;
1471
}
1472
1473
return playback_node->state.load() == AudioStreamPlaybackListNode::PAUSED || playback_node->state.load() == AudioStreamPlaybackListNode::FADE_OUT_TO_PAUSE;
1474
}
1475
1476
uint64_t AudioServer::get_mix_count() const {
1477
return mix_count;
1478
}
1479
1480
uint64_t AudioServer::get_mixed_frames() const {
1481
return mix_frames;
1482
}
1483
1484
String AudioServer::get_driver_name() const {
1485
return AudioDriver::get_singleton()->get_name();
1486
}
1487
1488
void AudioServer::notify_listener_changed() {
1489
for (CallbackItem *ci : listener_changed_callback_list) {
1490
ci->callback(ci->userdata);
1491
}
1492
}
1493
1494
void AudioServer::init_channels_and_buffers() {
1495
channel_count = get_channel_count();
1496
temp_buffer.resize(channel_count);
1497
mix_buffer.resize(buffer_size + LOOKAHEAD_BUFFER_SIZE);
1498
1499
for (int i = 0; i < temp_buffer.size(); i++) {
1500
temp_buffer.write[i].resize(buffer_size);
1501
}
1502
1503
for (int i = 0; i < buses.size(); i++) {
1504
buses[i]->channels.resize(channel_count);
1505
for (int j = 0; j < channel_count; j++) {
1506
buses.write[i]->channels.write[j].buffer.resize(buffer_size);
1507
}
1508
_update_bus_effects(i);
1509
}
1510
}
1511
1512
void AudioServer::init() {
1513
channel_disable_threshold_db = GLOBAL_DEF_RST(PropertyInfo(Variant::FLOAT, "audio/buses/channel_disable_threshold_db", PROPERTY_HINT_RANGE, "-80,0,0.1,suffix:dB"), -60.0);
1514
channel_disable_frames = float(GLOBAL_DEF_RST(PropertyInfo(Variant::FLOAT, "audio/buses/channel_disable_time", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater"), 2.0)) * get_mix_rate();
1515
// TODO: Buffer size is hardcoded for now. This would be really nice to have as a project setting because currently it limits audio latency to an absolute minimum of 11ms with default mix rate, but there's some additional work required to make that happen. See TODOs in `_mix_step_for_channel`.
1516
// When this becomes a project setting, it should be specified in milliseconds rather than raw sample count, because 512 samples at 192khz is shorter than it is at 48khz, for example.
1517
buffer_size = 512;
1518
1519
init_channels_and_buffers();
1520
1521
mix_count = 0;
1522
set_bus_count(1);
1523
set_bus_name(0, "Master");
1524
1525
if (AudioDriver::get_singleton()) {
1526
AudioDriver::get_singleton()->start();
1527
AudioDriver::get_singleton()->set_sample_bus_count(1);
1528
}
1529
1530
#ifdef TOOLS_ENABLED
1531
set_edited(false); //avoid editors from thinking this was edited
1532
#endif
1533
1534
GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "audio/video/video_delay_compensation_ms", PROPERTY_HINT_RANGE, "-1000,1000,1,suffix:ms"), 0);
1535
}
1536
1537
void AudioServer::update() {
1538
#ifdef DEBUG_ENABLED
1539
if (EngineDebugger::is_profiling(SNAME("servers"))) {
1540
// Driver time includes server time + effects times
1541
// Server time includes effects times
1542
uint64_t driver_time = AudioDriver::get_singleton()->get_profiling_time();
1543
uint64_t server_time = prof_time.get();
1544
1545
// Subtract the server time from the driver time
1546
if (driver_time > server_time) {
1547
driver_time -= server_time;
1548
}
1549
1550
Array values;
1551
1552
for (int i = buses.size() - 1; i >= 0; i--) {
1553
Bus *bus = buses[i];
1554
if (bus->bypass) {
1555
continue;
1556
}
1557
1558
for (int j = 0; j < bus->effects.size(); j++) {
1559
if (!bus->effects[j].enabled) {
1560
continue;
1561
}
1562
1563
values.push_back(String(bus->name) + bus->effects[j].effect->get_name());
1564
values.push_back(USEC_TO_SEC(bus->effects[j].prof_time));
1565
1566
// Subtract the effect time from the driver and server times
1567
if (driver_time > bus->effects[j].prof_time) {
1568
driver_time -= bus->effects[j].prof_time;
1569
}
1570
if (server_time > bus->effects[j].prof_time) {
1571
server_time -= bus->effects[j].prof_time;
1572
}
1573
}
1574
}
1575
1576
values.push_back("audio_server");
1577
values.push_back(USEC_TO_SEC(server_time));
1578
values.push_back("audio_driver");
1579
values.push_back(USEC_TO_SEC(driver_time));
1580
1581
values.push_front("audio_thread");
1582
EngineDebugger::profiler_add_frame_data("servers", values);
1583
}
1584
1585
// Reset profiling times
1586
for (int i = buses.size() - 1; i >= 0; i--) {
1587
Bus *bus = buses[i];
1588
if (bus->bypass) {
1589
continue;
1590
}
1591
1592
for (int j = 0; j < bus->effects.size(); j++) {
1593
if (!bus->effects[j].enabled) {
1594
continue;
1595
}
1596
1597
bus->effects.write[j].prof_time = 0;
1598
}
1599
}
1600
1601
AudioDriver::get_singleton()->reset_profiling_time();
1602
prof_time.set(0);
1603
#endif
1604
1605
for (CallbackItem *ci : update_callback_list) {
1606
ci->callback(ci->userdata);
1607
}
1608
mix_callback_list.maybe_cleanup();
1609
update_callback_list.maybe_cleanup();
1610
listener_changed_callback_list.maybe_cleanup();
1611
playback_list.maybe_cleanup();
1612
for (AudioStreamPlaybackBusDetails *bus_details : bus_details_graveyard_frame_old) {
1613
bus_details_graveyard_frame_old.erase(bus_details, [](AudioStreamPlaybackBusDetails *d) { delete d; });
1614
}
1615
for (AudioStreamPlaybackBusDetails *bus_details : bus_details_graveyard) {
1616
bus_details_graveyard_frame_old.insert(bus_details);
1617
bus_details_graveyard.erase(bus_details);
1618
}
1619
bus_details_graveyard.maybe_cleanup();
1620
bus_details_graveyard_frame_old.maybe_cleanup();
1621
}
1622
1623
void AudioServer::load_default_bus_layout() {
1624
String layout_path = GLOBAL_GET("audio/buses/default_bus_layout");
1625
1626
if (ResourceLoader::exists(layout_path)) {
1627
Ref<AudioBusLayout> default_layout = ResourceLoader::load(layout_path);
1628
if (default_layout.is_valid()) {
1629
set_bus_layout(default_layout);
1630
}
1631
}
1632
}
1633
1634
void AudioServer::finish() {
1635
for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
1636
AudioDriverManager::get_driver(i)->finish();
1637
}
1638
1639
for (int i = 0; i < buses.size(); i++) {
1640
memdelete(buses[i]);
1641
}
1642
1643
buses.clear();
1644
}
1645
1646
/* MISC config */
1647
1648
void AudioServer::lock() {
1649
AudioDriver::get_singleton()->lock();
1650
}
1651
1652
void AudioServer::unlock() {
1653
AudioDriver::get_singleton()->unlock();
1654
}
1655
1656
AudioServer::SpeakerMode AudioServer::get_speaker_mode() const {
1657
return (AudioServer::SpeakerMode)AudioDriver::get_singleton()->get_speaker_mode();
1658
}
1659
1660
float AudioServer::get_mix_rate() const {
1661
return AudioDriver::get_singleton()->get_mix_rate();
1662
}
1663
1664
float AudioServer::get_input_mix_rate() const {
1665
return AudioDriver::get_singleton()->get_input_mix_rate();
1666
}
1667
1668
float AudioServer::read_output_peak_db() const {
1669
return 0;
1670
}
1671
1672
AudioServer *AudioServer::get_singleton() {
1673
return singleton;
1674
}
1675
1676
double AudioServer::get_output_latency() const {
1677
return AudioDriver::get_singleton()->get_latency();
1678
}
1679
1680
double AudioServer::get_time_to_next_mix() const {
1681
return AudioDriver::get_singleton()->get_time_to_next_mix();
1682
}
1683
1684
double AudioServer::get_time_since_last_mix() const {
1685
return AudioDriver::get_singleton()->get_time_since_last_mix();
1686
}
1687
1688
AudioServer *AudioServer::singleton = nullptr;
1689
1690
void AudioServer::add_update_callback(AudioCallback p_callback, void *p_userdata) {
1691
CallbackItem *ci = new CallbackItem();
1692
ci->callback = p_callback;
1693
ci->userdata = p_userdata;
1694
update_callback_list.insert(ci);
1695
}
1696
1697
void AudioServer::remove_update_callback(AudioCallback p_callback, void *p_userdata) {
1698
for (CallbackItem *ci : update_callback_list) {
1699
if (ci->callback == p_callback && ci->userdata == p_userdata) {
1700
update_callback_list.erase(ci, [](CallbackItem *c) { delete c; });
1701
}
1702
}
1703
}
1704
1705
void AudioServer::add_mix_callback(AudioCallback p_callback, void *p_userdata) {
1706
CallbackItem *ci = new CallbackItem();
1707
ci->callback = p_callback;
1708
ci->userdata = p_userdata;
1709
mix_callback_list.insert(ci);
1710
}
1711
1712
void AudioServer::remove_mix_callback(AudioCallback p_callback, void *p_userdata) {
1713
for (CallbackItem *ci : mix_callback_list) {
1714
if (ci->callback == p_callback && ci->userdata == p_userdata) {
1715
mix_callback_list.erase(ci, [](CallbackItem *c) { delete c; });
1716
}
1717
}
1718
}
1719
1720
void AudioServer::add_listener_changed_callback(AudioCallback p_callback, void *p_userdata) {
1721
CallbackItem *ci = new CallbackItem();
1722
ci->callback = p_callback;
1723
ci->userdata = p_userdata;
1724
listener_changed_callback_list.insert(ci);
1725
}
1726
1727
void AudioServer::remove_listener_changed_callback(AudioCallback p_callback, void *p_userdata) {
1728
for (CallbackItem *ci : listener_changed_callback_list) {
1729
if (ci->callback == p_callback && ci->userdata == p_userdata) {
1730
listener_changed_callback_list.erase(ci, [](CallbackItem *c) { delete c; });
1731
}
1732
}
1733
}
1734
1735
void AudioServer::set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout) {
1736
ERR_FAIL_COND(p_bus_layout.is_null() || p_bus_layout->buses.is_empty());
1737
1738
lock();
1739
for (int i = 0; i < buses.size(); i++) {
1740
memdelete(buses[i]);
1741
}
1742
buses.resize(p_bus_layout->buses.size());
1743
bus_map.clear();
1744
1745
AudioDriver::get_singleton()->set_sample_bus_count(buses.size());
1746
1747
for (int i = 0; i < p_bus_layout->buses.size(); i++) {
1748
Bus *bus = memnew(Bus);
1749
if (i == 0) {
1750
bus->name = SceneStringName(Master);
1751
} else {
1752
bus->name = p_bus_layout->buses[i].name;
1753
bus->send = p_bus_layout->buses[i].send;
1754
AudioDriver::get_singleton()->set_sample_bus_send(i, bus->send);
1755
}
1756
1757
bus->solo = p_bus_layout->buses[i].solo;
1758
bus->mute = p_bus_layout->buses[i].mute;
1759
bus->bypass = p_bus_layout->buses[i].bypass;
1760
bus->volume_db = p_bus_layout->buses[i].volume_db;
1761
1762
AudioDriver::get_singleton()->set_sample_bus_solo(i, bus->solo);
1763
AudioDriver::get_singleton()->set_sample_bus_mute(i, bus->mute);
1764
AudioDriver::get_singleton()->set_sample_bus_volume_db(i, bus->volume_db);
1765
1766
for (int j = 0; j < p_bus_layout->buses[i].effects.size(); j++) {
1767
Ref<AudioEffect> fx = p_bus_layout->buses[i].effects[j].effect;
1768
1769
if (fx.is_valid()) {
1770
Bus::Effect bfx;
1771
bfx.effect = fx;
1772
bfx.enabled = p_bus_layout->buses[i].effects[j].enabled;
1773
#ifdef DEBUG_ENABLED
1774
bfx.prof_time = 0;
1775
#endif
1776
bus->effects.push_back(bfx);
1777
}
1778
}
1779
1780
bus_map[bus->name] = bus;
1781
buses.write[i] = bus;
1782
1783
buses[i]->channels.resize(channel_count);
1784
for (int j = 0; j < channel_count; j++) {
1785
buses.write[i]->channels.write[j].buffer.resize(buffer_size);
1786
}
1787
_update_bus_effects(i);
1788
}
1789
#ifdef TOOLS_ENABLED
1790
set_edited(false);
1791
#endif
1792
unlock();
1793
1794
// Samples bus sync.
1795
}
1796
1797
Ref<AudioBusLayout> AudioServer::generate_bus_layout() const {
1798
Ref<AudioBusLayout> state;
1799
state.instantiate();
1800
1801
state->buses.resize(buses.size());
1802
1803
for (int i = 0; i < buses.size(); i++) {
1804
state->buses.write[i].name = buses[i]->name;
1805
state->buses.write[i].send = buses[i]->send;
1806
state->buses.write[i].mute = buses[i]->mute;
1807
state->buses.write[i].solo = buses[i]->solo;
1808
state->buses.write[i].bypass = buses[i]->bypass;
1809
state->buses.write[i].volume_db = buses[i]->volume_db;
1810
for (int j = 0; j < buses[i]->effects.size(); j++) {
1811
AudioBusLayout::Bus::Effect fx;
1812
fx.effect = buses[i]->effects[j].effect;
1813
fx.enabled = buses[i]->effects[j].enabled;
1814
state->buses.write[i].effects.push_back(fx);
1815
}
1816
}
1817
1818
return state;
1819
}
1820
1821
PackedStringArray AudioServer::get_output_device_list() {
1822
return AudioDriver::get_singleton()->get_output_device_list();
1823
}
1824
1825
String AudioServer::get_output_device() {
1826
return AudioDriver::get_singleton()->get_output_device();
1827
}
1828
1829
void AudioServer::set_output_device(const String &p_name) {
1830
AudioDriver::get_singleton()->set_output_device(p_name);
1831
}
1832
1833
PackedStringArray AudioServer::get_input_device_list() {
1834
return AudioDriver::get_singleton()->get_input_device_list();
1835
}
1836
1837
String AudioServer::get_input_device() {
1838
return AudioDriver::get_singleton()->get_input_device();
1839
}
1840
1841
void AudioServer::set_input_device(const String &p_name) {
1842
AudioDriver::get_singleton()->set_input_device(p_name);
1843
}
1844
1845
void AudioServer::set_enable_tagging_used_audio_streams(bool p_enable) {
1846
tag_used_audio_streams = p_enable;
1847
}
1848
1849
#ifdef TOOLS_ENABLED
1850
void AudioServer::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
1851
const String pf = p_function;
1852
if ((p_idx == 0 && pf == "get_bus_index") || (p_idx == 1 && pf == "set_bus_send")) {
1853
for (const AudioServer::Bus *E : buses) {
1854
r_options->push_back(String(E->name).quote());
1855
}
1856
}
1857
1858
Object::get_argument_options(p_function, p_idx, r_options);
1859
}
1860
#endif
1861
1862
AudioServer::PlaybackType AudioServer::get_default_playback_type() const {
1863
int playback_type = GLOBAL_GET_CACHED(int, "audio/general/default_playback_type");
1864
ERR_FAIL_COND_V_MSG(
1865
playback_type < 0 || playback_type >= PlaybackType::PLAYBACK_TYPE_MAX,
1866
PlaybackType::PLAYBACK_TYPE_STREAM,
1867
vformat(R"(Project settings value (%s) for "audio/general/default_playback_type" is not supported)", playback_type));
1868
1869
switch (playback_type) {
1870
case 1: {
1871
return PlaybackType::PLAYBACK_TYPE_SAMPLE;
1872
} break;
1873
1874
case 0:
1875
default: {
1876
return PlaybackType::PLAYBACK_TYPE_STREAM;
1877
} break;
1878
}
1879
}
1880
1881
bool AudioServer::is_stream_registered_as_sample(const Ref<AudioStream> &p_stream) {
1882
ERR_FAIL_COND_V_MSG(p_stream.is_null(), false, "Parameter p_stream is null.");
1883
return AudioDriver::get_singleton()->is_stream_registered_as_sample(p_stream);
1884
}
1885
1886
void AudioServer::register_stream_as_sample(const Ref<AudioStream> &p_stream) {
1887
ERR_FAIL_COND_MSG(p_stream.is_null(), "Parameter p_stream is null.");
1888
ERR_FAIL_COND_MSG(!(p_stream->can_be_sampled()), "Parameter p_stream cannot be sampled.");
1889
Ref<AudioSample> sample = p_stream->generate_sample();
1890
register_sample(sample);
1891
}
1892
1893
void AudioServer::unregister_stream_as_sample(const Ref<AudioStream> &p_stream) {
1894
ERR_FAIL_COND_MSG(p_stream.is_null(), "Parameter p_stream is null.");
1895
ERR_FAIL_COND_MSG(!(p_stream->can_be_sampled()), "Parameter p_stream cannot be sampled.");
1896
Ref<AudioSample> sample = p_stream->generate_sample();
1897
unregister_sample(sample);
1898
}
1899
1900
void AudioServer::register_sample(const Ref<AudioSample> &p_sample) {
1901
ERR_FAIL_COND_MSG(p_sample.is_null(), "Parameter p_sample is null.");
1902
ERR_FAIL_COND_MSG(p_sample->stream.is_null(), "Parameter p_sample->stream is null.");
1903
ERR_FAIL_COND_MSG(!(p_sample->stream->can_be_sampled()), "Parameter p_stream cannot be sampled.");
1904
AudioDriver::get_singleton()->register_sample(p_sample);
1905
}
1906
1907
void AudioServer::unregister_sample(const Ref<AudioSample> &p_sample) {
1908
ERR_FAIL_COND_MSG(p_sample.is_null(), "Parameter p_sample is null.");
1909
ERR_FAIL_COND_MSG(p_sample->stream.is_null(), "Parameter p_sample->stream is null.");
1910
AudioDriver::get_singleton()->unregister_sample(p_sample);
1911
}
1912
1913
void AudioServer::start_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
1914
ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
1915
AudioDriver::get_singleton()->start_sample_playback(p_playback);
1916
sample_playback_list.ordered_insert(p_playback);
1917
}
1918
1919
void AudioServer::stop_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
1920
ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
1921
if (!sample_playback_list.has(p_playback)) {
1922
return;
1923
}
1924
sample_playback_list.erase(p_playback);
1925
AudioDriver::get_singleton()->stop_sample_playback(p_playback);
1926
p_playback->stream_playback->set_sample_playback(nullptr);
1927
stop_playback_stream(p_playback->stream_playback);
1928
}
1929
1930
void AudioServer::set_sample_playback_pause(const Ref<AudioSamplePlayback> &p_playback, bool p_paused) {
1931
ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
1932
AudioDriver::get_singleton()->set_sample_playback_pause(p_playback, p_paused);
1933
}
1934
1935
bool AudioServer::is_sample_playback_active(const Ref<AudioSamplePlayback> &p_playback) {
1936
ERR_FAIL_COND_V_MSG(p_playback.is_null(), false, "Parameter p_playback is null.");
1937
return sample_playback_list.has(p_playback);
1938
}
1939
1940
double AudioServer::get_sample_playback_position(const Ref<AudioSamplePlayback> &p_playback) {
1941
ERR_FAIL_COND_V_MSG(p_playback.is_null(), false, "Parameter p_playback is null.");
1942
return AudioDriver::get_singleton()->get_sample_playback_position(p_playback);
1943
}
1944
1945
void AudioServer::update_sample_playback_pitch_scale(const Ref<AudioSamplePlayback> &p_playback, float p_pitch_scale) {
1946
ERR_FAIL_COND_MSG(p_playback.is_null(), "Parameter p_playback is null.");
1947
return AudioDriver::get_singleton()->update_sample_playback_pitch_scale(p_playback, p_pitch_scale);
1948
}
1949
1950
void AudioServer::_bind_methods() {
1951
ClassDB::bind_method(D_METHOD("set_bus_count", "amount"), &AudioServer::set_bus_count);
1952
ClassDB::bind_method(D_METHOD("get_bus_count"), &AudioServer::get_bus_count);
1953
1954
ClassDB::bind_method(D_METHOD("remove_bus", "index"), &AudioServer::remove_bus);
1955
ClassDB::bind_method(D_METHOD("add_bus", "at_position"), &AudioServer::add_bus, DEFVAL(-1));
1956
ClassDB::bind_method(D_METHOD("move_bus", "index", "to_index"), &AudioServer::move_bus);
1957
1958
ClassDB::bind_method(D_METHOD("set_bus_name", "bus_idx", "name"), &AudioServer::set_bus_name);
1959
ClassDB::bind_method(D_METHOD("get_bus_name", "bus_idx"), &AudioServer::get_bus_name);
1960
ClassDB::bind_method(D_METHOD("get_bus_index", "bus_name"), &AudioServer::get_bus_index);
1961
1962
ClassDB::bind_method(D_METHOD("get_bus_channels", "bus_idx"), &AudioServer::get_bus_channels);
1963
1964
ClassDB::bind_method(D_METHOD("set_bus_volume_db", "bus_idx", "volume_db"), &AudioServer::set_bus_volume_db);
1965
ClassDB::bind_method(D_METHOD("get_bus_volume_db", "bus_idx"), &AudioServer::get_bus_volume_db);
1966
1967
ClassDB::bind_method(D_METHOD("set_bus_volume_linear", "bus_idx", "volume_linear"), &AudioServer::set_bus_volume_linear);
1968
ClassDB::bind_method(D_METHOD("get_bus_volume_linear", "bus_idx"), &AudioServer::get_bus_volume_linear);
1969
1970
ClassDB::bind_method(D_METHOD("set_bus_send", "bus_idx", "send"), &AudioServer::set_bus_send);
1971
ClassDB::bind_method(D_METHOD("get_bus_send", "bus_idx"), &AudioServer::get_bus_send);
1972
1973
ClassDB::bind_method(D_METHOD("set_bus_solo", "bus_idx", "enable"), &AudioServer::set_bus_solo);
1974
ClassDB::bind_method(D_METHOD("is_bus_solo", "bus_idx"), &AudioServer::is_bus_solo);
1975
1976
ClassDB::bind_method(D_METHOD("set_bus_mute", "bus_idx", "enable"), &AudioServer::set_bus_mute);
1977
ClassDB::bind_method(D_METHOD("is_bus_mute", "bus_idx"), &AudioServer::is_bus_mute);
1978
1979
ClassDB::bind_method(D_METHOD("set_bus_bypass_effects", "bus_idx", "enable"), &AudioServer::set_bus_bypass_effects);
1980
ClassDB::bind_method(D_METHOD("is_bus_bypassing_effects", "bus_idx"), &AudioServer::is_bus_bypassing_effects);
1981
1982
ClassDB::bind_method(D_METHOD("add_bus_effect", "bus_idx", "effect", "at_position"), &AudioServer::add_bus_effect, DEFVAL(-1));
1983
ClassDB::bind_method(D_METHOD("remove_bus_effect", "bus_idx", "effect_idx"), &AudioServer::remove_bus_effect);
1984
1985
ClassDB::bind_method(D_METHOD("get_bus_effect_count", "bus_idx"), &AudioServer::get_bus_effect_count);
1986
ClassDB::bind_method(D_METHOD("get_bus_effect", "bus_idx", "effect_idx"), &AudioServer::get_bus_effect);
1987
ClassDB::bind_method(D_METHOD("get_bus_effect_instance", "bus_idx", "effect_idx", "channel"), &AudioServer::get_bus_effect_instance, DEFVAL(0));
1988
ClassDB::bind_method(D_METHOD("swap_bus_effects", "bus_idx", "effect_idx", "by_effect_idx"), &AudioServer::swap_bus_effects);
1989
1990
ClassDB::bind_method(D_METHOD("set_bus_effect_enabled", "bus_idx", "effect_idx", "enabled"), &AudioServer::set_bus_effect_enabled);
1991
ClassDB::bind_method(D_METHOD("is_bus_effect_enabled", "bus_idx", "effect_idx"), &AudioServer::is_bus_effect_enabled);
1992
1993
ClassDB::bind_method(D_METHOD("get_bus_peak_volume_left_db", "bus_idx", "channel"), &AudioServer::get_bus_peak_volume_left_db);
1994
ClassDB::bind_method(D_METHOD("get_bus_peak_volume_right_db", "bus_idx", "channel"), &AudioServer::get_bus_peak_volume_right_db);
1995
1996
ClassDB::bind_method(D_METHOD("set_playback_speed_scale", "scale"), &AudioServer::set_playback_speed_scale);
1997
ClassDB::bind_method(D_METHOD("get_playback_speed_scale"), &AudioServer::get_playback_speed_scale);
1998
1999
ClassDB::bind_method(D_METHOD("lock"), &AudioServer::lock);
2000
ClassDB::bind_method(D_METHOD("unlock"), &AudioServer::unlock);
2001
2002
ClassDB::bind_method(D_METHOD("get_speaker_mode"), &AudioServer::get_speaker_mode);
2003
ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioServer::get_mix_rate);
2004
ClassDB::bind_method(D_METHOD("get_input_mix_rate"), &AudioServer::get_input_mix_rate);
2005
2006
ClassDB::bind_method(D_METHOD("get_driver_name"), &AudioServer::get_driver_name);
2007
2008
ClassDB::bind_method(D_METHOD("get_output_device_list"), &AudioServer::get_output_device_list);
2009
ClassDB::bind_method(D_METHOD("get_output_device"), &AudioServer::get_output_device);
2010
ClassDB::bind_method(D_METHOD("set_output_device", "name"), &AudioServer::set_output_device);
2011
2012
ClassDB::bind_method(D_METHOD("get_time_to_next_mix"), &AudioServer::get_time_to_next_mix);
2013
ClassDB::bind_method(D_METHOD("get_time_since_last_mix"), &AudioServer::get_time_since_last_mix);
2014
ClassDB::bind_method(D_METHOD("get_output_latency"), &AudioServer::get_output_latency);
2015
2016
ClassDB::bind_method(D_METHOD("get_input_device_list"), &AudioServer::get_input_device_list);
2017
ClassDB::bind_method(D_METHOD("get_input_device"), &AudioServer::get_input_device);
2018
ClassDB::bind_method(D_METHOD("set_input_device", "name"), &AudioServer::set_input_device);
2019
2020
ClassDB::bind_method(D_METHOD("set_bus_layout", "bus_layout"), &AudioServer::set_bus_layout);
2021
ClassDB::bind_method(D_METHOD("generate_bus_layout"), &AudioServer::generate_bus_layout);
2022
2023
ClassDB::bind_method(D_METHOD("set_enable_tagging_used_audio_streams", "enable"), &AudioServer::set_enable_tagging_used_audio_streams);
2024
2025
ClassDB::bind_method(D_METHOD("is_stream_registered_as_sample", "stream"), &AudioServer::is_stream_registered_as_sample);
2026
ClassDB::bind_method(D_METHOD("register_stream_as_sample", "stream"), &AudioServer::register_stream_as_sample);
2027
2028
ADD_PROPERTY(PropertyInfo(Variant::INT, "bus_count"), "set_bus_count", "get_bus_count");
2029
ADD_PROPERTY(PropertyInfo(Variant::STRING, "output_device"), "set_output_device", "get_output_device");
2030
ADD_PROPERTY(PropertyInfo(Variant::STRING, "input_device"), "set_input_device", "get_input_device");
2031
// The default value may be set to an empty string by the platform-specific audio driver.
2032
// Override for class reference generation purposes.
2033
ADD_PROPERTY_DEFAULT("input_device", "Default");
2034
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "playback_speed_scale"), "set_playback_speed_scale", "get_playback_speed_scale");
2035
2036
ADD_SIGNAL(MethodInfo("bus_layout_changed"));
2037
ADD_SIGNAL(MethodInfo("bus_renamed", PropertyInfo(Variant::INT, "bus_index"), PropertyInfo(Variant::STRING_NAME, "old_name"), PropertyInfo(Variant::STRING_NAME, "new_name")));
2038
2039
BIND_ENUM_CONSTANT(SPEAKER_MODE_STEREO);
2040
BIND_ENUM_CONSTANT(SPEAKER_SURROUND_31);
2041
BIND_ENUM_CONSTANT(SPEAKER_SURROUND_51);
2042
BIND_ENUM_CONSTANT(SPEAKER_SURROUND_71);
2043
2044
BIND_ENUM_CONSTANT(PLAYBACK_TYPE_DEFAULT);
2045
BIND_ENUM_CONSTANT(PLAYBACK_TYPE_STREAM);
2046
BIND_ENUM_CONSTANT(PLAYBACK_TYPE_SAMPLE);
2047
BIND_ENUM_CONSTANT(PLAYBACK_TYPE_MAX);
2048
}
2049
2050
AudioServer::AudioServer() {
2051
singleton = this;
2052
}
2053
2054
AudioServer::~AudioServer() {
2055
singleton = nullptr;
2056
}
2057
2058
/////////////////////////////////
2059
2060
bool AudioBusLayout::_set(const StringName &p_name, const Variant &p_value) {
2061
String s = p_name;
2062
if (s.begins_with("bus/")) {
2063
int index = s.get_slicec('/', 1).to_int();
2064
if (buses.size() <= index) {
2065
buses.resize(index + 1);
2066
}
2067
2068
Bus &bus = buses.write[index];
2069
2070
String what = s.get_slicec('/', 2);
2071
2072
if (what == "name") {
2073
bus.name = p_value;
2074
} else if (what == "solo") {
2075
bus.solo = p_value;
2076
} else if (what == "mute") {
2077
bus.mute = p_value;
2078
} else if (what == "bypass_fx") {
2079
bus.bypass = p_value;
2080
} else if (what == "volume_db") {
2081
bus.volume_db = p_value;
2082
} else if (what == "send") {
2083
bus.send = p_value;
2084
} else if (what == "effect") {
2085
int which = s.get_slicec('/', 3).to_int();
2086
if (bus.effects.size() <= which) {
2087
bus.effects.resize(which + 1);
2088
}
2089
2090
Bus::Effect &fx = bus.effects.write[which];
2091
2092
String fxwhat = s.get_slicec('/', 4);
2093
if (fxwhat == "effect") {
2094
fx.effect = p_value;
2095
} else if (fxwhat == "enabled") {
2096
fx.enabled = p_value;
2097
} else {
2098
return false;
2099
}
2100
2101
return true;
2102
} else {
2103
return false;
2104
}
2105
2106
return true;
2107
}
2108
2109
return false;
2110
}
2111
2112
bool AudioBusLayout::_get(const StringName &p_name, Variant &r_ret) const {
2113
String s = p_name;
2114
if (s.begins_with("bus/")) {
2115
int index = s.get_slicec('/', 1).to_int();
2116
if (index < 0 || index >= buses.size()) {
2117
return false;
2118
}
2119
2120
const Bus &bus = buses[index];
2121
2122
String what = s.get_slicec('/', 2);
2123
2124
if (what == "name") {
2125
r_ret = bus.name;
2126
} else if (what == "solo") {
2127
r_ret = bus.solo;
2128
} else if (what == "mute") {
2129
r_ret = bus.mute;
2130
} else if (what == "bypass_fx") {
2131
r_ret = bus.bypass;
2132
} else if (what == "volume_db") {
2133
r_ret = bus.volume_db;
2134
} else if (what == "send") {
2135
r_ret = bus.send;
2136
} else if (what == "effect") {
2137
int which = s.get_slicec('/', 3).to_int();
2138
if (which < 0 || which >= bus.effects.size()) {
2139
return false;
2140
}
2141
2142
const Bus::Effect &fx = bus.effects[which];
2143
2144
String fxwhat = s.get_slicec('/', 4);
2145
if (fxwhat == "effect") {
2146
r_ret = fx.effect;
2147
} else if (fxwhat == "enabled") {
2148
r_ret = fx.enabled;
2149
} else {
2150
return false;
2151
}
2152
2153
return true;
2154
} else {
2155
return false;
2156
}
2157
2158
return true;
2159
}
2160
2161
return false;
2162
}
2163
2164
void AudioBusLayout::_get_property_list(List<PropertyInfo> *p_list) const {
2165
for (int i = 0; i < buses.size(); i++) {
2166
p_list->push_back(PropertyInfo(Variant::STRING, "bus/" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2167
p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/solo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2168
p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/mute", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2169
p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/bypass_fx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2170
p_list->push_back(PropertyInfo(Variant::FLOAT, "bus/" + itos(i) + "/volume_db", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2171
p_list->push_back(PropertyInfo(Variant::FLOAT, "bus/" + itos(i) + "/send", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2172
2173
for (int j = 0; j < buses[i].effects.size(); j++) {
2174
p_list->push_back(PropertyInfo(Variant::OBJECT, "bus/" + itos(i) + "/effect/" + itos(j) + "/effect", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2175
p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/effect/" + itos(j) + "/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
2176
}
2177
}
2178
}
2179
2180
AudioBusLayout::AudioBusLayout() {
2181
buses.resize(1);
2182
buses.write[0].name = SceneStringName(Master);
2183
}
2184
2185