audio_server.h 15 KB

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