audio_driver_pulseaudio.cpp 24 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/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. bool ver_ok = false;
  254. String version = String::utf8(pa_get_library_version());
  255. Vector<String> ver_parts = version.split(".");
  256. if (ver_parts.size() >= 2) {
  257. ver_ok = (ver_parts[0].to_int() >= 8); // 8.0.0
  258. }
  259. print_verbose(vformat("PulseAudio %s detected.", version));
  260. if (!ver_ok) {
  261. print_verbose("Unsupported PulseAudio library version!");
  262. return ERR_CANT_OPEN;
  263. }
  264. active.clear();
  265. exit_thread.clear();
  266. mix_rate = _get_configured_mix_rate();
  267. pa_ml = pa_mainloop_new();
  268. ERR_FAIL_COND_V(pa_ml == nullptr, ERR_CANT_OPEN);
  269. String context_name;
  270. if (Engine::get_singleton()->is_editor_hint()) {
  271. context_name = VERSION_NAME " Editor";
  272. } else {
  273. context_name = GLOBAL_GET("application/config/name");
  274. if (context_name.is_empty()) {
  275. context_name = VERSION_NAME " Project";
  276. }
  277. }
  278. pa_ctx = pa_context_new(pa_mainloop_get_api(pa_ml), context_name.utf8().ptr());
  279. ERR_FAIL_COND_V(pa_ctx == nullptr, ERR_CANT_OPEN);
  280. pa_ready = 0;
  281. pa_context_set_state_callback(pa_ctx, pa_state_cb, (void *)this);
  282. int ret = pa_context_connect(pa_ctx, nullptr, PA_CONTEXT_NOFLAGS, nullptr);
  283. if (ret < 0) {
  284. if (pa_ctx) {
  285. pa_context_unref(pa_ctx);
  286. pa_ctx = nullptr;
  287. }
  288. if (pa_ml) {
  289. pa_mainloop_free(pa_ml);
  290. pa_ml = nullptr;
  291. }
  292. return ERR_CANT_OPEN;
  293. }
  294. while (pa_ready == 0) {
  295. ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  296. if (ret < 0) {
  297. ERR_PRINT("pa_mainloop_iterate error");
  298. }
  299. }
  300. if (pa_ready < 0) {
  301. if (pa_ctx) {
  302. pa_context_disconnect(pa_ctx);
  303. pa_context_unref(pa_ctx);
  304. pa_ctx = nullptr;
  305. }
  306. if (pa_ml) {
  307. pa_mainloop_free(pa_ml);
  308. pa_ml = nullptr;
  309. }
  310. return ERR_CANT_OPEN;
  311. }
  312. init_output_device();
  313. thread.start(AudioDriverPulseAudio::thread_func, this);
  314. return OK;
  315. }
  316. float AudioDriverPulseAudio::get_latency() {
  317. if (latency == 0) { //only do this once since it's approximate anyway
  318. lock();
  319. pa_usec_t palat = 0;
  320. if (pa_stream_get_state(pa_str) == PA_STREAM_READY) {
  321. int negative = 0;
  322. if (pa_stream_get_latency(pa_str, &palat, &negative) >= 0) {
  323. if (negative) {
  324. palat = 0;
  325. }
  326. }
  327. }
  328. if (palat > 0) {
  329. latency = double(palat) / 1000000.0;
  330. }
  331. unlock();
  332. }
  333. return latency;
  334. }
  335. void AudioDriverPulseAudio::thread_func(void *p_udata) {
  336. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(p_udata);
  337. unsigned int write_ofs = 0;
  338. size_t avail_bytes = 0;
  339. uint64_t default_device_msec = OS::get_singleton()->get_ticks_msec();
  340. while (!ad->exit_thread.is_set()) {
  341. size_t read_bytes = 0;
  342. size_t written_bytes = 0;
  343. if (avail_bytes == 0) {
  344. ad->lock();
  345. ad->start_counting_ticks();
  346. if (!ad->active.is_set()) {
  347. ad->samples_out.fill(0);
  348. } else {
  349. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  350. int16_t *out_ptr = ad->samples_out.ptrw();
  351. if (ad->channels == ad->pa_map.channels) {
  352. for (unsigned int i = 0; i < ad->pa_buffer_size; i++) {
  353. out_ptr[i] = ad->samples_in[i] >> 16;
  354. }
  355. } else {
  356. // Uneven amount of channels
  357. unsigned int in_idx = 0;
  358. unsigned int out_idx = 0;
  359. for (unsigned int i = 0; i < ad->buffer_frames; i++) {
  360. for (int j = 0; j < ad->pa_map.channels - 1; j++) {
  361. out_ptr[out_idx++] = ad->samples_in[in_idx++] >> 16;
  362. }
  363. uint32_t l = ad->samples_in[in_idx++] >> 16;
  364. uint32_t r = ad->samples_in[in_idx++] >> 16;
  365. out_ptr[out_idx++] = (l + r) / 2;
  366. }
  367. }
  368. }
  369. avail_bytes = ad->pa_buffer_size * sizeof(int16_t);
  370. write_ofs = 0;
  371. ad->stop_counting_ticks();
  372. ad->unlock();
  373. }
  374. ad->lock();
  375. ad->start_counting_ticks();
  376. int ret;
  377. do {
  378. ret = pa_mainloop_iterate(ad->pa_ml, 0, nullptr);
  379. } while (ret > 0);
  380. if (avail_bytes > 0 && pa_stream_get_state(ad->pa_str) == PA_STREAM_READY) {
  381. size_t bytes = pa_stream_writable_size(ad->pa_str);
  382. if (bytes > 0) {
  383. size_t bytes_to_write = MIN(bytes, avail_bytes);
  384. const void *ptr = ad->samples_out.ptr();
  385. ret = pa_stream_write(ad->pa_str, (char *)ptr + write_ofs, bytes_to_write, nullptr, 0LL, PA_SEEK_RELATIVE);
  386. if (ret != 0) {
  387. ERR_PRINT("PulseAudio: pa_stream_write error: " + String(pa_strerror(ret)));
  388. } else {
  389. avail_bytes -= bytes_to_write;
  390. write_ofs += bytes_to_write;
  391. written_bytes += bytes_to_write;
  392. }
  393. }
  394. }
  395. // User selected a new output device, finish the current one so we'll init the new output device
  396. if (ad->output_device_name != ad->new_output_device) {
  397. ad->output_device_name = ad->new_output_device;
  398. ad->finish_output_device();
  399. Error err = ad->init_output_device();
  400. if (err != OK) {
  401. ERR_PRINT("PulseAudio: init_output_device error");
  402. ad->output_device_name = "Default";
  403. ad->new_output_device = "Default";
  404. err = ad->init_output_device();
  405. if (err != OK) {
  406. ad->active.clear();
  407. ad->exit_thread.set();
  408. break;
  409. }
  410. }
  411. avail_bytes = 0;
  412. write_ofs = 0;
  413. }
  414. // If we're using the default output device, check that the current output device is still the default
  415. if (ad->output_device_name == "Default") {
  416. uint64_t msec = OS::get_singleton()->get_ticks_msec();
  417. if (msec > (default_device_msec + 1000)) {
  418. String old_default_device = ad->default_output_device;
  419. default_device_msec = msec;
  420. ad->pa_status = 0;
  421. pa_operation *pa_op = pa_context_get_server_info(ad->pa_ctx, &AudioDriverPulseAudio::pa_server_info_cb, (void *)ad);
  422. if (pa_op) {
  423. while (ad->pa_status == 0) {
  424. ret = pa_mainloop_iterate(ad->pa_ml, 1, nullptr);
  425. if (ret < 0) {
  426. ERR_PRINT("pa_mainloop_iterate error");
  427. }
  428. }
  429. pa_operation_unref(pa_op);
  430. } else {
  431. ERR_PRINT("pa_context_get_server_info error: " + String(pa_strerror(pa_context_errno(ad->pa_ctx))));
  432. }
  433. if (old_default_device != ad->default_output_device) {
  434. ad->finish_output_device();
  435. Error err = ad->init_output_device();
  436. if (err != OK) {
  437. ERR_PRINT("PulseAudio: init_output_device error");
  438. ad->active.clear();
  439. ad->exit_thread.set();
  440. break;
  441. }
  442. avail_bytes = 0;
  443. write_ofs = 0;
  444. }
  445. }
  446. }
  447. if (ad->pa_rec_str && pa_stream_get_state(ad->pa_rec_str) == PA_STREAM_READY) {
  448. size_t bytes = pa_stream_readable_size(ad->pa_rec_str);
  449. if (bytes > 0) {
  450. const void *ptr = nullptr;
  451. size_t maxbytes = ad->input_buffer.size() * sizeof(int16_t);
  452. bytes = MIN(bytes, maxbytes);
  453. ret = pa_stream_peek(ad->pa_rec_str, &ptr, &bytes);
  454. if (ret != 0) {
  455. ERR_PRINT("pa_stream_peek error");
  456. } else {
  457. int16_t *srcptr = (int16_t *)ptr;
  458. for (size_t i = bytes >> 1; i > 0; i--) {
  459. int32_t sample = int32_t(*srcptr++) << 16;
  460. ad->input_buffer_write(sample);
  461. if (ad->pa_rec_map.channels == 1) {
  462. // In case input device is single channel convert it to Stereo
  463. ad->input_buffer_write(sample);
  464. }
  465. }
  466. read_bytes += bytes;
  467. ret = pa_stream_drop(ad->pa_rec_str);
  468. if (ret != 0) {
  469. ERR_PRINT("pa_stream_drop error");
  470. }
  471. }
  472. }
  473. // User selected a new input device, finish the current one so we'll init the new input device
  474. if (ad->input_device_name != ad->new_input_device) {
  475. ad->input_device_name = ad->new_input_device;
  476. ad->finish_input_device();
  477. Error err = ad->init_input_device();
  478. if (err != OK) {
  479. ERR_PRINT("PulseAudio: init_input_device error");
  480. ad->input_device_name = "Default";
  481. ad->new_input_device = "Default";
  482. err = ad->init_input_device();
  483. if (err != OK) {
  484. ad->active.clear();
  485. ad->exit_thread.set();
  486. break;
  487. }
  488. }
  489. }
  490. }
  491. ad->stop_counting_ticks();
  492. ad->unlock();
  493. // Let the thread rest a while if we haven't read or write anything
  494. if (written_bytes == 0 && read_bytes == 0) {
  495. OS::get_singleton()->delay_usec(1000);
  496. }
  497. }
  498. }
  499. void AudioDriverPulseAudio::start() {
  500. active.set();
  501. }
  502. int AudioDriverPulseAudio::get_mix_rate() const {
  503. return mix_rate;
  504. }
  505. AudioDriver::SpeakerMode AudioDriverPulseAudio::get_speaker_mode() const {
  506. return get_speaker_mode_by_total_channels(channels);
  507. }
  508. void AudioDriverPulseAudio::pa_sinklist_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) {
  509. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  510. // If eol is set to a positive number, you're at the end of the list
  511. if (eol > 0) {
  512. return;
  513. }
  514. ad->pa_devices.push_back(l->name);
  515. ad->pa_status++;
  516. }
  517. PackedStringArray AudioDriverPulseAudio::get_output_device_list() {
  518. pa_devices.clear();
  519. pa_devices.push_back("Default");
  520. if (pa_ctx == nullptr) {
  521. return pa_devices;
  522. }
  523. lock();
  524. // Get the output device list
  525. pa_status = 0;
  526. pa_operation *pa_op = pa_context_get_sink_info_list(pa_ctx, pa_sinklist_cb, (void *)this);
  527. if (pa_op) {
  528. while (pa_status == 0) {
  529. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  530. if (ret < 0) {
  531. ERR_PRINT("pa_mainloop_iterate error");
  532. }
  533. }
  534. pa_operation_unref(pa_op);
  535. } else {
  536. ERR_PRINT("pa_context_get_server_info error");
  537. }
  538. unlock();
  539. return pa_devices;
  540. }
  541. String AudioDriverPulseAudio::get_output_device() {
  542. return output_device_name;
  543. }
  544. void AudioDriverPulseAudio::set_output_device(const String &p_name) {
  545. lock();
  546. new_output_device = p_name;
  547. unlock();
  548. }
  549. void AudioDriverPulseAudio::lock() {
  550. mutex.lock();
  551. }
  552. void AudioDriverPulseAudio::unlock() {
  553. mutex.unlock();
  554. }
  555. void AudioDriverPulseAudio::finish_output_device() {
  556. if (pa_str) {
  557. pa_stream_disconnect(pa_str);
  558. pa_stream_unref(pa_str);
  559. pa_str = nullptr;
  560. }
  561. }
  562. void AudioDriverPulseAudio::finish() {
  563. if (!thread.is_started()) {
  564. return;
  565. }
  566. exit_thread.set();
  567. if (thread.is_started()) {
  568. thread.wait_to_finish();
  569. }
  570. finish_output_device();
  571. if (pa_ctx) {
  572. pa_context_disconnect(pa_ctx);
  573. pa_context_unref(pa_ctx);
  574. pa_ctx = nullptr;
  575. }
  576. if (pa_ml) {
  577. pa_mainloop_free(pa_ml);
  578. pa_ml = nullptr;
  579. }
  580. }
  581. Error AudioDriverPulseAudio::init_input_device() {
  582. // If there is a specified input device, check that it is really present
  583. if (input_device_name != "Default") {
  584. PackedStringArray list = get_input_device_list();
  585. if (list.find(input_device_name) == -1) {
  586. input_device_name = "Default";
  587. new_input_device = "Default";
  588. }
  589. }
  590. detect_channels(true);
  591. switch (pa_rec_map.channels) {
  592. case 1: // Mono
  593. case 2: // Stereo
  594. break;
  595. default:
  596. WARN_PRINT("PulseAudio: Unsupported number of input channels: " + itos(pa_rec_map.channels));
  597. pa_channel_map_init_stereo(&pa_rec_map);
  598. break;
  599. }
  600. print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
  601. pa_sample_spec spec;
  602. spec.format = PA_SAMPLE_S16LE;
  603. spec.channels = pa_rec_map.channels;
  604. spec.rate = mix_rate;
  605. int input_latency = 30;
  606. int input_buffer_frames = closest_power_of_2(input_latency * mix_rate / 1000);
  607. int input_buffer_size = input_buffer_frames * spec.channels;
  608. pa_buffer_attr attr;
  609. attr.fragsize = input_buffer_size * sizeof(int16_t);
  610. pa_rec_str = pa_stream_new(pa_ctx, "Record", &spec, &pa_rec_map);
  611. if (pa_rec_str == nullptr) {
  612. ERR_PRINT("PulseAudio: pa_stream_new error: " + String(pa_strerror(pa_context_errno(pa_ctx))));
  613. ERR_FAIL_V(ERR_CANT_OPEN);
  614. }
  615. const char *dev = input_device_name == "Default" ? nullptr : input_device_name.utf8().get_data();
  616. pa_stream_flags flags = pa_stream_flags(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE);
  617. int error_code = pa_stream_connect_record(pa_rec_str, dev, &attr, flags);
  618. if (error_code < 0) {
  619. ERR_PRINT("PulseAudio: pa_stream_connect_record error: " + String(pa_strerror(error_code)));
  620. ERR_FAIL_V(ERR_CANT_OPEN);
  621. }
  622. input_buffer_init(input_buffer_frames);
  623. print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
  624. print_verbose("PulseAudio: input buffer frames: " + itos(input_buffer_frames) + " calculated latency: " + itos(input_buffer_frames * 1000 / mix_rate) + "ms");
  625. return OK;
  626. }
  627. void AudioDriverPulseAudio::finish_input_device() {
  628. if (pa_rec_str) {
  629. int ret = pa_stream_disconnect(pa_rec_str);
  630. if (ret != 0) {
  631. ERR_PRINT("PulseAudio: pa_stream_disconnect error: " + String(pa_strerror(ret)));
  632. }
  633. pa_stream_unref(pa_rec_str);
  634. pa_rec_str = nullptr;
  635. }
  636. }
  637. Error AudioDriverPulseAudio::input_start() {
  638. lock();
  639. Error err = init_input_device();
  640. unlock();
  641. return err;
  642. }
  643. Error AudioDriverPulseAudio::input_stop() {
  644. lock();
  645. finish_input_device();
  646. unlock();
  647. return OK;
  648. }
  649. void AudioDriverPulseAudio::pa_sourcelist_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) {
  650. AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
  651. // If eol is set to a positive number, you're at the end of the list
  652. if (eol > 0) {
  653. return;
  654. }
  655. if (l->monitor_of_sink == PA_INVALID_INDEX) {
  656. ad->pa_rec_devices.push_back(l->name);
  657. }
  658. ad->pa_status++;
  659. }
  660. PackedStringArray AudioDriverPulseAudio::get_input_device_list() {
  661. pa_rec_devices.clear();
  662. pa_rec_devices.push_back("Default");
  663. if (pa_ctx == nullptr) {
  664. return pa_rec_devices;
  665. }
  666. lock();
  667. // Get the device list
  668. pa_status = 0;
  669. pa_operation *pa_op = pa_context_get_source_info_list(pa_ctx, pa_sourcelist_cb, (void *)this);
  670. if (pa_op) {
  671. while (pa_status == 0) {
  672. int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
  673. if (ret < 0) {
  674. ERR_PRINT("pa_mainloop_iterate error");
  675. }
  676. }
  677. pa_operation_unref(pa_op);
  678. } else {
  679. ERR_PRINT("pa_context_get_server_info error");
  680. }
  681. unlock();
  682. return pa_rec_devices;
  683. }
  684. String AudioDriverPulseAudio::get_input_device() {
  685. lock();
  686. String name = input_device_name;
  687. unlock();
  688. return name;
  689. }
  690. void AudioDriverPulseAudio::set_input_device(const String &p_name) {
  691. lock();
  692. new_input_device = p_name;
  693. unlock();
  694. }
  695. AudioDriverPulseAudio::AudioDriverPulseAudio() {
  696. samples_in.clear();
  697. samples_out.clear();
  698. }
  699. #endif // PULSEAUDIO_ENABLED