audio_driver_pulseaudio.cpp 21 KB

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