2
0

audio_server.h 15 KB

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