Debian Codegraph @

drivers/pulseaudio/audio_driver_pulseaudio.cpp

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