audio_driver_pulseaudio.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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/os/os.h"
  33. #include "core/project_settings.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. active = false;
  203. thread_exited = false;
  204. exit_thread = false;
  205. mix_rate = GLOBAL_GET("audio/mix_rate");
  206. pa_ml = pa_mainloop_new();
  207. ERR_FAIL_COND_V(pa_ml == nullptr, ERR_CANT_OPEN);
  208. pa_ctx = pa_context_new(pa_mainloop_get_api(pa_ml), "Godot");
  209. ERR_FAIL_COND_V(pa_ctx == nullptr, ERR_CANT_OPEN);
  210. pa_ready = 0;
  211. pa_context_set_state_callback(pa_ctx, pa_state_cb, (void *)this);
  212. int ret = pa_context_connect(pa_ctx, nullptr, PA_CONTEXT_NOFLAGS, nullptr);
  213. if (ret < 0) {
  214. if (pa_ctx) {
  215. pa_context_unref(pa_ctx);
  216. pa_ctx = nullptr;
  217. }
  218. if (pa_ml) {
  219. pa_mainloop_free(pa_ml);
  220. pa_ml = nullptr;
  221. }
  222. return ERR_CANT_OPEN;
  223. }
  224. while (pa_ready == 0) {
  225. ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  226. if (ret < 0) {
  227. ERR_PRINT("pa_mainloop_iterate error");
  228. }
  229. }
  230. if (pa_ready < 0) {
  231. if (pa_ctx) {
  232. pa_context_disconnect(pa_ctx);
  233. pa_context_unref(pa_ctx);
  234. pa_ctx = nullptr;
  235. }
  236. if (pa_ml) {
  237. pa_mainloop_free(pa_ml);
  238. pa_ml = nullptr;
  239. }
  240. return ERR_CANT_OPEN;
  241. }
  242. Error err = init_device();
  243. if (err == OK) {
  244. thread = Thread::create(AudioDriverPulseAudio::thread_func, this);
  245. }
  246. return OK;
  247. }
  248. float AudioDriverPulseAudio::get_latency() {
  249. if (latency == 0) { //only do this once since it's approximate anyway
  250. lock();
  251. pa_usec_t palat = 0;
  252. if (pa_stream_get_state(pa_str) == PA_STREAM_READY) {
  253. int negative = 0;
  254. if (pa_stream_get_latency(pa_str, &palat, &negative) >= 0) {
  255. if (negative) {
  256. palat = 0;
  257. }
  258. }
  259. }
  260. if (palat > 0) {
  261. latency = double(palat) / 1000000.0;
  262. }
  263. unlock();
  264. }
  265. return latency;
  266. }
  267. void AudioDriverPulseAudio::thread_func(void *p_udata) {
  268. AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)p_udata;
  269. unsigned int write_ofs = 0;
  270. size_t avail_bytes = 0;
  271. uint32_t default_device_msec = OS::get_singleton()->get_ticks_msec();
  272. while (!ad->exit_thread) {
  273. size_t read_bytes = 0;
  274. size_t written_bytes = 0;
  275. if (avail_bytes == 0) {
  276. ad->lock();
  277. ad->start_counting_ticks();
  278. if (!ad->active) {
  279. for (unsigned int i = 0; i < ad->pa_buffer_size; i++) {
  280. ad->samples_out.write[i] = 0;
  281. }
  282. } else {
  283. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  284. if (ad->channels == ad->pa_map.channels) {
  285. for (unsigned int i = 0; i < ad->pa_buffer_size; i++) {
  286. ad->samples_out.write[i] = ad->samples_in[i] >> 16;
  287. }
  288. } else {
  289. // Uneven amount of channels
  290. unsigned int in_idx = 0;
  291. unsigned int out_idx = 0;
  292. for (unsigned int i = 0; i < ad->buffer_frames; i++) {
  293. for (int j = 0; j < ad->pa_map.channels - 1; j++) {
  294. ad->samples_out.write[out_idx++] = ad->samples_in[in_idx++] >> 16;
  295. }
  296. uint32_t l = ad->samples_in[in_idx++] >> 16;
  297. uint32_t r = ad->samples_in[in_idx++] >> 16;
  298. ad->samples_out.write[out_idx++] = (l + r) / 2;
  299. }
  300. }
  301. }
  302. avail_bytes = ad->pa_buffer_size * sizeof(int16_t);
  303. write_ofs = 0;
  304. ad->stop_counting_ticks();
  305. ad->unlock();
  306. }
  307. ad->lock();
  308. ad->start_counting_ticks();
  309. int ret;
  310. do {
  311. ret = pa_mainloop_iterate(ad->pa_ml, 0, nullptr);
  312. } while (ret > 0);
  313. if (avail_bytes > 0 && pa_stream_get_state(ad->pa_str) == PA_STREAM_READY) {
  314. size_t bytes = pa_stream_writable_size(ad->pa_str);
  315. if (bytes > 0) {
  316. size_t bytes_to_write = MIN(bytes, avail_bytes);
  317. const void *ptr = ad->samples_out.ptr();
  318. ret = pa_stream_write(ad->pa_str, (char *)ptr + write_ofs, bytes_to_write, nullptr, 0LL, PA_SEEK_RELATIVE);
  319. if (ret != 0) {
  320. ERR_PRINT("PulseAudio: pa_stream_write error: " + String(pa_strerror(ret)));
  321. } else {
  322. avail_bytes -= bytes_to_write;
  323. write_ofs += bytes_to_write;
  324. written_bytes += bytes_to_write;
  325. }
  326. }
  327. }
  328. // User selected a new device, finish the current one so we'll init the new device
  329. if (ad->device_name != ad->new_device) {
  330. ad->device_name = ad->new_device;
  331. ad->finish_device();
  332. Error err = ad->init_device();
  333. if (err != OK) {
  334. ERR_PRINT("PulseAudio: init_device error");
  335. ad->device_name = "Default";
  336. ad->new_device = "Default";
  337. err = ad->init_device();
  338. if (err != OK) {
  339. ad->active = false;
  340. ad->exit_thread = true;
  341. break;
  342. }
  343. }
  344. avail_bytes = 0;
  345. write_ofs = 0;
  346. }
  347. // If we're using the default device check that the current device is still the default
  348. if (ad->device_name == "Default") {
  349. uint32_t msec = OS::get_singleton()->get_ticks_msec();
  350. if (msec > (default_device_msec + 1000)) {
  351. String old_default_device = ad->default_device;
  352. default_device_msec = msec;
  353. ad->pa_status = 0;
  354. pa_operation *pa_op = pa_context_get_server_info(ad->pa_ctx, &AudioDriverPulseAudio::pa_server_info_cb, (void *)ad);
  355. if (pa_op) {
  356. while (ad->pa_status == 0) {
  357. ret = pa_mainloop_iterate(ad->pa_ml, 1, nullptr);
  358. if (ret < 0) {
  359. ERR_PRINT("pa_mainloop_iterate error");
  360. }
  361. }
  362. pa_operation_unref(pa_op);
  363. } else {
  364. ERR_PRINT("pa_context_get_server_info error");
  365. }
  366. if (old_default_device != ad->default_device) {
  367. ad->finish_device();
  368. Error err = ad->init_device();
  369. if (err != OK) {
  370. ERR_PRINT("PulseAudio: init_device error");
  371. ad->active = false;
  372. ad->exit_thread = true;
  373. break;
  374. }
  375. avail_bytes = 0;
  376. write_ofs = 0;
  377. }
  378. }
  379. }
  380. if (ad->pa_rec_str && pa_stream_get_state(ad->pa_rec_str) == PA_STREAM_READY) {
  381. size_t bytes = pa_stream_readable_size(ad->pa_rec_str);
  382. if (bytes > 0) {
  383. const void *ptr = nullptr;
  384. size_t maxbytes = ad->input_buffer.size() * sizeof(int16_t);
  385. bytes = MIN(bytes, maxbytes);
  386. ret = pa_stream_peek(ad->pa_rec_str, &ptr, &bytes);
  387. if (ret != 0) {
  388. ERR_PRINT("pa_stream_peek error");
  389. } else {
  390. int16_t *srcptr = (int16_t *)ptr;
  391. for (size_t i = bytes >> 1; i > 0; i--) {
  392. int32_t sample = int32_t(*srcptr++) << 16;
  393. ad->input_buffer_write(sample);
  394. if (ad->pa_rec_map.channels == 1) {
  395. // In case input device is single channel convert it to Stereo
  396. ad->input_buffer_write(sample);
  397. }
  398. }
  399. read_bytes += bytes;
  400. ret = pa_stream_drop(ad->pa_rec_str);
  401. if (ret != 0) {
  402. ERR_PRINT("pa_stream_drop error");
  403. }
  404. }
  405. }
  406. // User selected a new device, finish the current one so we'll init the new device
  407. if (ad->capture_device_name != ad->capture_new_device) {
  408. ad->capture_device_name = ad->capture_new_device;
  409. ad->capture_finish_device();
  410. Error err = ad->capture_init_device();
  411. if (err != OK) {
  412. ERR_PRINT("PulseAudio: capture_init_device error");
  413. ad->capture_device_name = "Default";
  414. ad->capture_new_device = "Default";
  415. err = ad->capture_init_device();
  416. if (err != OK) {
  417. ad->active = false;
  418. ad->exit_thread = true;
  419. break;
  420. }
  421. }
  422. }
  423. }
  424. ad->stop_counting_ticks();
  425. ad->unlock();
  426. // Let the thread rest a while if we haven't read or write anything
  427. if (written_bytes == 0 && read_bytes == 0) {
  428. OS::get_singleton()->delay_usec(1000);
  429. }
  430. }
  431. ad->thread_exited = true;
  432. }
  433. void AudioDriverPulseAudio::start() {
  434. active = true;
  435. }
  436. int AudioDriverPulseAudio::get_mix_rate() const {
  437. return mix_rate;
  438. }
  439. AudioDriver::SpeakerMode AudioDriverPulseAudio::get_speaker_mode() const {
  440. return get_speaker_mode_by_total_channels(channels);
  441. }
  442. void AudioDriverPulseAudio::pa_sinklist_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) {
  443. AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata;
  444. // If eol is set to a positive number, you're at the end of the list
  445. if (eol > 0) {
  446. return;
  447. }
  448. ad->pa_devices.push_back(l->name);
  449. ad->pa_status++;
  450. }
  451. Array AudioDriverPulseAudio::get_device_list() {
  452. pa_devices.clear();
  453. pa_devices.push_back("Default");
  454. if (pa_ctx == nullptr) {
  455. return pa_devices;
  456. }
  457. lock();
  458. // Get the device list
  459. pa_status = 0;
  460. pa_operation *pa_op = pa_context_get_sink_info_list(pa_ctx, pa_sinklist_cb, (void *)this);
  461. if (pa_op) {
  462. while (pa_status == 0) {
  463. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  464. if (ret < 0) {
  465. ERR_PRINT("pa_mainloop_iterate error");
  466. }
  467. }
  468. pa_operation_unref(pa_op);
  469. } else {
  470. ERR_PRINT("pa_context_get_server_info error");
  471. }
  472. unlock();
  473. return pa_devices;
  474. }
  475. String AudioDriverPulseAudio::get_device() {
  476. return device_name;
  477. }
  478. void AudioDriverPulseAudio::set_device(String device) {
  479. lock();
  480. new_device = device;
  481. unlock();
  482. }
  483. void AudioDriverPulseAudio::lock() {
  484. if (!thread) {
  485. return;
  486. }
  487. mutex.lock();
  488. }
  489. void AudioDriverPulseAudio::unlock() {
  490. if (!thread) {
  491. return;
  492. }
  493. mutex.unlock();
  494. }
  495. void AudioDriverPulseAudio::finish_device() {
  496. if (pa_str) {
  497. pa_stream_disconnect(pa_str);
  498. pa_stream_unref(pa_str);
  499. pa_str = nullptr;
  500. }
  501. }
  502. void AudioDriverPulseAudio::finish() {
  503. if (!thread) {
  504. return;
  505. }
  506. exit_thread = true;
  507. Thread::wait_to_finish(thread);
  508. finish_device();
  509. if (pa_ctx) {
  510. pa_context_disconnect(pa_ctx);
  511. pa_context_unref(pa_ctx);
  512. pa_ctx = nullptr;
  513. }
  514. if (pa_ml) {
  515. pa_mainloop_free(pa_ml);
  516. pa_ml = nullptr;
  517. }
  518. memdelete(thread);
  519. thread = nullptr;
  520. }
  521. Error AudioDriverPulseAudio::capture_init_device() {
  522. // If there is a specified device check that it is really present
  523. if (capture_device_name != "Default") {
  524. Array list = capture_get_device_list();
  525. if (list.find(capture_device_name) == -1) {
  526. capture_device_name = "Default";
  527. capture_new_device = "Default";
  528. }
  529. }
  530. detect_channels(true);
  531. switch (pa_rec_map.channels) {
  532. case 1: // Mono
  533. case 2: // Stereo
  534. break;
  535. default:
  536. WARN_PRINT("PulseAudio: Unsupported number of input channels: " + itos(pa_rec_map.channels));
  537. pa_channel_map_init_stereo(&pa_rec_map);
  538. break;
  539. }
  540. pa_sample_spec spec;
  541. spec.format = PA_SAMPLE_S16LE;
  542. spec.channels = pa_rec_map.channels;
  543. spec.rate = mix_rate;
  544. int input_latency = 30;
  545. int input_buffer_frames = closest_power_of_2(input_latency * mix_rate / 1000);
  546. int input_buffer_size = input_buffer_frames * spec.channels;
  547. pa_buffer_attr attr;
  548. attr.fragsize = input_buffer_size * sizeof(int16_t);
  549. pa_rec_str = pa_stream_new(pa_ctx, "Record", &spec, &pa_rec_map);
  550. if (pa_rec_str == nullptr) {
  551. ERR_PRINT("PulseAudio: pa_stream_new error: " + String(pa_strerror(pa_context_errno(pa_ctx))));
  552. ERR_FAIL_V(ERR_CANT_OPEN);
  553. }
  554. const char *dev = capture_device_name == "Default" ? nullptr : capture_device_name.utf8().get_data();
  555. pa_stream_flags flags = pa_stream_flags(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE);
  556. int error_code = pa_stream_connect_record(pa_rec_str, dev, &attr, flags);
  557. if (error_code < 0) {
  558. ERR_PRINT("PulseAudio: pa_stream_connect_record error: " + String(pa_strerror(error_code)));
  559. ERR_FAIL_V(ERR_CANT_OPEN);
  560. }
  561. input_buffer_init(input_buffer_frames);
  562. print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
  563. print_verbose("PulseAudio: input buffer frames: " + itos(input_buffer_frames) + " calculated latency: " + itos(input_buffer_frames * 1000 / mix_rate) + "ms");
  564. return OK;
  565. }
  566. void AudioDriverPulseAudio::capture_finish_device() {
  567. if (pa_rec_str) {
  568. int ret = pa_stream_disconnect(pa_rec_str);
  569. if (ret != 0) {
  570. ERR_PRINT("PulseAudio: pa_stream_disconnect error: " + String(pa_strerror(ret)));
  571. }
  572. pa_stream_unref(pa_rec_str);
  573. pa_rec_str = nullptr;
  574. }
  575. }
  576. Error AudioDriverPulseAudio::capture_start() {
  577. lock();
  578. Error err = capture_init_device();
  579. unlock();
  580. return err;
  581. }
  582. Error AudioDriverPulseAudio::capture_stop() {
  583. lock();
  584. capture_finish_device();
  585. unlock();
  586. return OK;
  587. }
  588. void AudioDriverPulseAudio::capture_set_device(const String &p_name) {
  589. lock();
  590. capture_new_device = p_name;
  591. unlock();
  592. }
  593. void AudioDriverPulseAudio::pa_sourcelist_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) {
  594. AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata;
  595. // If eol is set to a positive number, you're at the end of the list
  596. if (eol > 0) {
  597. return;
  598. }
  599. if (l->monitor_of_sink == PA_INVALID_INDEX) {
  600. ad->pa_rec_devices.push_back(l->name);
  601. }
  602. ad->pa_status++;
  603. }
  604. Array AudioDriverPulseAudio::capture_get_device_list() {
  605. pa_rec_devices.clear();
  606. pa_rec_devices.push_back("Default");
  607. if (pa_ctx == nullptr) {
  608. return pa_rec_devices;
  609. }
  610. lock();
  611. // Get the device list
  612. pa_status = 0;
  613. pa_operation *pa_op = pa_context_get_source_info_list(pa_ctx, pa_sourcelist_cb, (void *)this);
  614. if (pa_op) {
  615. while (pa_status == 0) {
  616. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  617. if (ret < 0) {
  618. ERR_PRINT("pa_mainloop_iterate error");
  619. }
  620. }
  621. pa_operation_unref(pa_op);
  622. } else {
  623. ERR_PRINT("pa_context_get_server_info error");
  624. }
  625. unlock();
  626. return pa_rec_devices;
  627. }
  628. String AudioDriverPulseAudio::capture_get_device() {
  629. lock();
  630. String name = capture_device_name;
  631. unlock();
  632. return name;
  633. }
  634. AudioDriverPulseAudio::AudioDriverPulseAudio() {
  635. samples_in.clear();
  636. samples_out.clear();
  637. }
  638. #endif // PULSEAUDIO_ENABLED