audio_driver_pulseaudio.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /**************************************************************************/
  2. /* audio_driver_pulseaudio.cpp */
  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. #include "audio_driver_pulseaudio.h"
  31. #ifdef PULSEAUDIO_ENABLED
  32. #include "core/config/project_settings.h"
  33. #include "core/os/os.h"
  34. #include "core/version.h"
  35. #ifdef ALSAMIDI_ENABLED
  36. #ifdef SOWRAP_ENABLED
  37. #include "drivers/alsa/asound-so_wrap.h"
  38. #else
  39. #include <alsa/asoundlib.h>
  40. #endif
  41. #endif
  42. void AudioDriverPulseAudio::pa_state_cb(pa_context *c, void *userdata) {
  43. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  44. switch (pa_context_get_state(c)) {
  45. case PA_CONTEXT_TERMINATED:
  46. print_verbose("PulseAudio: context terminated");
  47. ad->pa_ready = -1;
  48. break;
  49. case PA_CONTEXT_FAILED:
  50. print_verbose("PulseAudio: context failed");
  51. ad->pa_ready = -1;
  52. break;
  53. case PA_CONTEXT_READY:
  54. print_verbose("PulseAudio: context ready");
  55. ad->pa_ready = 1;
  56. break;
  57. default:
  58. print_verbose("PulseAudio: context other");
  59. // TODO: Check if we want to handle some of the other
  60. // PA context states like PA_CONTEXT_UNCONNECTED.
  61. break;
  62. }
  63. }
  64. void AudioDriverPulseAudio::pa_sink_info_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) {
  65. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  66. // If eol is set to a positive number, you're at the end of the list
  67. if (eol > 0) {
  68. return;
  69. }
  70. // If eol is set to a negative number there's an error.
  71. if (eol < 0) {
  72. ERR_PRINT("PulseAudio: sink info error: " + String(pa_strerror(pa_context_errno(c))));
  73. ad->pa_status--;
  74. return;
  75. }
  76. ad->pa_map = l->channel_map;
  77. ad->pa_status++;
  78. }
  79. void AudioDriverPulseAudio::pa_source_info_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) {
  80. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  81. // If eol is set to a positive number, you're at the end of the list
  82. if (eol > 0) {
  83. return;
  84. }
  85. // If eol is set to a negative number there's an error.
  86. if (eol < 0) {
  87. ERR_PRINT("PulseAudio: sink info error: " + String(pa_strerror(pa_context_errno(c))));
  88. ad->pa_status--;
  89. return;
  90. }
  91. ad->pa_rec_map = l->channel_map;
  92. ad->pa_status++;
  93. }
  94. void AudioDriverPulseAudio::pa_server_info_cb(pa_context *c, const pa_server_info *i, void *userdata) {
  95. ERR_FAIL_COND_MSG(!i, "PulseAudio server info is null.");
  96. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  97. ad->default_input_device = i->default_source_name;
  98. ad->default_output_device = i->default_sink_name;
  99. ad->pa_status++;
  100. }
  101. Error AudioDriverPulseAudio::detect_channels(bool input) {
  102. pa_channel_map_init_stereo(input ? &pa_rec_map : &pa_map);
  103. String device = input ? input_device_name : output_device_name;
  104. if (device == "Default") {
  105. // Get the default output device name
  106. pa_status = 0;
  107. pa_operation *pa_op = pa_context_get_server_info(pa_ctx, &AudioDriverPulseAudio::pa_server_info_cb, (void *)this);
  108. if (pa_op) {
  109. while (pa_status == 0) {
  110. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  111. if (ret < 0) {
  112. ERR_PRINT("pa_mainloop_iterate error");
  113. }
  114. }
  115. pa_operation_unref(pa_op);
  116. } else {
  117. ERR_PRINT("pa_context_get_server_info error: " + String(pa_strerror(pa_context_errno(pa_ctx))));
  118. return FAILED;
  119. }
  120. }
  121. char dev[1024];
  122. if (device == "Default") {
  123. strcpy(dev, input ? default_input_device.utf8().get_data() : default_output_device.utf8().get_data());
  124. } else {
  125. strcpy(dev, device.utf8().get_data());
  126. }
  127. print_verbose("PulseAudio: Detecting channels for device: " + String(dev));
  128. // Now using the device name get the amount of channels
  129. pa_status = 0;
  130. pa_operation *pa_op;
  131. if (input) {
  132. pa_op = pa_context_get_source_info_by_name(pa_ctx, dev, &AudioDriverPulseAudio::pa_source_info_cb, (void *)this);
  133. } else {
  134. pa_op = pa_context_get_sink_info_by_name(pa_ctx, dev, &AudioDriverPulseAudio::pa_sink_info_cb, (void *)this);
  135. }
  136. if (pa_op) {
  137. while (pa_status == 0) {
  138. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  139. if (ret < 0) {
  140. ERR_PRINT("pa_mainloop_iterate error");
  141. }
  142. }
  143. pa_operation_unref(pa_op);
  144. if (pa_status == -1) {
  145. return FAILED;
  146. }
  147. } else {
  148. if (input) {
  149. ERR_PRINT("pa_context_get_source_info_by_name error");
  150. } else {
  151. ERR_PRINT("pa_context_get_sink_info_by_name error");
  152. }
  153. }
  154. return OK;
  155. }
  156. Error AudioDriverPulseAudio::init_output_device() {
  157. // If there is a specified output device, check that it is really present
  158. if (output_device_name != "Default") {
  159. PackedStringArray list = get_output_device_list();
  160. if (list.find(output_device_name) == -1) {
  161. output_device_name = "Default";
  162. new_output_device = "Default";
  163. }
  164. }
  165. // Detect the amount of channels PulseAudio is using
  166. // Note: If using an even amount of channels (2, 4, etc) channels and pa_map.channels will be equal,
  167. // if not then pa_map.channels will have the real amount of channels PulseAudio is using and channels
  168. // will have the amount of channels Godot is using (in this case it's pa_map.channels + 1)
  169. Error err = detect_channels();
  170. if (err != OK) {
  171. // This most likely means there are no sinks.
  172. ERR_PRINT("PulseAudio: init_output_device failed to detect number of output channels");
  173. return err;
  174. }
  175. switch (pa_map.channels) {
  176. case 1: // Mono
  177. case 3: // Surround 2.1
  178. case 5: // Surround 5.0
  179. case 7: // Surround 7.0
  180. channels = pa_map.channels + 1;
  181. break;
  182. case 2: // Stereo
  183. case 4: // Surround 4.0
  184. case 6: // Surround 5.1
  185. case 8: // Surround 7.1
  186. channels = pa_map.channels;
  187. break;
  188. default:
  189. WARN_PRINT("PulseAudio: Unsupported number of output channels: " + itos(pa_map.channels));
  190. pa_channel_map_init_stereo(&pa_map);
  191. channels = 2;
  192. break;
  193. }
  194. int tmp_latency = GLOBAL_GET("audio/driver/output_latency");
  195. buffer_frames = closest_power_of_2(tmp_latency * mix_rate / 1000);
  196. pa_buffer_size = buffer_frames * pa_map.channels;
  197. print_verbose("PulseAudio: detected " + itos(pa_map.channels) + " output channels");
  198. print_verbose("PulseAudio: audio buffer frames: " + itos(buffer_frames) + " calculated output latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  199. pa_sample_spec spec;
  200. spec.format = PA_SAMPLE_S16LE;
  201. spec.channels = pa_map.channels;
  202. spec.rate = mix_rate;
  203. pa_map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
  204. pa_map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
  205. pa_map.map[2] = PA_CHANNEL_POSITION_FRONT_CENTER;
  206. pa_map.map[3] = PA_CHANNEL_POSITION_LFE;
  207. pa_map.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
  208. pa_map.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
  209. pa_map.map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;
  210. pa_map.map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;
  211. pa_str = pa_stream_new(pa_ctx, "Sound", &spec, &pa_map);
  212. if (pa_str == nullptr) {
  213. ERR_PRINT("PulseAudio: pa_stream_new error: " + String(pa_strerror(pa_context_errno(pa_ctx))));
  214. ERR_FAIL_V(ERR_CANT_OPEN);
  215. }
  216. pa_buffer_attr attr;
  217. // set to appropriate buffer length (in bytes) from global settings
  218. // Note: PulseAudio defaults to 4 fragments, which means that the actual
  219. // latency is tlength / fragments. It seems that the PulseAudio has no way
  220. // to get the fragments number so we're hardcoding this to the default of 4
  221. const int fragments = 4;
  222. attr.tlength = pa_buffer_size * sizeof(int16_t) * fragments;
  223. // set them to be automatically chosen
  224. attr.prebuf = (uint32_t)-1;
  225. attr.maxlength = (uint32_t)-1;
  226. attr.minreq = (uint32_t)-1;
  227. const char *dev = output_device_name == "Default" ? nullptr : output_device_name.utf8().get_data();
  228. pa_stream_flags flags = pa_stream_flags(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE);
  229. int error_code = pa_stream_connect_playback(pa_str, dev, &attr, flags, nullptr, nullptr);
  230. ERR_FAIL_COND_V(error_code < 0, ERR_CANT_OPEN);
  231. samples_in.resize(buffer_frames * channels);
  232. samples_out.resize(pa_buffer_size);
  233. // Reset audio input to keep synchronization.
  234. input_position = 0;
  235. input_size = 0;
  236. return OK;
  237. }
  238. Error AudioDriverPulseAudio::init() {
  239. #ifdef SOWRAP_ENABLED
  240. #ifdef DEBUG_ENABLED
  241. int dylibloader_verbose = 1;
  242. #else
  243. int dylibloader_verbose = 0;
  244. #endif
  245. #ifdef ALSAMIDI_ENABLED
  246. // If using PulseAudio with ALSA MIDI, we need to initialize ALSA as well
  247. initialize_asound(dylibloader_verbose);
  248. #endif
  249. if (initialize_pulse(dylibloader_verbose)) {
  250. return ERR_CANT_OPEN;
  251. }
  252. #endif
  253. active.clear();
  254. exit_thread.clear();
  255. mix_rate = _get_configured_mix_rate();
  256. pa_ml = pa_mainloop_new();
  257. ERR_FAIL_COND_V(pa_ml == nullptr, ERR_CANT_OPEN);
  258. String context_name;
  259. if (Engine::get_singleton()->is_editor_hint()) {
  260. context_name = VERSION_NAME " Editor";
  261. } else {
  262. context_name = GLOBAL_GET("application/config/name");
  263. if (context_name.is_empty()) {
  264. context_name = VERSION_NAME " Project";
  265. }
  266. }
  267. pa_ctx = pa_context_new(pa_mainloop_get_api(pa_ml), context_name.utf8().ptr());
  268. ERR_FAIL_COND_V(pa_ctx == nullptr, ERR_CANT_OPEN);
  269. pa_ready = 0;
  270. pa_context_set_state_callback(pa_ctx, pa_state_cb, (void *)this);
  271. int ret = pa_context_connect(pa_ctx, nullptr, PA_CONTEXT_NOFLAGS, nullptr);
  272. if (ret < 0) {
  273. if (pa_ctx) {
  274. pa_context_unref(pa_ctx);
  275. pa_ctx = nullptr;
  276. }
  277. if (pa_ml) {
  278. pa_mainloop_free(pa_ml);
  279. pa_ml = nullptr;
  280. }
  281. return ERR_CANT_OPEN;
  282. }
  283. while (pa_ready == 0) {
  284. ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  285. if (ret < 0) {
  286. ERR_PRINT("pa_mainloop_iterate error");
  287. }
  288. }
  289. if (pa_ready < 0) {
  290. if (pa_ctx) {
  291. pa_context_disconnect(pa_ctx);
  292. pa_context_unref(pa_ctx);
  293. pa_ctx = nullptr;
  294. }
  295. if (pa_ml) {
  296. pa_mainloop_free(pa_ml);
  297. pa_ml = nullptr;
  298. }
  299. return ERR_CANT_OPEN;
  300. }
  301. init_output_device();
  302. thread.start(AudioDriverPulseAudio::thread_func, this);
  303. return OK;
  304. }
  305. float AudioDriverPulseAudio::get_latency() {
  306. if (latency == 0) { //only do this once since it's approximate anyway
  307. lock();
  308. pa_usec_t palat = 0;
  309. if (pa_stream_get_state(pa_str) == PA_STREAM_READY) {
  310. int negative = 0;
  311. if (pa_stream_get_latency(pa_str, &palat, &negative) >= 0) {
  312. if (negative) {
  313. palat = 0;
  314. }
  315. }
  316. }
  317. if (palat > 0) {
  318. latency = double(palat) / 1000000.0;
  319. }
  320. unlock();
  321. }
  322. return latency;
  323. }
  324. void AudioDriverPulseAudio::thread_func(void *p_udata) {
  325. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(p_udata);
  326. unsigned int write_ofs = 0;
  327. size_t avail_bytes = 0;
  328. uint64_t default_device_msec = OS::get_singleton()->get_ticks_msec();
  329. while (!ad->exit_thread.is_set()) {
  330. size_t read_bytes = 0;
  331. size_t written_bytes = 0;
  332. if (avail_bytes == 0) {
  333. ad->lock();
  334. ad->start_counting_ticks();
  335. if (!ad->active.is_set()) {
  336. ad->samples_out.fill(0);
  337. } else {
  338. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  339. int16_t *out_ptr = ad->samples_out.ptrw();
  340. if (ad->channels == ad->pa_map.channels) {
  341. for (unsigned int i = 0; i < ad->pa_buffer_size; i++) {
  342. out_ptr[i] = ad->samples_in[i] >> 16;
  343. }
  344. } else {
  345. // Uneven amount of channels
  346. unsigned int in_idx = 0;
  347. unsigned int out_idx = 0;
  348. for (unsigned int i = 0; i < ad->buffer_frames; i++) {
  349. for (int j = 0; j < ad->pa_map.channels - 1; j++) {
  350. out_ptr[out_idx++] = ad->samples_in[in_idx++] >> 16;
  351. }
  352. uint32_t l = ad->samples_in[in_idx++] >> 16;
  353. uint32_t r = ad->samples_in[in_idx++] >> 16;
  354. out_ptr[out_idx++] = (l + r) / 2;
  355. }
  356. }
  357. }
  358. avail_bytes = ad->pa_buffer_size * sizeof(int16_t);
  359. write_ofs = 0;
  360. ad->stop_counting_ticks();
  361. ad->unlock();
  362. }
  363. ad->lock();
  364. ad->start_counting_ticks();
  365. int ret;
  366. do {
  367. ret = pa_mainloop_iterate(ad->pa_ml, 0, nullptr);
  368. } while (ret > 0);
  369. if (avail_bytes > 0 && pa_stream_get_state(ad->pa_str) == PA_STREAM_READY) {
  370. size_t bytes = pa_stream_writable_size(ad->pa_str);
  371. if (bytes > 0) {
  372. size_t bytes_to_write = MIN(bytes, avail_bytes);
  373. const void *ptr = ad->samples_out.ptr();
  374. ret = pa_stream_write(ad->pa_str, (char *)ptr + write_ofs, bytes_to_write, nullptr, 0LL, PA_SEEK_RELATIVE);
  375. if (ret != 0) {
  376. ERR_PRINT("PulseAudio: pa_stream_write error: " + String(pa_strerror(ret)));
  377. } else {
  378. avail_bytes -= bytes_to_write;
  379. write_ofs += bytes_to_write;
  380. written_bytes += bytes_to_write;
  381. }
  382. }
  383. }
  384. // User selected a new output device, finish the current one so we'll init the new output device
  385. if (ad->output_device_name != ad->new_output_device) {
  386. ad->output_device_name = ad->new_output_device;
  387. ad->finish_output_device();
  388. Error err = ad->init_output_device();
  389. if (err != OK) {
  390. ERR_PRINT("PulseAudio: init_output_device error");
  391. ad->output_device_name = "Default";
  392. ad->new_output_device = "Default";
  393. err = ad->init_output_device();
  394. if (err != OK) {
  395. ad->active.clear();
  396. ad->exit_thread.set();
  397. break;
  398. }
  399. }
  400. avail_bytes = 0;
  401. write_ofs = 0;
  402. }
  403. // If we're using the default output device, check that the current output device is still the default
  404. if (ad->output_device_name == "Default") {
  405. uint64_t msec = OS::get_singleton()->get_ticks_msec();
  406. if (msec > (default_device_msec + 1000)) {
  407. String old_default_device = ad->default_output_device;
  408. default_device_msec = msec;
  409. ad->pa_status = 0;
  410. pa_operation *pa_op = pa_context_get_server_info(ad->pa_ctx, &AudioDriverPulseAudio::pa_server_info_cb, (void *)ad);
  411. if (pa_op) {
  412. while (ad->pa_status == 0) {
  413. ret = pa_mainloop_iterate(ad->pa_ml, 1, nullptr);
  414. if (ret < 0) {
  415. ERR_PRINT("pa_mainloop_iterate error");
  416. }
  417. }
  418. pa_operation_unref(pa_op);
  419. } else {
  420. ERR_PRINT("pa_context_get_server_info error: " + String(pa_strerror(pa_context_errno(ad->pa_ctx))));
  421. }
  422. if (old_default_device != ad->default_output_device) {
  423. ad->finish_output_device();
  424. Error err = ad->init_output_device();
  425. if (err != OK) {
  426. ERR_PRINT("PulseAudio: init_output_device error");
  427. ad->active.clear();
  428. ad->exit_thread.set();
  429. break;
  430. }
  431. avail_bytes = 0;
  432. write_ofs = 0;
  433. }
  434. }
  435. }
  436. if (ad->pa_rec_str && pa_stream_get_state(ad->pa_rec_str) == PA_STREAM_READY) {
  437. size_t bytes = pa_stream_readable_size(ad->pa_rec_str);
  438. if (bytes > 0) {
  439. const void *ptr = nullptr;
  440. size_t maxbytes = ad->input_buffer.size() * sizeof(int16_t);
  441. bytes = MIN(bytes, maxbytes);
  442. ret = pa_stream_peek(ad->pa_rec_str, &ptr, &bytes);
  443. if (ret != 0) {
  444. ERR_PRINT("pa_stream_peek error");
  445. } else {
  446. int16_t *srcptr = (int16_t *)ptr;
  447. for (size_t i = bytes >> 1; i > 0; i--) {
  448. int32_t sample = int32_t(*srcptr++) << 16;
  449. ad->input_buffer_write(sample);
  450. if (ad->pa_rec_map.channels == 1) {
  451. // In case input device is single channel convert it to Stereo
  452. ad->input_buffer_write(sample);
  453. }
  454. }
  455. read_bytes += bytes;
  456. ret = pa_stream_drop(ad->pa_rec_str);
  457. if (ret != 0) {
  458. ERR_PRINT("pa_stream_drop error");
  459. }
  460. }
  461. }
  462. // User selected a new input device, finish the current one so we'll init the new input device
  463. if (ad->input_device_name != ad->new_input_device) {
  464. ad->input_device_name = ad->new_input_device;
  465. ad->finish_input_device();
  466. Error err = ad->init_input_device();
  467. if (err != OK) {
  468. ERR_PRINT("PulseAudio: init_input_device error");
  469. ad->input_device_name = "Default";
  470. ad->new_input_device = "Default";
  471. err = ad->init_input_device();
  472. if (err != OK) {
  473. ad->active.clear();
  474. ad->exit_thread.set();
  475. break;
  476. }
  477. }
  478. }
  479. }
  480. ad->stop_counting_ticks();
  481. ad->unlock();
  482. // Let the thread rest a while if we haven't read or write anything
  483. if (written_bytes == 0 && read_bytes == 0) {
  484. OS::get_singleton()->delay_usec(1000);
  485. }
  486. }
  487. }
  488. void AudioDriverPulseAudio::start() {
  489. active.set();
  490. }
  491. int AudioDriverPulseAudio::get_mix_rate() const {
  492. return mix_rate;
  493. }
  494. AudioDriver::SpeakerMode AudioDriverPulseAudio::get_speaker_mode() const {
  495. return get_speaker_mode_by_total_channels(channels);
  496. }
  497. void AudioDriverPulseAudio::pa_sinklist_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) {
  498. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  499. // If eol is set to a positive number, you're at the end of the list
  500. if (eol > 0) {
  501. return;
  502. }
  503. ad->pa_devices.push_back(l->name);
  504. ad->pa_status++;
  505. }
  506. PackedStringArray AudioDriverPulseAudio::get_output_device_list() {
  507. pa_devices.clear();
  508. pa_devices.push_back("Default");
  509. if (pa_ctx == nullptr) {
  510. return pa_devices;
  511. }
  512. lock();
  513. // Get the output device list
  514. pa_status = 0;
  515. pa_operation *pa_op = pa_context_get_sink_info_list(pa_ctx, pa_sinklist_cb, (void *)this);
  516. if (pa_op) {
  517. while (pa_status == 0) {
  518. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  519. if (ret < 0) {
  520. ERR_PRINT("pa_mainloop_iterate error");
  521. }
  522. }
  523. pa_operation_unref(pa_op);
  524. } else {
  525. ERR_PRINT("pa_context_get_server_info error");
  526. }
  527. unlock();
  528. return pa_devices;
  529. }
  530. String AudioDriverPulseAudio::get_output_device() {
  531. return output_device_name;
  532. }
  533. void AudioDriverPulseAudio::set_output_device(const String &p_name) {
  534. lock();
  535. new_output_device = p_name;
  536. unlock();
  537. }
  538. void AudioDriverPulseAudio::lock() {
  539. mutex.lock();
  540. }
  541. void AudioDriverPulseAudio::unlock() {
  542. mutex.unlock();
  543. }
  544. void AudioDriverPulseAudio::finish_output_device() {
  545. if (pa_str) {
  546. pa_stream_disconnect(pa_str);
  547. pa_stream_unref(pa_str);
  548. pa_str = nullptr;
  549. }
  550. }
  551. void AudioDriverPulseAudio::finish() {
  552. if (!thread.is_started()) {
  553. return;
  554. }
  555. exit_thread.set();
  556. thread.wait_to_finish();
  557. finish_output_device();
  558. if (pa_ctx) {
  559. pa_context_disconnect(pa_ctx);
  560. pa_context_unref(pa_ctx);
  561. pa_ctx = nullptr;
  562. }
  563. if (pa_ml) {
  564. pa_mainloop_free(pa_ml);
  565. pa_ml = nullptr;
  566. }
  567. }
  568. Error AudioDriverPulseAudio::init_input_device() {
  569. // If there is a specified input device, check that it is really present
  570. if (input_device_name != "Default") {
  571. PackedStringArray list = get_input_device_list();
  572. if (list.find(input_device_name) == -1) {
  573. input_device_name = "Default";
  574. new_input_device = "Default";
  575. }
  576. }
  577. detect_channels(true);
  578. switch (pa_rec_map.channels) {
  579. case 1: // Mono
  580. case 2: // Stereo
  581. break;
  582. default:
  583. WARN_PRINT("PulseAudio: Unsupported number of input channels: " + itos(pa_rec_map.channels));
  584. pa_channel_map_init_stereo(&pa_rec_map);
  585. break;
  586. }
  587. print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
  588. pa_sample_spec spec;
  589. spec.format = PA_SAMPLE_S16LE;
  590. spec.channels = pa_rec_map.channels;
  591. spec.rate = mix_rate;
  592. int input_latency = 30;
  593. int input_buffer_frames = closest_power_of_2(input_latency * mix_rate / 1000);
  594. int input_buffer_size = input_buffer_frames * spec.channels;
  595. pa_buffer_attr attr;
  596. attr.fragsize = input_buffer_size * sizeof(int16_t);
  597. pa_rec_str = pa_stream_new(pa_ctx, "Record", &spec, &pa_rec_map);
  598. if (pa_rec_str == nullptr) {
  599. ERR_PRINT("PulseAudio: pa_stream_new error: " + String(pa_strerror(pa_context_errno(pa_ctx))));
  600. ERR_FAIL_V(ERR_CANT_OPEN);
  601. }
  602. const char *dev = input_device_name == "Default" ? nullptr : input_device_name.utf8().get_data();
  603. pa_stream_flags flags = pa_stream_flags(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE);
  604. int error_code = pa_stream_connect_record(pa_rec_str, dev, &attr, flags);
  605. if (error_code < 0) {
  606. ERR_PRINT("PulseAudio: pa_stream_connect_record error: " + String(pa_strerror(error_code)));
  607. ERR_FAIL_V(ERR_CANT_OPEN);
  608. }
  609. input_buffer_init(input_buffer_frames);
  610. print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
  611. print_verbose("PulseAudio: input buffer frames: " + itos(input_buffer_frames) + " calculated latency: " + itos(input_buffer_frames * 1000 / mix_rate) + "ms");
  612. return OK;
  613. }
  614. void AudioDriverPulseAudio::finish_input_device() {
  615. if (pa_rec_str) {
  616. int ret = pa_stream_disconnect(pa_rec_str);
  617. if (ret != 0) {
  618. ERR_PRINT("PulseAudio: pa_stream_disconnect error: " + String(pa_strerror(ret)));
  619. }
  620. pa_stream_unref(pa_rec_str);
  621. pa_rec_str = nullptr;
  622. }
  623. }
  624. Error AudioDriverPulseAudio::input_start() {
  625. lock();
  626. Error err = init_input_device();
  627. unlock();
  628. return err;
  629. }
  630. Error AudioDriverPulseAudio::input_stop() {
  631. lock();
  632. finish_input_device();
  633. unlock();
  634. return OK;
  635. }
  636. void AudioDriverPulseAudio::pa_sourcelist_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) {
  637. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  638. // If eol is set to a positive number, you're at the end of the list
  639. if (eol > 0) {
  640. return;
  641. }
  642. if (l->monitor_of_sink == PA_INVALID_INDEX) {
  643. ad->pa_rec_devices.push_back(l->name);
  644. }
  645. ad->pa_status++;
  646. }
  647. PackedStringArray AudioDriverPulseAudio::get_input_device_list() {
  648. pa_rec_devices.clear();
  649. pa_rec_devices.push_back("Default");
  650. if (pa_ctx == nullptr) {
  651. return pa_rec_devices;
  652. }
  653. lock();
  654. // Get the device list
  655. pa_status = 0;
  656. pa_operation *pa_op = pa_context_get_source_info_list(pa_ctx, pa_sourcelist_cb, (void *)this);
  657. if (pa_op) {
  658. while (pa_status == 0) {
  659. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  660. if (ret < 0) {
  661. ERR_PRINT("pa_mainloop_iterate error");
  662. }
  663. }
  664. pa_operation_unref(pa_op);
  665. } else {
  666. ERR_PRINT("pa_context_get_server_info error");
  667. }
  668. unlock();
  669. return pa_rec_devices;
  670. }
  671. String AudioDriverPulseAudio::get_input_device() {
  672. lock();
  673. String name = input_device_name;
  674. unlock();
  675. return name;
  676. }
  677. void AudioDriverPulseAudio::set_input_device(const String &p_name) {
  678. lock();
  679. new_input_device = p_name;
  680. unlock();
  681. }
  682. AudioDriverPulseAudio::AudioDriverPulseAudio() {
  683. samples_in.clear();
  684. samples_out.clear();
  685. }
  686. #endif // PULSEAUDIO_ENABLED