audio_server.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. #ifndef AUDIO_SERVER_H
  31. #define AUDIO_SERVER_H
  32. #include "core/math/audio_frame.h"
  33. #include "core/object/class_db.h"
  34. #include "core/os/os.h"
  35. #include "core/templates/safe_list.h"
  36. #include "core/variant/variant.h"
  37. #include "servers/audio/audio_effect.h"
  38. #include "servers/audio/audio_filter_sw.h"
  39. #include <atomic>
  40. class AudioDriverDummy;
  41. class AudioStream;
  42. class AudioStreamWAV;
  43. class AudioStreamPlayback;
  44. class AudioDriver {
  45. static AudioDriver *singleton;
  46. uint64_t _last_mix_time = 0;
  47. uint64_t _last_mix_frames = 0;
  48. #ifdef DEBUG_ENABLED
  49. uint64_t prof_ticks = 0;
  50. uint64_t prof_time = 0;
  51. #endif
  52. protected:
  53. Vector<int32_t> input_buffer;
  54. unsigned int input_position = 0;
  55. unsigned int input_size = 0;
  56. void audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time = true);
  57. void update_mix_time(int p_frames);
  58. void input_buffer_init(int driver_buffer_frames);
  59. void input_buffer_write(int32_t sample);
  60. int _get_configured_mix_rate();
  61. #ifdef DEBUG_ENABLED
  62. _FORCE_INLINE_ void start_counting_ticks() { prof_ticks = OS::get_singleton()->get_ticks_usec(); }
  63. _FORCE_INLINE_ void stop_counting_ticks() { prof_time += OS::get_singleton()->get_ticks_usec() - prof_ticks; }
  64. #else
  65. _FORCE_INLINE_ void start_counting_ticks() {}
  66. _FORCE_INLINE_ void stop_counting_ticks() {}
  67. #endif
  68. public:
  69. double get_time_since_last_mix(); //useful for video -> audio sync
  70. double get_time_to_next_mix();
  71. enum SpeakerMode {
  72. SPEAKER_MODE_STEREO,
  73. SPEAKER_SURROUND_31,
  74. SPEAKER_SURROUND_51,
  75. SPEAKER_SURROUND_71,
  76. };
  77. static AudioDriver *get_singleton();
  78. void set_singleton();
  79. // Virtual API to implement.
  80. virtual const char *get_name() const = 0;
  81. virtual Error init() = 0;
  82. virtual void start() = 0;
  83. virtual int get_mix_rate() const = 0;
  84. virtual SpeakerMode get_speaker_mode() const = 0;
  85. virtual float get_latency() { return 0; }
  86. virtual void lock() = 0;
  87. virtual void unlock() = 0;
  88. virtual void finish() = 0;
  89. virtual PackedStringArray get_output_device_list();
  90. virtual String get_output_device();
  91. virtual void set_output_device(const String &p_name) {}
  92. virtual Error input_start() { return FAILED; }
  93. virtual Error input_stop() { return FAILED; }
  94. virtual PackedStringArray get_input_device_list();
  95. virtual String get_input_device() { return "Default"; }
  96. virtual void set_input_device(const String &p_name) {}
  97. //
  98. SpeakerMode get_speaker_mode_by_total_channels(int p_channels) const;
  99. int get_total_channels_by_speaker_mode(SpeakerMode) const;
  100. Vector<int32_t> get_input_buffer() { return input_buffer; }
  101. unsigned int get_input_position() { return input_position; }
  102. unsigned int get_input_size() { return input_size; }
  103. #ifdef DEBUG_ENABLED
  104. uint64_t get_profiling_time() const { return prof_time; }
  105. void reset_profiling_time() { prof_time = 0; }
  106. #endif
  107. AudioDriver() {}
  108. virtual ~AudioDriver() {}
  109. };
  110. class AudioDriverManager {
  111. enum {
  112. MAX_DRIVERS = 10
  113. };
  114. static AudioDriver *drivers[MAX_DRIVERS];
  115. static int driver_count;
  116. static AudioDriverDummy dummy_driver;
  117. public:
  118. static const int DEFAULT_MIX_RATE = 44100;
  119. static void add_driver(AudioDriver *p_driver);
  120. static void initialize(int p_driver);
  121. static int get_driver_count();
  122. static AudioDriver *get_driver(int p_driver);
  123. };
  124. class AudioBusLayout;
  125. class AudioServer : public Object {
  126. GDCLASS(AudioServer, Object);
  127. public:
  128. //re-expose this here, as AudioDriver is not exposed to script
  129. enum SpeakerMode {
  130. SPEAKER_MODE_STEREO,
  131. SPEAKER_SURROUND_31,
  132. SPEAKER_SURROUND_51,
  133. SPEAKER_SURROUND_71,
  134. };
  135. enum {
  136. AUDIO_DATA_INVALID_ID = -1,
  137. MAX_CHANNELS_PER_BUS = 4,
  138. MAX_BUSES_PER_PLAYBACK = 6,
  139. LOOKAHEAD_BUFFER_SIZE = 64,
  140. };
  141. typedef void (*AudioCallback)(void *p_userdata);
  142. private:
  143. uint64_t mix_time = 0;
  144. int mix_size = 0;
  145. uint32_t buffer_size = 0;
  146. uint64_t mix_count = 0;
  147. uint64_t mix_frames = 0;
  148. #ifdef DEBUG_ENABLED
  149. uint64_t prof_time = 0;
  150. #endif
  151. float channel_disable_threshold_db = 0.0f;
  152. uint32_t channel_disable_frames = 0;
  153. int channel_count = 0;
  154. int to_mix = 0;
  155. float playback_speed_scale = 1.0f;
  156. bool tag_used_audio_streams = false;
  157. struct Bus {
  158. StringName name;
  159. bool solo = false;
  160. bool mute = false;
  161. bool bypass = false;
  162. bool soloed = false;
  163. // Each channel is a stereo pair.
  164. struct Channel {
  165. bool used = false;
  166. bool active = false;
  167. AudioFrame peak_volume = AudioFrame(AUDIO_MIN_PEAK_DB, AUDIO_MIN_PEAK_DB);
  168. Vector<AudioFrame> buffer;
  169. Vector<Ref<AudioEffectInstance>> effect_instances;
  170. uint64_t last_mix_with_audio = 0;
  171. Channel() {}
  172. };
  173. Vector<Channel> channels;
  174. struct Effect {
  175. Ref<AudioEffect> effect;
  176. bool enabled = false;
  177. #ifdef DEBUG_ENABLED
  178. uint64_t prof_time = 0;
  179. #endif
  180. };
  181. Vector<Effect> effects;
  182. float volume_db = 0.0f;
  183. StringName send;
  184. int index_cache = 0;
  185. };
  186. struct AudioStreamPlaybackBusDetails {
  187. bool bus_active[MAX_BUSES_PER_PLAYBACK] = {};
  188. StringName bus[MAX_BUSES_PER_PLAYBACK];
  189. AudioFrame volume[MAX_BUSES_PER_PLAYBACK][MAX_CHANNELS_PER_BUS];
  190. };
  191. struct AudioStreamPlaybackListNode {
  192. enum PlaybackState {
  193. PAUSED = 0, // Paused. Keep this stream playback around though so it can be restarted.
  194. PLAYING = 1, // Playing. Fading may still be necessary if volume changes!
  195. FADE_OUT_TO_PAUSE = 2, // About to pause.
  196. FADE_OUT_TO_DELETION = 3, // About to stop.
  197. AWAITING_DELETION = 4,
  198. };
  199. // If zero or positive, a place in the stream to seek to during the next mix.
  200. SafeNumeric<float> setseek;
  201. SafeNumeric<float> pitch_scale;
  202. SafeNumeric<float> highshelf_gain;
  203. SafeNumeric<float> attenuation_filter_cutoff_hz; // This isn't used unless highshelf_gain is nonzero.
  204. AudioFilterSW::Processor filter_process[8];
  205. // Updating this ref after the list node is created breaks consistency guarantees, don't do it!
  206. Ref<AudioStreamPlayback> stream_playback;
  207. // Playback state determines the fate of a particular AudioStreamListNode during the mix step. Must be atomically replaced.
  208. std::atomic<PlaybackState> state = AWAITING_DELETION;
  209. // This data should only ever be modified by an atomic replacement of the pointer.
  210. std::atomic<AudioStreamPlaybackBusDetails *> bus_details = nullptr;
  211. // Previous bus details should only be accessed on the audio thread.
  212. AudioStreamPlaybackBusDetails *prev_bus_details = nullptr;
  213. // 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.
  214. AudioFrame lookahead[LOOKAHEAD_BUFFER_SIZE];
  215. };
  216. SafeList<AudioStreamPlaybackListNode *> playback_list;
  217. SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard;
  218. // TODO document if this is necessary.
  219. SafeList<AudioStreamPlaybackBusDetails *> bus_details_graveyard_frame_old;
  220. Vector<Vector<AudioFrame>> temp_buffer; //temp_buffer for each level
  221. Vector<AudioFrame> mix_buffer;
  222. Vector<Bus *> buses;
  223. HashMap<StringName, Bus *> bus_map;
  224. void _update_bus_effects(int p_bus);
  225. static AudioServer *singleton;
  226. void init_channels_and_buffers();
  227. void _mix_step();
  228. 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);
  229. // Should only be called on the main thread.
  230. AudioStreamPlaybackListNode *_find_playback_list_node(Ref<AudioStreamPlayback> p_playback);
  231. struct CallbackItem {
  232. AudioCallback callback;
  233. void *userdata = nullptr;
  234. };
  235. SafeList<CallbackItem *> update_callback_list;
  236. SafeList<CallbackItem *> mix_callback_list;
  237. SafeList<CallbackItem *> listener_changed_callback_list;
  238. friend class AudioDriver;
  239. void _driver_process(int p_frames, int32_t *p_buffer);
  240. protected:
  241. static void _bind_methods();
  242. public:
  243. _FORCE_INLINE_ int get_channel_count() const {
  244. switch (get_speaker_mode()) {
  245. case SPEAKER_MODE_STEREO:
  246. return 1;
  247. case SPEAKER_SURROUND_31:
  248. return 2;
  249. case SPEAKER_SURROUND_51:
  250. return 3;
  251. case SPEAKER_SURROUND_71:
  252. return 4;
  253. }
  254. ERR_FAIL_V(1);
  255. }
  256. // Do not use from outside audio thread.
  257. bool thread_has_channel_mix_buffer(int p_bus, int p_buffer) const;
  258. AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer);
  259. int thread_get_mix_buffer_size() const;
  260. int thread_find_bus_index(const StringName &p_name);
  261. void set_bus_count(int p_count);
  262. int get_bus_count() const;
  263. void remove_bus(int p_index);
  264. void add_bus(int p_at_pos = -1);
  265. void move_bus(int p_bus, int p_to_pos);
  266. void set_bus_name(int p_bus, const String &p_name);
  267. String get_bus_name(int p_bus) const;
  268. int get_bus_index(const StringName &p_bus_name) const;
  269. int get_bus_channels(int p_bus) const;
  270. void set_bus_volume_db(int p_bus, float p_volume_db);
  271. float get_bus_volume_db(int p_bus) const;
  272. void set_bus_send(int p_bus, const StringName &p_send);
  273. StringName get_bus_send(int p_bus) const;
  274. void set_bus_solo(int p_bus, bool p_enable);
  275. bool is_bus_solo(int p_bus) const;
  276. void set_bus_mute(int p_bus, bool p_enable);
  277. bool is_bus_mute(int p_bus) const;
  278. void set_bus_bypass_effects(int p_bus, bool p_enable);
  279. bool is_bus_bypassing_effects(int p_bus) const;
  280. void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1);
  281. void remove_bus_effect(int p_bus, int p_effect);
  282. int get_bus_effect_count(int p_bus);
  283. Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
  284. Ref<AudioEffectInstance> get_bus_effect_instance(int p_bus, int p_effect, int p_channel = 0);
  285. void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);
  286. void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled);
  287. bool is_bus_effect_enabled(int p_bus, int p_effect) const;
  288. float get_bus_peak_volume_left_db(int p_bus, int p_channel) const;
  289. float get_bus_peak_volume_right_db(int p_bus, int p_channel) const;
  290. bool is_bus_channel_active(int p_bus, int p_channel) const;
  291. void set_playback_speed_scale(float p_scale);
  292. float get_playback_speed_scale() const;
  293. // Convenience method.
  294. void start_playback_stream(Ref<AudioStreamPlayback> p_playback, StringName p_bus, Vector<AudioFrame> p_volume_db_vector, float p_start_time = 0, float p_pitch_scale = 1);
  295. // Expose all parameters.
  296. void start_playback_stream(Ref<AudioStreamPlayback> p_playback, 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);
  297. void stop_playback_stream(Ref<AudioStreamPlayback> p_playback);
  298. void set_playback_bus_exclusive(Ref<AudioStreamPlayback> p_playback, StringName p_bus, Vector<AudioFrame> p_volumes);
  299. void set_playback_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, HashMap<StringName, Vector<AudioFrame>> p_bus_volumes);
  300. void set_playback_all_bus_volumes_linear(Ref<AudioStreamPlayback> p_playback, Vector<AudioFrame> p_volumes);
  301. void set_playback_pitch_scale(Ref<AudioStreamPlayback> p_playback, float p_pitch_scale);
  302. void set_playback_paused(Ref<AudioStreamPlayback> p_playback, bool p_paused);
  303. void set_playback_highshelf_params(Ref<AudioStreamPlayback> p_playback, float p_gain, float p_attenuation_cutoff_hz);
  304. bool is_playback_active(Ref<AudioStreamPlayback> p_playback);
  305. float get_playback_position(Ref<AudioStreamPlayback> p_playback);
  306. bool is_playback_paused(Ref<AudioStreamPlayback> p_playback);
  307. uint64_t get_mix_count() const;
  308. uint64_t get_mixed_frames() const;
  309. void notify_listener_changed();
  310. virtual void init();
  311. virtual void finish();
  312. virtual void update();
  313. virtual void load_default_bus_layout();
  314. /* MISC config */
  315. virtual void lock();
  316. virtual void unlock();
  317. virtual SpeakerMode get_speaker_mode() const;
  318. virtual float get_mix_rate() const;
  319. virtual float read_output_peak_db() const;
  320. static AudioServer *get_singleton();
  321. virtual double get_output_latency() const;
  322. virtual double get_time_to_next_mix() const;
  323. virtual double get_time_since_last_mix() const;
  324. void add_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
  325. void remove_listener_changed_callback(AudioCallback p_callback, void *p_userdata);
  326. void add_update_callback(AudioCallback p_callback, void *p_userdata);
  327. void remove_update_callback(AudioCallback p_callback, void *p_userdata);
  328. void add_mix_callback(AudioCallback p_callback, void *p_userdata);
  329. void remove_mix_callback(AudioCallback p_callback, void *p_userdata);
  330. void set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout);
  331. Ref<AudioBusLayout> generate_bus_layout() const;
  332. PackedStringArray get_output_device_list();
  333. String get_output_device();
  334. void set_output_device(const String &p_name);
  335. PackedStringArray get_input_device_list();
  336. String get_input_device();
  337. void set_input_device(const String &p_name);
  338. void set_enable_tagging_used_audio_streams(bool p_enable);
  339. AudioServer();
  340. virtual ~AudioServer();
  341. };
  342. VARIANT_ENUM_CAST(AudioServer::SpeakerMode)
  343. class AudioBusLayout : public Resource {
  344. GDCLASS(AudioBusLayout, Resource);
  345. friend class AudioServer;
  346. struct Bus {
  347. StringName name;
  348. bool solo = false;
  349. bool mute = false;
  350. bool bypass = false;
  351. struct Effect {
  352. Ref<AudioEffect> effect;
  353. bool enabled = false;
  354. };
  355. Vector<Effect> effects;
  356. float volume_db = 0.0f;
  357. StringName send;
  358. Bus() {}
  359. };
  360. Vector<Bus> buses;
  361. protected:
  362. bool _set(const StringName &p_name, const Variant &p_value);
  363. bool _get(const StringName &p_name, Variant &r_ret) const;
  364. void _get_property_list(List<PropertyInfo> *p_list) const;
  365. public:
  366. AudioBusLayout();
  367. };
  368. typedef AudioServer AS;
  369. #endif // AUDIO_SERVER_H