audio_driver_pulseaudio.cpp 24 KB

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