Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/drivers/pulseaudio/audio_driver_pulseaudio.cpp
9973 views
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 (ad->input_device_name != ad->new_input_device) {
559
ad->input_device_name = ad->new_input_device;
560
ad->finish_input_device();
561
562
Error err = ad->init_input_device();
563
if (err != OK) {
564
ERR_PRINT("PulseAudio: init_input_device error");
565
ad->input_device_name = "Default";
566
ad->new_input_device = "Default";
567
568
err = ad->init_input_device();
569
if (err != OK) {
570
ad->active.clear();
571
ad->exit_thread.set();
572
break;
573
}
574
}
575
}
576
}
577
578
ad->stop_counting_ticks();
579
ad->unlock();
580
581
// Let the thread rest a while if we haven't read or write anything
582
if (written_bytes == 0 && read_bytes == 0) {
583
OS::get_singleton()->delay_usec(1000);
584
}
585
}
586
}
587
588
void AudioDriverPulseAudio::start() {
589
active.set();
590
}
591
592
int AudioDriverPulseAudio::get_mix_rate() const {
593
return mix_rate;
594
}
595
596
AudioDriver::SpeakerMode AudioDriverPulseAudio::get_speaker_mode() const {
597
return get_speaker_mode_by_total_channels(channels);
598
}
599
600
void AudioDriverPulseAudio::pa_sinklist_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) {
601
AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
602
603
// If eol is set to a positive number, you're at the end of the list
604
if (eol > 0) {
605
return;
606
}
607
608
ad->pa_devices.push_back(l->name);
609
ad->pa_status++;
610
}
611
612
PackedStringArray AudioDriverPulseAudio::get_output_device_list() {
613
pa_devices.clear();
614
pa_devices.push_back("Default");
615
616
if (pa_ctx == nullptr) {
617
return pa_devices;
618
}
619
620
lock();
621
622
// Get the output device list
623
pa_status = 0;
624
pa_operation *pa_op = pa_context_get_sink_info_list(pa_ctx, pa_sinklist_cb, (void *)this);
625
if (pa_op) {
626
while (pa_status == 0) {
627
int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
628
if (ret < 0) {
629
ERR_PRINT("pa_mainloop_iterate error");
630
}
631
}
632
633
pa_operation_unref(pa_op);
634
} else {
635
ERR_PRINT("pa_context_get_server_info error");
636
}
637
638
unlock();
639
640
return pa_devices;
641
}
642
643
String AudioDriverPulseAudio::get_output_device() {
644
return output_device_name;
645
}
646
647
void AudioDriverPulseAudio::set_output_device(const String &p_name) {
648
lock();
649
new_output_device = p_name;
650
unlock();
651
}
652
653
void AudioDriverPulseAudio::lock() {
654
mutex.lock();
655
}
656
657
void AudioDriverPulseAudio::unlock() {
658
mutex.unlock();
659
}
660
661
void AudioDriverPulseAudio::finish_output_device() {
662
if (pa_str) {
663
pa_stream_disconnect(pa_str);
664
pa_stream_unref(pa_str);
665
pa_str = nullptr;
666
}
667
}
668
669
void AudioDriverPulseAudio::finish() {
670
if (!thread.is_started()) {
671
return;
672
}
673
674
exit_thread.set();
675
if (thread.is_started()) {
676
thread.wait_to_finish();
677
}
678
679
finish_output_device();
680
681
if (pa_ctx) {
682
pa_context_disconnect(pa_ctx);
683
pa_context_unref(pa_ctx);
684
pa_ctx = nullptr;
685
}
686
687
if (pa_ml) {
688
pa_mainloop_free(pa_ml);
689
pa_ml = nullptr;
690
}
691
}
692
693
Error AudioDriverPulseAudio::init_input_device() {
694
// If there is a specified input device, check that it is really present
695
if (input_device_name != "Default") {
696
PackedStringArray list = get_input_device_list();
697
if (!list.has(input_device_name)) {
698
input_device_name = "Default";
699
new_input_device = "Default";
700
}
701
}
702
703
detect_channels(true);
704
switch (pa_rec_map.channels) {
705
case 1: // Mono
706
case 2: // Stereo
707
break;
708
709
default:
710
WARN_PRINT("PulseAudio: Unsupported number of input channels: " + itos(pa_rec_map.channels));
711
pa_channel_map_init_stereo(&pa_rec_map);
712
break;
713
}
714
715
print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
716
717
pa_sample_spec spec;
718
719
spec.format = PA_SAMPLE_S16LE;
720
spec.channels = pa_rec_map.channels;
721
spec.rate = mix_rate;
722
723
int input_latency = 30;
724
int input_buffer_frames = closest_power_of_2(input_latency * mix_rate / 1000);
725
int input_buffer_size = input_buffer_frames * spec.channels;
726
727
pa_buffer_attr attr = {};
728
attr.maxlength = (uint32_t)-1;
729
attr.fragsize = input_buffer_size * sizeof(int16_t);
730
731
pa_rec_str = pa_stream_new(pa_ctx, "Record", &spec, &pa_rec_map);
732
if (pa_rec_str == nullptr) {
733
ERR_PRINT("PulseAudio: pa_stream_new error: " + String(pa_strerror(pa_context_errno(pa_ctx))));
734
ERR_FAIL_V(ERR_CANT_OPEN);
735
}
736
737
const char *dev = input_device_name == "Default" ? nullptr : input_device_name.utf8().get_data();
738
pa_stream_flags flags = pa_stream_flags(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE);
739
int error_code = pa_stream_connect_record(pa_rec_str, dev, &attr, flags);
740
if (error_code < 0) {
741
ERR_PRINT("PulseAudio: pa_stream_connect_record error: " + String(pa_strerror(error_code)));
742
ERR_FAIL_V(ERR_CANT_OPEN);
743
}
744
745
input_buffer_init(input_buffer_frames);
746
747
print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels");
748
print_verbose("PulseAudio: input buffer frames: " + itos(input_buffer_frames) + " calculated latency: " + itos(input_buffer_frames * 1000 / mix_rate) + "ms");
749
750
return OK;
751
}
752
753
void AudioDriverPulseAudio::finish_input_device() {
754
if (pa_rec_str) {
755
int ret = pa_stream_disconnect(pa_rec_str);
756
if (ret != 0) {
757
ERR_PRINT("PulseAudio: pa_stream_disconnect error: " + String(pa_strerror(ret)));
758
}
759
pa_stream_unref(pa_rec_str);
760
pa_rec_str = nullptr;
761
}
762
}
763
764
Error AudioDriverPulseAudio::input_start() {
765
lock();
766
Error err = init_input_device();
767
unlock();
768
769
return err;
770
}
771
772
Error AudioDriverPulseAudio::input_stop() {
773
lock();
774
finish_input_device();
775
unlock();
776
777
return OK;
778
}
779
780
void AudioDriverPulseAudio::pa_sourcelist_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) {
781
AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata);
782
783
// If eol is set to a positive number, you're at the end of the list
784
if (eol > 0) {
785
return;
786
}
787
788
if (l->monitor_of_sink == PA_INVALID_INDEX) {
789
ad->pa_rec_devices.push_back(l->name);
790
}
791
792
ad->pa_status++;
793
}
794
795
PackedStringArray AudioDriverPulseAudio::get_input_device_list() {
796
pa_rec_devices.clear();
797
pa_rec_devices.push_back("Default");
798
799
if (pa_ctx == nullptr) {
800
return pa_rec_devices;
801
}
802
803
lock();
804
805
// Get the device list
806
pa_status = 0;
807
pa_operation *pa_op = pa_context_get_source_info_list(pa_ctx, pa_sourcelist_cb, (void *)this);
808
if (pa_op) {
809
while (pa_status == 0) {
810
int ret = pa_mainloop_iterate(pa_ml, 1, nullptr);
811
if (ret < 0) {
812
ERR_PRINT("pa_mainloop_iterate error");
813
}
814
}
815
816
pa_operation_unref(pa_op);
817
} else {
818
ERR_PRINT("pa_context_get_server_info error");
819
}
820
821
unlock();
822
823
return pa_rec_devices;
824
}
825
826
String AudioDriverPulseAudio::get_input_device() {
827
lock();
828
String name = input_device_name;
829
unlock();
830
831
return name;
832
}
833
834
void AudioDriverPulseAudio::set_input_device(const String &p_name) {
835
lock();
836
new_input_device = p_name;
837
unlock();
838
}
839
840
AudioDriverPulseAudio::AudioDriverPulseAudio() {
841
samples_in.clear();
842
samples_out.clear();
843
}
844
845
#endif // PULSEAUDIO_ENABLED
846
847