audio_driver_pulseaudio.cpp 23 KB

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