Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/servers/audio/audio_server.h
21362 views
1
/**************************************************************************/
2
/* audio_server.h */
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
#pragma once
32
33
#include "core/math/audio_frame.h"
34
#include "core/object/class_db.h"
35
#include "core/os/os.h"
36
#include "core/templates/safe_list.h"
37
#include "core/variant/variant.h"
38
#include "servers/audio/audio_effect.h"
39
#include "servers/audio/audio_filter_sw.h"
40
41
#include <atomic>
42
43
class AudioDriverDummy;
44
class AudioSample;
45
class AudioStream;
46
class AudioStreamWAV;
47
class AudioStreamPlayback;
48
class AudioSamplePlayback;
49
50
class AudioDriver {
51
static AudioDriver *singleton;
52
uint64_t _last_mix_time = 0;
53
uint64_t _last_mix_frames = 0;
54
55
#ifdef DEBUG_ENABLED
56
SafeNumeric<uint64_t> prof_ticks;
57
SafeNumeric<uint64_t> prof_time;
58
#endif
59
60
protected:
61
Vector<int32_t> input_buffer;
62
unsigned int input_position = 0;
63
unsigned int input_size = 0;
64
65
void audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time = true);
66
void update_mix_time(int p_frames);
67
void input_buffer_init(int driver_buffer_frames);
68
void input_buffer_write(int32_t sample);
69
70
int _get_configured_mix_rate();
71
72
#ifdef DEBUG_ENABLED
73
_FORCE_INLINE_ void start_counting_ticks() { prof_ticks.set(OS::get_singleton()->get_ticks_usec()); }
74
_FORCE_INLINE_ void stop_counting_ticks() { prof_time.add(OS::get_singleton()->get_ticks_usec() - prof_ticks.get()); }
75
#else
76
_FORCE_INLINE_ void start_counting_ticks() {}
77
_FORCE_INLINE_ void stop_counting_ticks() {}
78
#endif
79
80
public:
81
double get_time_since_last_mix(); //useful for video -> audio sync
82
double get_time_to_next_mix();
83
84
enum SpeakerMode {
85
SPEAKER_MODE_STEREO,
86
SPEAKER_SURROUND_31,
87
SPEAKER_SURROUND_51,
88
SPEAKER_SURROUND_71,
89
};
90
91
static AudioDriver *get_singleton();
92
void set_singleton();
93
94
// Virtual API to implement.
95
96
virtual const char *get_name() const = 0;
97
98
virtual Error init() = 0;
99
virtual void start() = 0;
100
virtual int get_mix_rate() const = 0;
101
virtual int get_input_mix_rate() const { return get_mix_rate(); }
102
virtual SpeakerMode get_speaker_mode() const = 0;
103
virtual float get_latency() { return 0; }
104
105
virtual void lock() = 0;
106
virtual void unlock() = 0;
107
virtual void finish() = 0;
108
109
virtual PackedStringArray get_output_device_list();
110
virtual String get_output_device();
111
virtual void set_output_device(const String &p_name) {}
112
113
virtual Error input_start() { return FAILED; }
114
virtual Error input_stop() { return FAILED; }
115
116
virtual PackedStringArray get_input_device_list();
117
virtual String get_input_device() { return "Default"; }
118
virtual void set_input_device(const String &p_name) {}
119
120
//
121
122
SpeakerMode get_speaker_mode_by_total_channels(int p_channels) const;
123
int get_total_channels_by_speaker_mode(SpeakerMode) const;
124
125
Vector<int32_t> get_input_buffer() { return input_buffer; }
126
unsigned int get_input_position() { return input_position; }
127
unsigned int get_input_size() { return input_size; }
128
129
#ifdef DEBUG_ENABLED
130
uint64_t get_profiling_time() const { return prof_time.get(); }
131
void reset_profiling_time() { prof_time.set(0); }
132
#endif
133
134
// Samples handling.
135
virtual bool is_stream_registered_as_sample(const Ref<AudioStream> &p_stream) const {
136
return false;
137
}
138
virtual void register_sample(const Ref<AudioSample> &p_sample) {}
139
virtual void unregister_sample(const Ref<AudioSample> &p_sample) {}
140
virtual void start_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
141
virtual void stop_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {}
142
virtual void set_sample_playback_pause(const Ref<AudioSamplePlayback> &p_playback, bool p_paused) {}
143
virtual bool is_sample_playback_active(const Ref<AudioSamplePlayback> &p_playback) { return false; }
144
virtual double get_sample_playback_position(const Ref<AudioSamplePlayback> &p_playback) { return false; }
145
virtual void update_sample_playback_pitch_scale(const Ref<AudioSamplePlayback> &p_playback, float p_pitch_scale = 0.0f) {}
146
virtual void set_sample_playback_bus_volumes_linear(const Ref<AudioSamplePlayback> &p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes) {}
147
148
virtual void set_sample_bus_count(int p_count) {}
149
virtual void remove_sample_bus(int p_bus) {}
150
virtual void add_sample_bus(int p_at_pos = -1) {}
151
virtual void move_sample_bus(int p_bus, int p_to_pos) {}
152
virtual void set_sample_bus_send(int p_bus, const StringName &p_send) {}
153
virtual void set_sample_bus_volume_db(int p_bus, float p_volume_db) {}
154
virtual void set_sample_bus_solo(int p_bus, bool p_enable) {}
155
virtual void set_sample_bus_mute(int p_bus, bool p_enable) {}
156
157
AudioDriver() {}
158
virtual ~AudioDriver() {}
159
};
160
161
class AudioDriverManager {
162
enum {
163
MAX_DRIVERS = 10
164
};
165
166
static AudioDriver *drivers[MAX_DRIVERS];
167
static int driver_count;
168
169
static AudioDriverDummy dummy_driver;
170
171
public:
172
static const int DEFAULT_MIX_RATE = 44100;
173
174
static void add_driver(AudioDriver *p_driver);
175
static void initialize(int p_driver);
176
static int get_driver_count();
177
static AudioDriver *get_driver(int p_driver);
178
};
179
180
class AudioBusLayout;
181
182
class AudioServer : public Object {
183
GDCLASS(AudioServer, Object);
184
185
public:
186
//re-expose this here, as AudioDriver is not exposed to script
187
enum SpeakerMode {
188
SPEAKER_MODE_STEREO,
189
SPEAKER_SURROUND_31,
190
SPEAKER_SURROUND_51,
191
SPEAKER_SURROUND_71,
192
};
193
194
enum PlaybackType {
195
PLAYBACK_TYPE_DEFAULT,
196
PLAYBACK_TYPE_STREAM,
197
PLAYBACK_TYPE_SAMPLE,
198
PLAYBACK_TYPE_MAX
199
};
200
201
enum {
202
AUDIO_DATA_INVALID_ID = -1,
203
MAX_CHANNELS_PER_BUS = 4,
204
MAX_BUSES_PER_PLAYBACK = 6,
205
LOOKAHEAD_BUFFER_SIZE = 64,
206
};
207
208
typedef void (*AudioCallback)(void *p_userdata);
209
210
private:
211
uint64_t mix_time = 0;
212
int mix_size = 0;
213
214
uint32_t buffer_size = 0;
215
uint64_t mix_count = 0;
216
uint64_t mix_frames = 0;
217
#ifdef DEBUG_ENABLED
218
SafeNumeric<uint64_t> prof_time;
219
#endif
220
221
float channel_disable_threshold_db = 0.0f;
222
uint32_t channel_disable_frames = 0;
223
224
int channel_count = 0;
225
int to_mix = 0;
226
227
float playback_speed_scale = 1.0f;
228
229
bool tag_used_audio_streams = false;
230
231
#ifdef DEBUG_ENABLED
232
bool debug_mute = false;
233
#endif // DEBUG_ENABLED
234
235
bool input_device_active = false;
236
int input_buffer_ofs = 0;
237
238
struct Bus {
239
StringName name;
240
bool solo = false;
241
bool mute = false;
242
bool bypass = false;
243
244
bool soloed = false;
245
246
// Each channel is a stereo pair.
247
struct Channel {
248
bool used = false;
249
bool active = false;
250
AudioFrame peak_volume = AudioFrame(AUDIO_MIN_PEAK_DB, AUDIO_MIN_PEAK_DB);
251
Vector<AudioFrame> buffer;
252
Vector<Ref<AudioEffectInstance>> effect_instances;
253
uint64_t last_mix_with_audio = 0;
254
Channel() {}
255
};
256
257
Vector<Channel> channels;
258
259
struct Effect {
260
Ref<AudioEffect> effect;
261
bool enabled = false;
262
#ifdef DEBUG_ENABLED
263
uint64_t prof_time = 0;
264
#endif
265
};
266
267
Vector<Effect> effects;
268
float volume_db = 0.0f;
269
StringName send;
270
int index_cache = 0;
271
};
272
273
struct AudioStreamPlaybackBusDetails {
274
bool bus_active[MAX_BUSES_PER_PLAYBACK] = {};
275
StringName bus[MAX_BUSES_PER_PLAYBACK];
276
AudioFrame volume[MAX_BUSES_PER_PLAYBACK][MAX_CHANNELS_PER_BUS];
277
};
278
279
struct AudioStreamPlaybackListNode {
280
// The state machine for audio stream playbacks is as follows:
281
// 1. The playback is created and added to the playback list in the playing state.
282
// 2. The playback is (maybe) paused, and the state is set to FADE_OUT_TO_PAUSE.
283
// 2.1. The playback is mixed after being paused, and the audio server thread atomically sets the state to PAUSED after performing a brief fade-out.
284
// 3. The playback is (maybe) deleted, and the state is set to FADE_OUT_TO_DELETION.
285
// 3.1. The playback is mixed after being deleted, and the audio server thread atomically sets the state to AWAITING_DELETION after performing a brief fade-out.
286
// NOTE: The playback is not deallocated at this time because allocation and deallocation are not realtime-safe.
287
// 4. The playback is removed and deallocated on the main thread using the SafeList maybe_cleanup method.
288
enum PlaybackState {
289
PAUSED = 0, // Paused. Keep this stream playback around though so it can be restarted.
290
PLAYING = 1, // Playing. Fading may still be necessary if volume changes!
291
FADE_OUT_TO_PAUSE = 2, // About to pause.
292
FADE_OUT_TO_DELETION = 3, // About to stop.
293
AWAITING_DELETION = 4,
294
};
295
// If zero or positive, a place in the stream to seek to during the next mix.
296
SafeNumeric<float> setseek;
297
SafeNumeric<float> pitch_scale;
298
SafeNumeric<float> highshelf_gain;
299
SafeNumeric<float> attenuation_filter_cutoff_hz; // This isn't used unless highshelf_gain is nonzero.
300
AudioFilterSW::Processor filter_process[8];
301
// Updating this ref after the list node is created breaks consistency guarantees, don't do it!
302
Ref<AudioStreamPlayback> stream_playback;
303
// Playback state determines the fate of a particular AudioStreamListNode during the mix step. Must be atomically replaced.
304
std::atomic<PlaybackState> state = AWAITING_DELETION;
305
// This data should only ever be modified by an atomic replacement of the pointer.
306
std::atomic<AudioStreamPlaybackBusDetails *> bus_details = nullptr;
307
// Previous bus details should only be accessed on the audio thread.
308
AudioStreamPlaybackBusDetails *prev_bus_details = nullptr;
309
// The next few samples are stored here so we have some time to fade audio out if it ends abruptly at the beginning of the next mix.
310
AudioFrame lookahead[LOOKAHEAD_BUFFER_SIZE];
311
};
312
313
SafeList<AudioStreamPlaybackListNode *> playback_list;
314
SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard;
315
void _delete_stream_playback(Ref<AudioStreamPlayback> p_playback);
316
void _delete_stream_playback_list_node(AudioStreamPlaybackListNode *p_node);
317
318
// TODO document if this is necessary.
319
SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard_frame_old;
320
321
Vector<Vector<AudioFrame>> temp_buffer; //temp_buffer for each level
322
Vector<AudioFrame> mix_buffer;
323
Vector<Bus *> buses;
324
HashMap<StringName, Bus *> bus_map;
325
326
void _update_bus_effects(int p_bus);
327
328
static AudioServer *singleton;
329
330
void init_channels_and_buffers();
331
332
void _mix_step();
333
void _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);
334
335
// Should only be called on the main thread.
336
AudioStreamPlaybackListNode *_find_playback_list_node(Ref<AudioStreamPlayback> p_playback);
337
338
struct CallbackItem {
339
AudioCallback callback;
340
void *userdata = nullptr;
341
};
342
343
SafeList<CallbackItem *> update_callback_list;
344
SafeList<CallbackItem *> mix_callback_list;
345
SafeList<CallbackItem *> listener_changed_callback_list;
346
347
friend class AudioDriver;
348
void _driver_process(int p_frames, int32_t *p_buffer);
349
350
LocalVector<Ref<AudioSamplePlayback>> sample_playback_list;
351
352
protected:
353
static void _bind_methods();
354
355
public:
356
_FORCE_INLINE_ int get_channel_count() const {
357
switch (get_speaker_mode()) {
358
case SPEAKER_MODE_STEREO:
359
return 1;
360
case SPEAKER_SURROUND_31:
361
return 2;
362
case SPEAKER_SURROUND_51:
363
return 3;
364
case SPEAKER_SURROUND_71:
365
return 4;
366
}
367
ERR_FAIL_V(1);
368
}
369
370
// Do not use from outside audio thread.
371
bool thread_has_channel_mix_buffer(int p_bus, int p_buffer) const;
372
AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer);
373
int thread_get_mix_buffer_size() const;
374
int thread_find_bus_index(const StringName &p_name);
375
376
#ifdef DEBUG_ENABLED
377
void set_debug_mute(bool p_mute);
378
bool get_debug_mute() const;
379
#endif // DEBUG_ENABLED
380
381
void set_bus_count(int p_count);
382
int get_bus_count() const;
383
384
void remove_bus(int p_index);
385
void add_bus(int p_at_pos = -1);
386
387
void move_bus(int p_bus, int p_to_pos);
388
389
void set_bus_name(int p_bus, const String &p_name);
390
String get_bus_name(int p_bus) const;
391
int get_bus_index(const StringName &p_bus_name) const;
392
393
int get_bus_channels(int p_bus) const;
394
395
void set_bus_volume_db(int p_bus, float p_volume_db);
396
float get_bus_volume_db(int p_bus) const;
397
398
void set_bus_volume_linear(int p_bus, float p_volume_linear);
399
float get_bus_volume_linear(int p_bus) const;
400
401
void set_bus_send(int p_bus, const StringName &p_send);
402
StringName get_bus_send(int p_bus) const;
403
404
void set_bus_solo(int p_bus, bool p_enable);
405
bool is_bus_solo(int p_bus) const;
406
407
void set_bus_mute(int p_bus, bool p_enable);
408
bool is_bus_mute(int p_bus) const;
409
410
void set_bus_bypass_effects(int p_bus, bool p_enable);
411
bool is_bus_bypassing_effects(int p_bus) const;
412
413
void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1);
414
void remove_bus_effect(int p_bus, int p_effect);
415
416
int get_bus_effect_count(int p_bus);
417
Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
418
Ref<AudioEffectInstance> get_bus_effect_instance(int p_bus, int p_effect, int p_channel = 0);
419
420
void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);
421
422
void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled);
423
bool is_bus_effect_enabled(int p_bus, int p_effect) const;
424
425
float get_bus_peak_volume_left_db(int p_bus, int p_channel) const;
426
float get_bus_peak_volume_right_db(int p_bus, int p_channel) const;
427
428
bool is_bus_channel_active(int p_bus, int p_channel) const;
429
430
void set_playback_speed_scale(float p_scale);
431
float get_playback_speed_scale() const;
432
433
// Convenience method.
434
void start_playback_stream(Ref<AudioStreamPlayback> p_playback, const StringName &p_bus, Vector<AudioFrame> p_volume_db_vector, float p_start_time = 0, float p_pitch_scale = 1);
435
// Expose all parameters.
436
void start_playback_stream(Ref<AudioStreamPlayback> p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes, float p_start_time = 0, float p_pitch_scale = 1, float p_highshelf_gain = 0, float p_attenuation_cutoff_hz = 0);
437
void stop_playback_stream(Ref<AudioStreamPlayback> p_playback);
438
439
void set_playback_bus_exclusive(Ref<AudioStreamPlayback> p_playback, const StringName &p_bus, Vector<AudioFrame> p_volumes);
440
void set_playback_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes);
441
void set_playback_all_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, Vector<AudioFrame> p_volumes);
442
void set_playback_pitch_scale(Ref<AudioStreamPlayback> p_playback, float p_pitch_scale);
443
void set_playback_paused(Ref<AudioStreamPlayback> p_playback, bool p_paused);
444
void set_playback_highshelf_params(Ref<AudioStreamPlayback> p_playback, float p_gain, float p_attenuation_cutoff_hz);
445
446
bool is_playback_active(Ref<AudioStreamPlayback> p_playback);
447
float get_playback_position(Ref<AudioStreamPlayback> p_playback);
448
bool is_playback_paused(Ref<AudioStreamPlayback> p_playback);
449
450
uint64_t get_mix_count() const;
451
uint64_t get_mixed_frames() const;
452
453
String get_driver_name() const;
454
455
void notify_listener_changed();
456
457
virtual void init();
458
virtual void finish();
459
virtual void update();
460
virtual void load_default_bus_layout();
461
462
/* MISC config */
463
464
virtual void lock();
465
virtual void unlock();
466
467
virtual SpeakerMode get_speaker_mode() const;
468
virtual float get_mix_rate() const;
469
virtual float get_input_mix_rate() const;
470
471
virtual float read_output_peak_db() const;
472
473
static AudioServer *get_singleton();
474
475
virtual double get_output_latency() const;
476
virtual double get_time_to_next_mix() const;
477
virtual double get_time_since_last_mix() const;
478
479
void add_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
480
void remove_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
481
482
void add_update_callback(AudioCallback p_callback, void *p_userdata);
483
void remove_update_callback(AudioCallback p_callback, void *p_userdata);
484
485
void add_mix_callback(AudioCallback p_callback, void *p_userdata);
486
void remove_mix_callback(AudioCallback p_callback, void *p_userdata);
487
488
void set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout);
489
Ref<AudioBusLayout> generate_bus_layout() const;
490
491
PackedStringArray get_output_device_list();
492
String get_output_device();
493
void set_output_device(const String &p_name);
494
495
PackedStringArray get_input_device_list();
496
String get_input_device();
497
void set_input_device(const String &p_name);
498
Error set_input_device_active(bool p_is_active);
499
int get_input_frames_available();
500
int get_input_buffer_length_frames();
501
PackedVector2Array get_input_frames(int p_frames);
502
503
void set_enable_tagging_used_audio_streams(bool p_enable);
504
505
#ifdef TOOLS_ENABLED
506
virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const override;
507
#endif
508
509
PlaybackType get_default_playback_type() const;
510
511
bool is_stream_registered_as_sample(const Ref<AudioStream> &p_stream);
512
void register_stream_as_sample(const Ref<AudioStream> &p_stream);
513
void unregister_stream_as_sample(const Ref<AudioStream> &p_stream);
514
void register_sample(const Ref<AudioSample> &p_sample);
515
void unregister_sample(const Ref<AudioSample> &p_sample);
516
void start_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
517
void stop_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
518
void set_sample_playback_pause(const Ref<AudioSamplePlayback> &p_playback, bool p_paused);
519
bool is_sample_playback_active(const Ref<AudioSamplePlayback> &p_playback);
520
double get_sample_playback_position(const Ref<AudioSamplePlayback> &p_playback);
521
void update_sample_playback_pitch_scale(const Ref<AudioSamplePlayback> &p_playback, float p_pitch_scale = 0.0f);
522
523
AudioServer();
524
virtual ~AudioServer();
525
};
526
527
VARIANT_ENUM_CAST(AudioServer::SpeakerMode)
528
VARIANT_ENUM_CAST(AudioServer::PlaybackType)
529
530
class AudioBusLayout : public Resource {
531
GDCLASS(AudioBusLayout, Resource);
532
533
friend class AudioServer;
534
535
struct Bus {
536
StringName name;
537
bool solo = false;
538
bool mute = false;
539
bool bypass = false;
540
541
struct Effect {
542
Ref<AudioEffect> effect;
543
bool enabled = false;
544
};
545
546
Vector<Effect> effects;
547
548
float volume_db = 0.0f;
549
StringName send;
550
551
Bus() {}
552
};
553
554
Vector<Bus> buses;
555
556
protected:
557
bool _set(const StringName &p_name, const Variant &p_value);
558
bool _get(const StringName &p_name, Variant &r_ret) const;
559
void _get_property_list(List<PropertyInfo> *p_list) const;
560
561
public:
562
AudioBusLayout();
563
};
564
565
typedef AudioServer AS;
566
567