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