Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/servers/audio_server.h
9887 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
struct Bus {
236
StringName name;
237
bool solo = false;
238
bool mute = false;
239
bool bypass = false;
240
241
bool soloed = false;
242
243
// Each channel is a stereo pair.
244
struct Channel {
245
bool used = false;
246
bool active = false;
247
AudioFrame peak_volume = AudioFrame(AUDIO_MIN_PEAK_DB, AUDIO_MIN_PEAK_DB);
248
Vector<AudioFrame> buffer;
249
Vector<Ref<AudioEffectInstance>> effect_instances;
250
uint64_t last_mix_with_audio = 0;
251
Channel() {}
252
};
253
254
Vector<Channel> channels;
255
256
struct Effect {
257
Ref<AudioEffect> effect;
258
bool enabled = false;
259
#ifdef DEBUG_ENABLED
260
uint64_t prof_time = 0;
261
#endif
262
};
263
264
Vector<Effect> effects;
265
float volume_db = 0.0f;
266
StringName send;
267
int index_cache = 0;
268
};
269
270
struct AudioStreamPlaybackBusDetails {
271
bool bus_active[MAX_BUSES_PER_PLAYBACK] = {};
272
StringName bus[MAX_BUSES_PER_PLAYBACK];
273
AudioFrame volume[MAX_BUSES_PER_PLAYBACK][MAX_CHANNELS_PER_BUS];
274
};
275
276
struct AudioStreamPlaybackListNode {
277
// The state machine for audio stream playbacks is as follows:
278
// 1. The playback is created and added to the playback list in the playing state.
279
// 2. The playback is (maybe) paused, and the state is set to FADE_OUT_TO_PAUSE.
280
// 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.
281
// 3. The playback is (maybe) deleted, and the state is set to FADE_OUT_TO_DELETION.
282
// 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.
283
// NOTE: The playback is not deallocated at this time because allocation and deallocation are not realtime-safe.
284
// 4. The playback is removed and deallocated on the main thread using the SafeList maybe_cleanup method.
285
enum PlaybackState {
286
PAUSED = 0, // Paused. Keep this stream playback around though so it can be restarted.
287
PLAYING = 1, // Playing. Fading may still be necessary if volume changes!
288
FADE_OUT_TO_PAUSE = 2, // About to pause.
289
FADE_OUT_TO_DELETION = 3, // About to stop.
290
AWAITING_DELETION = 4,
291
};
292
// If zero or positive, a place in the stream to seek to during the next mix.
293
SafeNumeric<float> setseek;
294
SafeNumeric<float> pitch_scale;
295
SafeNumeric<float> highshelf_gain;
296
SafeNumeric<float> attenuation_filter_cutoff_hz; // This isn't used unless highshelf_gain is nonzero.
297
AudioFilterSW::Processor filter_process[8];
298
// Updating this ref after the list node is created breaks consistency guarantees, don't do it!
299
Ref<AudioStreamPlayback> stream_playback;
300
// Playback state determines the fate of a particular AudioStreamListNode during the mix step. Must be atomically replaced.
301
std::atomic<PlaybackState> state = AWAITING_DELETION;
302
// This data should only ever be modified by an atomic replacement of the pointer.
303
std::atomic<AudioStreamPlaybackBusDetails *> bus_details = nullptr;
304
// Previous bus details should only be accessed on the audio thread.
305
AudioStreamPlaybackBusDetails *prev_bus_details = nullptr;
306
// 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.
307
AudioFrame lookahead[LOOKAHEAD_BUFFER_SIZE];
308
};
309
310
SafeList<AudioStreamPlaybackListNode *> playback_list;
311
SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard;
312
void _delete_stream_playback(Ref<AudioStreamPlayback> p_playback);
313
void _delete_stream_playback_list_node(AudioStreamPlaybackListNode *p_node);
314
315
// TODO document if this is necessary.
316
SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard_frame_old;
317
318
Vector<Vector<AudioFrame>> temp_buffer; //temp_buffer for each level
319
Vector<AudioFrame> mix_buffer;
320
Vector<Bus *> buses;
321
HashMap<StringName, Bus *> bus_map;
322
323
void _update_bus_effects(int p_bus);
324
325
static AudioServer *singleton;
326
327
void init_channels_and_buffers();
328
329
void _mix_step();
330
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);
331
332
// Should only be called on the main thread.
333
AudioStreamPlaybackListNode *_find_playback_list_node(Ref<AudioStreamPlayback> p_playback);
334
335
struct CallbackItem {
336
AudioCallback callback;
337
void *userdata = nullptr;
338
};
339
340
SafeList<CallbackItem *> update_callback_list;
341
SafeList<CallbackItem *> mix_callback_list;
342
SafeList<CallbackItem *> listener_changed_callback_list;
343
344
friend class AudioDriver;
345
void _driver_process(int p_frames, int32_t *p_buffer);
346
347
LocalVector<Ref<AudioSamplePlayback>> sample_playback_list;
348
349
protected:
350
static void _bind_methods();
351
352
public:
353
_FORCE_INLINE_ int get_channel_count() const {
354
switch (get_speaker_mode()) {
355
case SPEAKER_MODE_STEREO:
356
return 1;
357
case SPEAKER_SURROUND_31:
358
return 2;
359
case SPEAKER_SURROUND_51:
360
return 3;
361
case SPEAKER_SURROUND_71:
362
return 4;
363
}
364
ERR_FAIL_V(1);
365
}
366
367
// Do not use from outside audio thread.
368
bool thread_has_channel_mix_buffer(int p_bus, int p_buffer) const;
369
AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer);
370
int thread_get_mix_buffer_size() const;
371
int thread_find_bus_index(const StringName &p_name);
372
373
#ifdef DEBUG_ENABLED
374
void set_debug_mute(bool p_mute);
375
bool get_debug_mute() const;
376
#endif // DEBUG_ENABLED
377
378
void set_bus_count(int p_count);
379
int get_bus_count() const;
380
381
void remove_bus(int p_index);
382
void add_bus(int p_at_pos = -1);
383
384
void move_bus(int p_bus, int p_to_pos);
385
386
void set_bus_name(int p_bus, const String &p_name);
387
String get_bus_name(int p_bus) const;
388
int get_bus_index(const StringName &p_bus_name) const;
389
390
int get_bus_channels(int p_bus) const;
391
392
void set_bus_volume_db(int p_bus, float p_volume_db);
393
float get_bus_volume_db(int p_bus) const;
394
395
void set_bus_volume_linear(int p_bus, float p_volume_linear);
396
float get_bus_volume_linear(int p_bus) const;
397
398
void set_bus_send(int p_bus, const StringName &p_send);
399
StringName get_bus_send(int p_bus) const;
400
401
void set_bus_solo(int p_bus, bool p_enable);
402
bool is_bus_solo(int p_bus) const;
403
404
void set_bus_mute(int p_bus, bool p_enable);
405
bool is_bus_mute(int p_bus) const;
406
407
void set_bus_bypass_effects(int p_bus, bool p_enable);
408
bool is_bus_bypassing_effects(int p_bus) const;
409
410
void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1);
411
void remove_bus_effect(int p_bus, int p_effect);
412
413
int get_bus_effect_count(int p_bus);
414
Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
415
Ref<AudioEffectInstance> get_bus_effect_instance(int p_bus, int p_effect, int p_channel = 0);
416
417
void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);
418
419
void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled);
420
bool is_bus_effect_enabled(int p_bus, int p_effect) const;
421
422
float get_bus_peak_volume_left_db(int p_bus, int p_channel) const;
423
float get_bus_peak_volume_right_db(int p_bus, int p_channel) const;
424
425
bool is_bus_channel_active(int p_bus, int p_channel) const;
426
427
void set_playback_speed_scale(float p_scale);
428
float get_playback_speed_scale() const;
429
430
// Convenience method.
431
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);
432
// Expose all parameters.
433
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);
434
void stop_playback_stream(Ref<AudioStreamPlayback> p_playback);
435
436
void set_playback_bus_exclusive(Ref<AudioStreamPlayback> p_playback, const StringName &p_bus, Vector<AudioFrame> p_volumes);
437
void set_playback_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes);
438
void set_playback_all_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, Vector<AudioFrame> p_volumes);
439
void set_playback_pitch_scale(Ref<AudioStreamPlayback> p_playback, float p_pitch_scale);
440
void set_playback_paused(Ref<AudioStreamPlayback> p_playback, bool p_paused);
441
void set_playback_highshelf_params(Ref<AudioStreamPlayback> p_playback, float p_gain, float p_attenuation_cutoff_hz);
442
443
bool is_playback_active(Ref<AudioStreamPlayback> p_playback);
444
float get_playback_position(Ref<AudioStreamPlayback> p_playback);
445
bool is_playback_paused(Ref<AudioStreamPlayback> p_playback);
446
447
uint64_t get_mix_count() const;
448
uint64_t get_mixed_frames() const;
449
450
String get_driver_name() const;
451
452
void notify_listener_changed();
453
454
virtual void init();
455
virtual void finish();
456
virtual void update();
457
virtual void load_default_bus_layout();
458
459
/* MISC config */
460
461
virtual void lock();
462
virtual void unlock();
463
464
virtual SpeakerMode get_speaker_mode() const;
465
virtual float get_mix_rate() const;
466
virtual float get_input_mix_rate() const;
467
468
virtual float read_output_peak_db() const;
469
470
static AudioServer *get_singleton();
471
472
virtual double get_output_latency() const;
473
virtual double get_time_to_next_mix() const;
474
virtual double get_time_since_last_mix() const;
475
476
void add_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
477
void remove_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
478
479
void add_update_callback(AudioCallback p_callback, void *p_userdata);
480
void remove_update_callback(AudioCallback p_callback, void *p_userdata);
481
482
void add_mix_callback(AudioCallback p_callback, void *p_userdata);
483
void remove_mix_callback(AudioCallback p_callback, void *p_userdata);
484
485
void set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout);
486
Ref<AudioBusLayout> generate_bus_layout() const;
487
488
PackedStringArray get_output_device_list();
489
String get_output_device();
490
void set_output_device(const String &p_name);
491
492
PackedStringArray get_input_device_list();
493
String get_input_device();
494
void set_input_device(const String &p_name);
495
496
void set_enable_tagging_used_audio_streams(bool p_enable);
497
498
#ifdef TOOLS_ENABLED
499
virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const override;
500
#endif
501
502
PlaybackType get_default_playback_type() const;
503
504
bool is_stream_registered_as_sample(const Ref<AudioStream> &p_stream);
505
void register_stream_as_sample(const Ref<AudioStream> &p_stream);
506
void unregister_stream_as_sample(const Ref<AudioStream> &p_stream);
507
void register_sample(const Ref<AudioSample> &p_sample);
508
void unregister_sample(const Ref<AudioSample> &p_sample);
509
void start_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
510
void stop_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
511
void set_sample_playback_pause(const Ref<AudioSamplePlayback> &p_playback, bool p_paused);
512
bool is_sample_playback_active(const Ref<AudioSamplePlayback> &p_playback);
513
double get_sample_playback_position(const Ref<AudioSamplePlayback> &p_playback);
514
void update_sample_playback_pitch_scale(const Ref<AudioSamplePlayback> &p_playback, float p_pitch_scale = 0.0f);
515
516
AudioServer();
517
virtual ~AudioServer();
518
};
519
520
VARIANT_ENUM_CAST(AudioServer::SpeakerMode)
521
VARIANT_ENUM_CAST(AudioServer::PlaybackType)
522
523
class AudioBusLayout : public Resource {
524
GDCLASS(AudioBusLayout, Resource);
525
526
friend class AudioServer;
527
528
struct Bus {
529
StringName name;
530
bool solo = false;
531
bool mute = false;
532
bool bypass = false;
533
534
struct Effect {
535
Ref<AudioEffect> effect;
536
bool enabled = false;
537
};
538
539
Vector<Effect> effects;
540
541
float volume_db = 0.0f;
542
StringName send;
543
544
Bus() {}
545
};
546
547
Vector<Bus> buses;
548
549
protected:
550
bool _set(const StringName &p_name, const Variant &p_value);
551
bool _get(const StringName &p_name, Variant &r_ret) const;
552
void _get_property_list(List<PropertyInfo> *p_list) const;
553
554
public:
555
AudioBusLayout();
556
};
557
558
typedef AudioServer AS;
559
560