Debian Codegraph @

servers/audio/audio_server.h

raw symbols SCIP
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 void _cleanup_lists();
319
320 // TODO document if this is necessary.
321 SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard_frame_old;
322
323 Vector<Vector<AudioFrame>> temp_buffer; //temp_buffer for each level
324 Vector<AudioFrame> mix_buffer;
325 Vector<Bus *> buses;
326 HashMap<StringName, Bus *> bus_map;
327
328 void _update_bus_effects(int p_bus);
329
330 static AudioServer *singleton;
331
332 void init_channels_and_buffers();
333
334 void _mix_step();
335 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);
336
337 // Should only be called on the main thread.
338 AudioStreamPlaybackListNode *_find_playback_list_node(Ref<AudioStreamPlayback> p_playback);
339
340 struct CallbackItem {
341 AudioCallback callback;
342 void *userdata = nullptr;
343 };
344
345 SafeList<CallbackItem *> update_callback_list;
346 SafeList<CallbackItem *> mix_callback_list;
347 SafeList<CallbackItem *> listener_changed_callback_list;
348
349 friend class AudioDriver;
350 void _driver_process(int p_frames, int32_t *p_buffer);
351
352 LocalVector<Ref<AudioSamplePlayback>> sample_playback_list;
353
354 protected:
355 static void _bind_methods();
356
357 public:
358 _FORCE_INLINE_ int get_channel_count() const {
359 switch (get_speaker_mode()) {
360 case SPEAKER_MODE_STEREO:
361 return 1;
362 case SPEAKER_SURROUND_31:
363 return 2;
364 case SPEAKER_SURROUND_51:
365 return 3;
366 case SPEAKER_SURROUND_71:
367 return 4;
368 }
369 ERR_FAIL_V(1);
370 }
371
372 // Do not use from outside audio thread.
373 bool thread_has_channel_mix_buffer(int p_bus, int p_buffer) const;
374 AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer);
375 int thread_get_mix_buffer_size() const;
376 int thread_find_bus_index(const StringName &p_name);
377
378 #ifdef DEBUG_ENABLED
379 void set_debug_mute(bool p_mute);
380 bool get_debug_mute() const;
381 #endif // DEBUG_ENABLED
382
383 void set_bus_count(int p_count);
384 int get_bus_count() const;
385
386 void remove_bus(int p_index);
387 void add_bus(int p_at_pos = -1);
388
389 void move_bus(int p_bus, int p_to_pos);
390
391 void set_bus_name(int p_bus, const String &p_name);
392 String get_bus_name(int p_bus) const;
393 int get_bus_index(const StringName &p_bus_name) const;
394
395 int get_bus_channels(int p_bus) const;
396
397 void set_bus_volume_db(int p_bus, float p_volume_db);
398 float get_bus_volume_db(int p_bus) const;
399
400 void set_bus_volume_linear(int p_bus, float p_volume_linear);
401 float get_bus_volume_linear(int p_bus) const;
402
403 void set_bus_send(int p_bus, const StringName &p_send);
404 StringName get_bus_send(int p_bus) const;
405
406 void set_bus_solo(int p_bus, bool p_enable);
407 bool is_bus_solo(int p_bus) const;
408
409 void set_bus_mute(int p_bus, bool p_enable);
410 bool is_bus_mute(int p_bus) const;
411
412 void set_bus_bypass_effects(int p_bus, bool p_enable);
413 bool is_bus_bypassing_effects(int p_bus) const;
414
415 void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1);
416 void remove_bus_effect(int p_bus, int p_effect);
417
418 int get_bus_effect_count(int p_bus);
419 Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
420 Ref<AudioEffectInstance> get_bus_effect_instance(int p_bus, int p_effect, int p_channel = 0);
421
422 void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);
423
424 void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled);
425 bool is_bus_effect_enabled(int p_bus, int p_effect) const;
426
427 float get_bus_peak_volume_left_db(int p_bus, int p_channel) const;
428 float get_bus_peak_volume_right_db(int p_bus, int p_channel) const;
429
430 bool is_bus_channel_active(int p_bus, int p_channel) const;
431
432 void set_playback_speed_scale(float p_scale);
433 float get_playback_speed_scale() const;
434
435 // Convenience method.
436 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);
437 // Expose all parameters.
438 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);
439 void stop_playback_stream(Ref<AudioStreamPlayback> p_playback);
440
441 void set_playback_bus_exclusive(Ref<AudioStreamPlayback> p_playback, const StringName &p_bus, Vector<AudioFrame> p_volumes);
442 void set_playback_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, const HashMap<StringName, Vector<AudioFrame>> &p_bus_volumes);
443 void set_playback_all_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, Vector<AudioFrame> p_volumes);
444 void set_playback_pitch_scale(Ref<AudioStreamPlayback> p_playback, float p_pitch_scale);
445 void set_playback_paused(Ref<AudioStreamPlayback> p_playback, bool p_paused);
446 void set_playback_highshelf_params(Ref<AudioStreamPlayback> p_playback, float p_gain, float p_attenuation_cutoff_hz);
447
448 bool is_playback_active(Ref<AudioStreamPlayback> p_playback);
449 float get_playback_position(Ref<AudioStreamPlayback> p_playback);
450 bool is_playback_paused(Ref<AudioStreamPlayback> p_playback);
451
452 uint64_t get_mix_count() const;
453 uint64_t get_mixed_frames() const;
454
455 String get_driver_name() const;
456
457 void notify_listener_changed();
458
459 virtual void init();
460 virtual void finish();
461 virtual void update();
462 virtual void load_default_bus_layout();
463
464 /* MISC config */
465
466 virtual void lock();
467 virtual void unlock();
468
469 virtual SpeakerMode get_speaker_mode() const;
470 virtual float get_mix_rate() const;
471 virtual float get_input_mix_rate() const;
472
473 virtual float read_output_peak_db() const;
474
475 static AudioServer *get_singleton();
476
477 virtual double get_output_latency() const;
478 virtual double get_time_to_next_mix() const;
479 virtual double get_time_since_last_mix() const;
480
481 void add_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
482 void remove_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
483
484 void add_update_callback(AudioCallback p_callback, void *p_userdata);
485 void remove_update_callback(AudioCallback p_callback, void *p_userdata);
486
487 void add_mix_callback(AudioCallback p_callback, void *p_userdata);
488 void remove_mix_callback(AudioCallback p_callback, void *p_userdata);
489
490 void set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout);
491 Ref<AudioBusLayout> generate_bus_layout() const;
492
493 PackedStringArray get_output_device_list();
494 String get_output_device();
495 void set_output_device(const String &p_name);
496
497 PackedStringArray get_input_device_list();
498 String get_input_device();
499 void set_input_device(const String &p_name);
500 Error set_input_device_active(bool p_is_active);
501 int get_input_frames_available();
502 int get_input_buffer_length_frames();
503 PackedVector2Array get_input_frames(int p_frames);
504
505 void set_enable_tagging_used_audio_streams(bool p_enable);
506
507 #ifdef TOOLS_ENABLED
508 virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const override;
509 #endif
510
511 PlaybackType get_default_playback_type() const;
512
513 bool is_stream_registered_as_sample(const Ref<AudioStream> &p_stream);
514 void register_stream_as_sample(const Ref<AudioStream> &p_stream);
515 void unregister_stream_as_sample(const Ref<AudioStream> &p_stream);
516 void register_sample(const Ref<AudioSample> &p_sample);
517 void unregister_sample(const Ref<AudioSample> &p_sample);
518 void start_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
519 void stop_sample_playback(const Ref<AudioSamplePlayback> &p_playback);
520 void set_sample_playback_pause(const Ref<AudioSamplePlayback> &p_playback, bool p_paused);
521 bool is_sample_playback_active(const Ref<AudioSamplePlayback> &p_playback);
522 double get_sample_playback_position(const Ref<AudioSamplePlayback> &p_playback);
523 void update_sample_playback_pitch_scale(const Ref<AudioSamplePlayback> &p_playback, float p_pitch_scale = 0.0f);
524
525 AudioServer();
526 virtual ~AudioServer();
527 };
528
529 VARIANT_ENUM_CAST(AudioServer::SpeakerMode)
530 VARIANT_ENUM_CAST(AudioServer::PlaybackType)
531
532 class AudioBusLayout : public Resource {
533 GDCLASS(AudioBusLayout, Resource);
534
535 friend class AudioServer;
536
537 struct Bus {
538 StringName name;
539 bool solo = false;
540 bool mute = false;
541 bool bypass = false;
542
543 struct Effect {
544 Ref<AudioEffect> effect;
545 bool enabled = false;
546 };
547
548 Vector<Effect> effects;
549
550 float volume_db = 0.0f;
551 StringName send;
552
553 Bus() {}
554 };
555
556 Vector<Bus> buses;
557
558 protected:
559 bool _set(const StringName &p_name, const Variant &p_value);
560 bool _get(const StringName &p_name, Variant &r_ret) const;
561 void _get_property_list(List<PropertyInfo> *p_list) const;
562
563 public:
564 AudioBusLayout();
565 };
566
567 typedef AudioServer AS;