forked from libuv/libuv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alsa.cpp
1829 lines (1569 loc) · 67.5 KB
/
alsa.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of libsoundio, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
#include "alsa.hpp"
#include "soundio.hpp"
#include <sys/inotify.h>
#include <math.h>
static snd_pcm_stream_t stream_types[] = {SND_PCM_STREAM_PLAYBACK, SND_PCM_STREAM_CAPTURE};
static snd_pcm_access_t prioritized_access_types[] = {
SND_PCM_ACCESS_MMAP_INTERLEAVED,
SND_PCM_ACCESS_MMAP_NONINTERLEAVED,
SND_PCM_ACCESS_MMAP_COMPLEX,
SND_PCM_ACCESS_RW_INTERLEAVED,
SND_PCM_ACCESS_RW_NONINTERLEAVED,
};
static void wakeup_device_poll(SoundIoAlsa *sia) {
ssize_t amt = write(sia->notify_pipe_fd[1], "a", 1);
if (amt == -1) {
assert(errno != EBADF);
assert(errno != EIO);
assert(errno != ENOSPC);
assert(errno != EPERM);
assert(errno != EPIPE);
}
}
static void destroy_alsa(SoundIoPrivate *si) {
SoundIoAlsa *sia = &si->backend_data.alsa;
if (sia->thread) {
sia->abort_flag.clear();
wakeup_device_poll(sia);
soundio_os_thread_destroy(sia->thread);
}
sia->pending_files.deinit();
if (sia->cond)
soundio_os_cond_destroy(sia->cond);
if (sia->mutex)
soundio_os_mutex_destroy(sia->mutex);
soundio_destroy_devices_info(sia->ready_devices_info);
close(sia->notify_pipe_fd[0]);
close(sia->notify_pipe_fd[1]);
close(sia->notify_fd);
}
static char * str_partition_on_char(char *str, char c) {
while (*str) {
if (*str == c) {
*str = 0;
return str + 1;
}
str += 1;
}
return nullptr;
}
static snd_pcm_stream_t aim_to_stream(SoundIoDeviceAim aim) {
switch (aim) {
case SoundIoDeviceAimOutput: return SND_PCM_STREAM_PLAYBACK;
case SoundIoDeviceAimInput: return SND_PCM_STREAM_CAPTURE;
}
assert(0); // Invalid aim
return SND_PCM_STREAM_PLAYBACK;
}
static SoundIoChannelId from_alsa_chmap_pos(unsigned int pos) {
switch ((snd_pcm_chmap_position)pos) {
case SND_CHMAP_UNKNOWN: return SoundIoChannelIdInvalid;
case SND_CHMAP_NA: return SoundIoChannelIdInvalid;
case SND_CHMAP_MONO: return SoundIoChannelIdFrontCenter;
case SND_CHMAP_FL: return SoundIoChannelIdFrontLeft; // front left
case SND_CHMAP_FR: return SoundIoChannelIdFrontRight; // front right
case SND_CHMAP_RL: return SoundIoChannelIdBackLeft; // rear left
case SND_CHMAP_RR: return SoundIoChannelIdBackRight; // rear right
case SND_CHMAP_FC: return SoundIoChannelIdFrontCenter; // front center
case SND_CHMAP_LFE: return SoundIoChannelIdLfe; // LFE
case SND_CHMAP_SL: return SoundIoChannelIdSideLeft; // side left
case SND_CHMAP_SR: return SoundIoChannelIdSideRight; // side right
case SND_CHMAP_RC: return SoundIoChannelIdBackCenter; // rear center
case SND_CHMAP_FLC: return SoundIoChannelIdFrontLeftCenter; // front left center
case SND_CHMAP_FRC: return SoundIoChannelIdFrontRightCenter; // front right center
case SND_CHMAP_RLC: return SoundIoChannelIdBackLeftCenter; // rear left center
case SND_CHMAP_RRC: return SoundIoChannelIdBackRightCenter; // rear right center
case SND_CHMAP_FLW: return SoundIoChannelIdFrontLeftWide; // front left wide
case SND_CHMAP_FRW: return SoundIoChannelIdFrontRightWide; // front right wide
case SND_CHMAP_FLH: return SoundIoChannelIdFrontLeftHigh; // front left high
case SND_CHMAP_FCH: return SoundIoChannelIdFrontCenterHigh; // front center high
case SND_CHMAP_FRH: return SoundIoChannelIdFrontRightHigh; // front right high
case SND_CHMAP_TC: return SoundIoChannelIdTopCenter; // top center
case SND_CHMAP_TFL: return SoundIoChannelIdTopFrontLeft; // top front left
case SND_CHMAP_TFR: return SoundIoChannelIdTopFrontRight; // top front right
case SND_CHMAP_TFC: return SoundIoChannelIdTopFrontCenter; // top front center
case SND_CHMAP_TRL: return SoundIoChannelIdTopBackLeft; // top rear left
case SND_CHMAP_TRR: return SoundIoChannelIdTopBackRight; // top rear right
case SND_CHMAP_TRC: return SoundIoChannelIdTopBackCenter; // top rear center
case SND_CHMAP_TFLC: return SoundIoChannelIdTopFrontLeftCenter; // top front left center
case SND_CHMAP_TFRC: return SoundIoChannelIdTopFrontRightCenter; // top front right center
case SND_CHMAP_TSL: return SoundIoChannelIdTopSideLeft; // top side left
case SND_CHMAP_TSR: return SoundIoChannelIdTopSideRight; // top side right
case SND_CHMAP_LLFE: return SoundIoChannelIdLeftLfe; // left LFE
case SND_CHMAP_RLFE: return SoundIoChannelIdRightLfe; // right LFE
case SND_CHMAP_BC: return SoundIoChannelIdBottomCenter; // bottom center
case SND_CHMAP_BLC: return SoundIoChannelIdBottomLeftCenter; // bottom left center
case SND_CHMAP_BRC: return SoundIoChannelIdBottomRightCenter; // bottom right center
}
return SoundIoChannelIdInvalid;
}
static int to_alsa_chmap_pos(SoundIoChannelId channel_id) {
switch (channel_id) {
case SoundIoChannelIdFrontLeft: return SND_CHMAP_FL;
case SoundIoChannelIdFrontRight: return SND_CHMAP_FR;
case SoundIoChannelIdBackLeft: return SND_CHMAP_RL;
case SoundIoChannelIdBackRight: return SND_CHMAP_RR;
case SoundIoChannelIdFrontCenter: return SND_CHMAP_FC;
case SoundIoChannelIdLfe: return SND_CHMAP_LFE;
case SoundIoChannelIdSideLeft: return SND_CHMAP_SL;
case SoundIoChannelIdSideRight: return SND_CHMAP_SR;
case SoundIoChannelIdBackCenter: return SND_CHMAP_RC;
case SoundIoChannelIdFrontLeftCenter: return SND_CHMAP_FLC;
case SoundIoChannelIdFrontRightCenter: return SND_CHMAP_FRC;
case SoundIoChannelIdBackLeftCenter: return SND_CHMAP_RLC;
case SoundIoChannelIdBackRightCenter: return SND_CHMAP_RRC;
case SoundIoChannelIdFrontLeftWide: return SND_CHMAP_FLW;
case SoundIoChannelIdFrontRightWide: return SND_CHMAP_FRW;
case SoundIoChannelIdFrontLeftHigh: return SND_CHMAP_FLH;
case SoundIoChannelIdFrontCenterHigh: return SND_CHMAP_FCH;
case SoundIoChannelIdFrontRightHigh: return SND_CHMAP_FRH;
case SoundIoChannelIdTopCenter: return SND_CHMAP_TC;
case SoundIoChannelIdTopFrontLeft: return SND_CHMAP_TFL;
case SoundIoChannelIdTopFrontRight: return SND_CHMAP_TFR;
case SoundIoChannelIdTopFrontCenter: return SND_CHMAP_TFC;
case SoundIoChannelIdTopBackLeft: return SND_CHMAP_TRL;
case SoundIoChannelIdTopBackRight: return SND_CHMAP_TRR;
case SoundIoChannelIdTopBackCenter: return SND_CHMAP_TRC;
case SoundIoChannelIdTopFrontLeftCenter: return SND_CHMAP_TFLC;
case SoundIoChannelIdTopFrontRightCenter: return SND_CHMAP_TFRC;
case SoundIoChannelIdTopSideLeft: return SND_CHMAP_TSL;
case SoundIoChannelIdTopSideRight: return SND_CHMAP_TSR;
case SoundIoChannelIdLeftLfe: return SND_CHMAP_LLFE;
case SoundIoChannelIdRightLfe: return SND_CHMAP_RLFE;
case SoundIoChannelIdBottomCenter: return SND_CHMAP_BC;
case SoundIoChannelIdBottomLeftCenter: return SND_CHMAP_BLC;
case SoundIoChannelIdBottomRightCenter: return SND_CHMAP_BRC;
default:
return SND_CHMAP_UNKNOWN;
}
}
static void get_channel_layout(SoundIoChannelLayout *dest, snd_pcm_chmap_t *chmap) {
int channel_count = min((unsigned int)SOUNDIO_MAX_CHANNELS, chmap->channels);
dest->channel_count = channel_count;
for (int i = 0; i < channel_count; i += 1) {
dest->channels[i] = from_alsa_chmap_pos(chmap->pos[i]);
}
soundio_channel_layout_detect_builtin(dest);
}
static int handle_channel_maps(SoundIoDevice *device, snd_pcm_chmap_query_t **maps) {
if (!maps)
return 0;
snd_pcm_chmap_query_t **p;
snd_pcm_chmap_query_t *v;
// one iteration to count
int layout_count = 0;
for (p = maps; (v = *p) && layout_count < SOUNDIO_MAX_CHANNELS; p += 1, layout_count += 1) { }
device->layouts = allocate<SoundIoChannelLayout>(layout_count);
if (!device->layouts) {
snd_pcm_free_chmaps(maps);
return SoundIoErrorNoMem;
}
device->layout_count = layout_count;
// iterate again to collect data
int layout_index;
for (p = maps, layout_index = 0;
(v = *p) && layout_index < layout_count;
p += 1, layout_index += 1)
{
get_channel_layout(&device->layouts[layout_index], &v->map);
}
snd_pcm_free_chmaps(maps);
return 0;
}
static snd_pcm_format_t to_alsa_fmt(SoundIoFormat fmt) {
switch (fmt) {
case SoundIoFormatS8: return SND_PCM_FORMAT_S8;
case SoundIoFormatU8: return SND_PCM_FORMAT_U8;
case SoundIoFormatS16LE: return SND_PCM_FORMAT_S16_LE;
case SoundIoFormatS16BE: return SND_PCM_FORMAT_S16_BE;
case SoundIoFormatU16LE: return SND_PCM_FORMAT_U16_LE;
case SoundIoFormatU16BE: return SND_PCM_FORMAT_U16_BE;
case SoundIoFormatS24LE: return SND_PCM_FORMAT_S24_LE;
case SoundIoFormatS24BE: return SND_PCM_FORMAT_S24_BE;
case SoundIoFormatU24LE: return SND_PCM_FORMAT_U24_LE;
case SoundIoFormatU24BE: return SND_PCM_FORMAT_U24_BE;
case SoundIoFormatS32LE: return SND_PCM_FORMAT_S32_LE;
case SoundIoFormatS32BE: return SND_PCM_FORMAT_S32_BE;
case SoundIoFormatU32LE: return SND_PCM_FORMAT_U32_LE;
case SoundIoFormatU32BE: return SND_PCM_FORMAT_U32_BE;
case SoundIoFormatFloat32LE: return SND_PCM_FORMAT_FLOAT_LE;
case SoundIoFormatFloat32BE: return SND_PCM_FORMAT_FLOAT_BE;
case SoundIoFormatFloat64LE: return SND_PCM_FORMAT_FLOAT64_LE;
case SoundIoFormatFloat64BE: return SND_PCM_FORMAT_FLOAT64_BE;
case SoundIoFormatInvalid:
return SND_PCM_FORMAT_UNKNOWN;
}
return SND_PCM_FORMAT_UNKNOWN;
}
static void test_fmt_mask(SoundIoDevice *device, const snd_pcm_format_mask_t *fmt_mask, SoundIoFormat fmt) {
if (snd_pcm_format_mask_test(fmt_mask, to_alsa_fmt(fmt))) {
device->formats[device->format_count] = fmt;
device->format_count += 1;
}
}
static int set_access(snd_pcm_t *handle, snd_pcm_hw_params_t *hwparams, snd_pcm_access_t *out_access) {
for (int i = 0; i < array_length(prioritized_access_types); i += 1) {
snd_pcm_access_t access = prioritized_access_types[i];
int err = snd_pcm_hw_params_set_access(handle, hwparams, access);
if (err >= 0) {
if (out_access)
*out_access = access;
return 0;
}
}
return SoundIoErrorOpeningDevice;
}
// this function does not override device->formats, so if you want it to, deallocate and set it to NULL
static int probe_open_device(SoundIoDevice *device, snd_pcm_t *handle, int resample,
int *out_channels_min, int *out_channels_max)
{
SoundIoDevicePrivate *dev = (SoundIoDevicePrivate *)device;
int err;
snd_pcm_hw_params_t *hwparams;
snd_pcm_hw_params_alloca(&hwparams);
if ((err = snd_pcm_hw_params_any(handle, hwparams)) < 0)
return SoundIoErrorOpeningDevice;
if ((err = snd_pcm_hw_params_set_rate_resample(handle, hwparams, resample)) < 0)
return SoundIoErrorOpeningDevice;
if ((err = set_access(handle, hwparams, nullptr)))
return err;
unsigned int channels_min;
unsigned int channels_max;
if ((err = snd_pcm_hw_params_get_channels_min(hwparams, &channels_min)) < 0)
return SoundIoErrorOpeningDevice;
if ((err = snd_pcm_hw_params_set_channels_last(handle, hwparams, &channels_max)) < 0)
return SoundIoErrorOpeningDevice;
*out_channels_min = channels_min;
*out_channels_max = channels_max;
unsigned int rate_min;
unsigned int rate_max;
if ((err = snd_pcm_hw_params_get_rate_min(hwparams, &rate_min, nullptr)) < 0)
return SoundIoErrorOpeningDevice;
if ((err = snd_pcm_hw_params_set_rate_last(handle, hwparams, &rate_max, nullptr)) < 0)
return SoundIoErrorOpeningDevice;
device->sample_rate_count = 1;
device->sample_rates = &dev->prealloc_sample_rate_range;
device->sample_rates[0].min = rate_min;
device->sample_rates[0].max = rate_max;
double one_over_actual_rate = 1.0 / (double)rate_max;
// Purposefully leave the parameters with the highest rate, highest channel count.
snd_pcm_uframes_t min_frames;
snd_pcm_uframes_t max_frames;
if ((err = snd_pcm_hw_params_get_buffer_size_min(hwparams, &min_frames)) < 0)
return SoundIoErrorOpeningDevice;
if ((err = snd_pcm_hw_params_get_buffer_size_max(hwparams, &max_frames)) < 0)
return SoundIoErrorOpeningDevice;
device->software_latency_min = min_frames * one_over_actual_rate;
device->software_latency_max = max_frames * one_over_actual_rate;
if ((err = snd_pcm_hw_params_set_buffer_size_first(handle, hwparams, &min_frames)) < 0)
return SoundIoErrorOpeningDevice;
snd_pcm_format_mask_t *fmt_mask;
snd_pcm_format_mask_alloca(&fmt_mask);
snd_pcm_format_mask_none(fmt_mask);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S8);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U8);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S16_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S16_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U16_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U16_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S24_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S24_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U24_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U24_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S32_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_S32_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U32_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_U32_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_FLOAT_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_FLOAT_BE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_FLOAT64_LE);
snd_pcm_format_mask_set(fmt_mask, SND_PCM_FORMAT_FLOAT64_BE);
if ((err = snd_pcm_hw_params_set_format_mask(handle, hwparams, fmt_mask)) < 0)
return SoundIoErrorOpeningDevice;
if (!device->formats) {
snd_pcm_hw_params_get_format_mask(hwparams, fmt_mask);
device->formats = allocate<SoundIoFormat>(18);
if (!device->formats)
return SoundIoErrorNoMem;
device->format_count = 0;
test_fmt_mask(device, fmt_mask, SoundIoFormatS8);
test_fmt_mask(device, fmt_mask, SoundIoFormatU8);
test_fmt_mask(device, fmt_mask, SoundIoFormatS16LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatS16BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatU16LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatU16BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatS24LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatS24BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatU24LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatU24BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatS32LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatS32BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatU32LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatU32BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatFloat32LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatFloat32BE);
test_fmt_mask(device, fmt_mask, SoundIoFormatFloat64LE);
test_fmt_mask(device, fmt_mask, SoundIoFormatFloat64BE);
}
return 0;
}
static int probe_device(SoundIoDevice *device, snd_pcm_chmap_query_t **maps) {
int err;
snd_pcm_t *handle;
snd_pcm_stream_t stream = aim_to_stream(device->aim);
if ((err = snd_pcm_open(&handle, device->id, stream, 0)) < 0) {
handle_channel_maps(device, maps);
return SoundIoErrorOpeningDevice;
}
int channels_min, channels_max;
if ((err = probe_open_device(device, handle, 0, &channels_min, &channels_max))) {
handle_channel_maps(device, maps);
snd_pcm_close(handle);
return err;
}
if (!maps) {
maps = snd_pcm_query_chmaps(handle);
if (!maps) {
// device gave us no channel maps. we're forced to conclude that
// the min and max channel counts are correct.
int layout_count = 0;
for (int i = 0; i < soundio_channel_layout_builtin_count(); i += 1) {
const SoundIoChannelLayout *layout = soundio_channel_layout_get_builtin(i);
if (layout->channel_count >= channels_min && layout->channel_count <= channels_max) {
layout_count += 1;
}
}
device->layout_count = layout_count;
device->layouts = allocate<SoundIoChannelLayout>(device->layout_count);
if (!device->layouts) {
snd_pcm_close(handle);
return SoundIoErrorNoMem;
}
int layout_index = 0;
for (int i = 0; i < soundio_channel_layout_builtin_count(); i += 1) {
const SoundIoChannelLayout *layout = soundio_channel_layout_get_builtin(i);
if (layout->channel_count >= channels_min && layout->channel_count <= channels_max) {
device->layouts[layout_index++] = *soundio_channel_layout_get_builtin(i);
}
}
}
}
snd_pcm_chmap_t *chmap = snd_pcm_get_chmap(handle);
if (chmap) {
get_channel_layout(&device->current_layout, chmap);
free(chmap);
}
if ((err = handle_channel_maps(device, maps))) {
snd_pcm_close(handle);
return err;
}
maps = nullptr;
if (!device->is_raw) {
if (device->sample_rates[0].min == device->sample_rates[0].max)
device->sample_rate_current = device->sample_rates[0].min;
if (device->software_latency_min == device->software_latency_max)
device->software_latency_current = device->software_latency_min;
// now say that resampling is OK and see what the real min and max is.
if ((err = probe_open_device(device, handle, 1, &channels_min, &channels_max)) < 0) {
snd_pcm_close(handle);
return SoundIoErrorOpeningDevice;
}
}
snd_pcm_close(handle);
return 0;
}
static inline bool str_has_prefix(const char *big_str, const char *prefix) {
return strncmp(big_str, prefix, strlen(prefix)) == 0;
}
static int refresh_devices(SoundIoPrivate *si) {
SoundIo *soundio = &si->pub;
SoundIoAlsa *sia = &si->backend_data.alsa;
int err;
if ((err = snd_config_update_free_global()) < 0)
return SoundIoErrorSystemResources;
if ((err = snd_config_update()) < 0)
return SoundIoErrorSystemResources;
SoundIoDevicesInfo *devices_info = allocate<SoundIoDevicesInfo>(1);
if (!devices_info)
return SoundIoErrorNoMem;
devices_info->default_output_index = -1;
devices_info->default_input_index = -1;
void **hints;
if (snd_device_name_hint(-1, "pcm", &hints) < 0) {
soundio_destroy_devices_info(devices_info);
return SoundIoErrorNoMem;
}
for (void **hint_ptr = hints; *hint_ptr; hint_ptr += 1) {
char *name = snd_device_name_get_hint(*hint_ptr, "NAME");
// null - libsoundio has its own dummy backend. API clients should use
// that instead of alsa null device.
if (strcmp(name, "null") == 0 ||
// sysdefault is confusing - the name and description is identical
// to default, and my best guess for what it does is ignore ~/.asoundrc
// which is just an accident waiting to happen.
str_has_prefix(name, "sysdefault:") ||
// all these surround devices are clutter
str_has_prefix(name, "front:") ||
str_has_prefix(name, "surround21:") ||
str_has_prefix(name, "surround40:") ||
str_has_prefix(name, "surround41:") ||
str_has_prefix(name, "surround50:") ||
str_has_prefix(name, "surround51:") ||
str_has_prefix(name, "surround71:"))
{
free(name);
continue;
}
char *descr = snd_device_name_get_hint(*hint_ptr, "DESC");
char *descr1 = str_partition_on_char(descr, '\n');
char *io = snd_device_name_get_hint(*hint_ptr, "IOID");
bool is_playback;
bool is_capture;
if (io) {
if (strcmp(io, "Input") == 0) {
is_playback = false;
is_capture = true;
} else {
assert(strcmp(io, "Output") == 0);
is_playback = true;
is_capture = false;
}
free(io);
} else {
is_playback = true;
is_capture = true;
}
for (int stream_type_i = 0; stream_type_i < array_length(stream_types); stream_type_i += 1) {
snd_pcm_stream_t stream = stream_types[stream_type_i];
if (stream == SND_PCM_STREAM_PLAYBACK && !is_playback) continue;
if (stream == SND_PCM_STREAM_CAPTURE && !is_capture) continue;
if (stream == SND_PCM_STREAM_CAPTURE && descr1 &&
(strstr(descr1, "Output") || strstr(descr1, "output")))
{
continue;
}
SoundIoDevicePrivate *dev = allocate<SoundIoDevicePrivate>(1);
if (!dev) {
free(name);
free(descr);
soundio_destroy_devices_info(devices_info);
snd_device_name_free_hint(hints);
return SoundIoErrorNoMem;
}
SoundIoDevice *device = &dev->pub;
device->ref_count = 1;
device->soundio = soundio;
device->is_raw = false;
device->id = strdup(name);
device->name = descr1 ?
soundio_alloc_sprintf(nullptr, "%s: %s", descr, descr1) : strdup(descr);
if (!device->id || !device->name) {
soundio_device_unref(device);
free(name);
free(descr);
soundio_destroy_devices_info(devices_info);
snd_device_name_free_hint(hints);
return SoundIoErrorNoMem;
}
SoundIoList<SoundIoDevice *> *device_list;
bool is_default = str_has_prefix(name, "default:") || strcmp(name, "default") == 0;
if (stream == SND_PCM_STREAM_PLAYBACK) {
device->aim = SoundIoDeviceAimOutput;
device_list = &devices_info->output_devices;
if (devices_info->default_output_index < 0 && is_default)
devices_info->default_output_index = device_list->length;
} else {
assert(stream == SND_PCM_STREAM_CAPTURE);
device->aim = SoundIoDeviceAimInput;
device_list = &devices_info->input_devices;
if (devices_info->default_input_index < 0 && is_default)
devices_info->default_input_index = device_list->length;
}
device->probe_error = probe_device(device, nullptr);
if (device_list->append(device)) {
soundio_device_unref(device);
free(name);
free(descr);
soundio_destroy_devices_info(devices_info);
snd_device_name_free_hint(hints);
return SoundIoErrorNoMem;
}
}
free(name);
free(descr);
}
snd_device_name_free_hint(hints);
int card_index = -1;
if (snd_card_next(&card_index) < 0)
return SoundIoErrorSystemResources;
snd_ctl_card_info_t *card_info;
snd_ctl_card_info_alloca(&card_info);
snd_pcm_info_t *pcm_info;
snd_pcm_info_alloca(&pcm_info);
while (card_index >= 0) {
int err;
snd_ctl_t *handle;
char name[32];
sprintf(name, "hw:%d", card_index);
if ((err = snd_ctl_open(&handle, name, 0)) < 0) {
if (err == -ENOENT) {
break;
} else {
soundio_destroy_devices_info(devices_info);
return SoundIoErrorOpeningDevice;
}
}
if ((err = snd_ctl_card_info(handle, card_info)) < 0) {
snd_ctl_close(handle);
soundio_destroy_devices_info(devices_info);
return SoundIoErrorSystemResources;
}
const char *card_name = snd_ctl_card_info_get_name(card_info);
int device_index = -1;
for (;;) {
if (snd_ctl_pcm_next_device(handle, &device_index) < 0) {
snd_ctl_close(handle);
soundio_destroy_devices_info(devices_info);
return SoundIoErrorSystemResources;
}
if (device_index < 0)
break;
snd_pcm_info_set_device(pcm_info, device_index);
snd_pcm_info_set_subdevice(pcm_info, 0);
for (int stream_type_i = 0; stream_type_i < array_length(stream_types); stream_type_i += 1) {
snd_pcm_stream_t stream = stream_types[stream_type_i];
snd_pcm_info_set_stream(pcm_info, stream);
if ((err = snd_ctl_pcm_info(handle, pcm_info)) < 0) {
if (err == -ENOENT) {
continue;
} else {
snd_ctl_close(handle);
soundio_destroy_devices_info(devices_info);
return SoundIoErrorSystemResources;
}
}
const char *device_name = snd_pcm_info_get_name(pcm_info);
SoundIoDevicePrivate *dev = allocate<SoundIoDevicePrivate>(1);
if (!dev) {
snd_ctl_close(handle);
soundio_destroy_devices_info(devices_info);
return SoundIoErrorNoMem;
}
SoundIoDevice *device = &dev->pub;
device->ref_count = 1;
device->soundio = soundio;
device->id = soundio_alloc_sprintf(nullptr, "hw:%d,%d", card_index, device_index);
device->name = soundio_alloc_sprintf(nullptr, "%s %s", card_name, device_name);
device->is_raw = true;
if (!device->id || !device->name) {
soundio_device_unref(device);
snd_ctl_close(handle);
soundio_destroy_devices_info(devices_info);
return SoundIoErrorNoMem;
}
SoundIoList<SoundIoDevice *> *device_list;
if (stream == SND_PCM_STREAM_PLAYBACK) {
device->aim = SoundIoDeviceAimOutput;
device_list = &devices_info->output_devices;
} else {
assert(stream == SND_PCM_STREAM_CAPTURE);
device->aim = SoundIoDeviceAimInput;
device_list = &devices_info->input_devices;
}
snd_pcm_chmap_query_t **maps = snd_pcm_query_chmaps_from_hw(card_index, device_index, -1, stream);
device->probe_error = probe_device(device, maps);
if (device_list->append(device)) {
soundio_device_unref(device);
soundio_destroy_devices_info(devices_info);
return SoundIoErrorNoMem;
}
}
}
snd_ctl_close(handle);
if (snd_card_next(&card_index) < 0) {
soundio_destroy_devices_info(devices_info);
return SoundIoErrorSystemResources;
}
}
soundio_os_mutex_lock(sia->mutex);
soundio_destroy_devices_info(sia->ready_devices_info);
sia->ready_devices_info = devices_info;
sia->have_devices_flag = true;
soundio_os_cond_signal(sia->cond, sia->mutex);
soundio->on_events_signal(soundio);
soundio_os_mutex_unlock(sia->mutex);
return 0;
}
static void shutdown_backend(SoundIoPrivate *si, int err) {
SoundIo *soundio = &si->pub;
SoundIoAlsa *sia = &si->backend_data.alsa;
soundio_os_mutex_lock(sia->mutex);
sia->shutdown_err = err;
soundio_os_cond_signal(sia->cond, sia->mutex);
soundio->on_events_signal(soundio);
soundio_os_mutex_unlock(sia->mutex);
}
static bool copy_str(char *dest, const char *src, int buf_len) {
for (;;) {
buf_len -= 1;
if (buf_len <= 0)
return false;
*dest = *src;
dest += 1;
src += 1;
if (!*src)
break;
}
*dest = '\0';
return true;
}
static void device_thread_run(void *arg) {
SoundIoPrivate *si = (SoundIoPrivate *)arg;
SoundIoAlsa *sia = &si->backend_data.alsa;
// Some systems cannot read integer variables if they are not
// properly aligned. On other systems, incorrect alignment may
// decrease performance. Hence, the buffer used for reading from
// the inotify file descriptor should have the same alignment as
// struct inotify_event.
char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
const struct inotify_event *event;
struct pollfd fds[2];
fds[0].fd = sia->notify_fd;
fds[0].events = POLLIN;
fds[1].fd = sia->notify_pipe_fd[0];
fds[1].events = POLLIN;
int err;
for (;;) {
int poll_num = poll(fds, 2, -1);
if (!sia->abort_flag.test_and_set())
break;
if (poll_num == -1) {
if (errno == EINTR)
continue;
assert(errno != EFAULT);
assert(errno != EFAULT);
assert(errno != EINVAL);
assert(errno == ENOMEM);
// Kernel ran out of polling memory.
shutdown_backend(si, SoundIoErrorSystemResources);
return;
}
if (poll_num <= 0)
continue;
bool got_rescan_event = false;
if (fds[0].revents & POLLIN) {
for (;;) {
ssize_t len = read(sia->notify_fd, buf, sizeof(buf));
if (len == -1) {
assert(errno != EBADF);
assert(errno != EFAULT);
assert(errno != EINVAL);
assert(errno != EIO);
assert(errno != EISDIR);
if (errno == EBADF || errno == EFAULT || errno == EINVAL ||
errno == EIO || errno == EISDIR)
{
shutdown_backend(si, SoundIoErrorSystemResources);
return;
}
}
// catches EINTR and EAGAIN
if (len <= 0)
break;
// loop over all events in the buffer
for (char *ptr = buf; ptr < buf + len; ptr += sizeof(struct inotify_event) + event->len) {
event = (const struct inotify_event *) ptr;
if (!((event->mask & IN_CLOSE_WRITE) || (event->mask & IN_DELETE) || (event->mask & IN_CREATE)))
continue;
if (event->mask & IN_ISDIR)
continue;
if (!event->len || event->len < 8)
continue;
if (strncmp(event->name, "controlC", 8) != 0) {
continue;
}
if (event->mask & IN_CREATE) {
if ((err = sia->pending_files.add_one())) {
shutdown_backend(si, SoundIoErrorNoMem);
return;
}
SoundIoAlsaPendingFile *pending_file = &sia->pending_files.last();
if (!copy_str(pending_file->name, event->name, SOUNDIO_MAX_ALSA_SND_FILE_LEN)) {
sia->pending_files.pop();
}
continue;
}
if (sia->pending_files.length > 0) {
// At this point ignore IN_DELETE in favor of waiting until the files
// opened with IN_CREATE have their IN_CLOSE_WRITE event.
if (!(event->mask & IN_CLOSE_WRITE))
continue;
for (int i = 0; i < sia->pending_files.length; i += 1) {
SoundIoAlsaPendingFile *pending_file = &sia->pending_files.at(i);
if (strcmp(pending_file->name, event->name) == 0) {
sia->pending_files.swap_remove(i);
if (sia->pending_files.length == 0) {
got_rescan_event = true;
}
break;
}
}
} else if (event->mask & IN_DELETE) {
// We are not waiting on created files to be closed, so when
// a delete happens we act on it.
got_rescan_event = true;
}
}
}
}
if (fds[1].revents & POLLIN) {
got_rescan_event = true;
for (;;) {
ssize_t len = read(sia->notify_pipe_fd[0], buf, sizeof(buf));
if (len == -1) {
assert(errno != EBADF);
assert(errno != EFAULT);
assert(errno != EINVAL);
assert(errno != EIO);
assert(errno != EISDIR);
if (errno == EBADF || errno == EFAULT || errno == EINVAL ||
errno == EIO || errno == EISDIR)
{
shutdown_backend(si, SoundIoErrorSystemResources);
return;
}
}
if (len <= 0)
break;
}
}
if (got_rescan_event) {
if ((err = refresh_devices(si))) {
shutdown_backend(si, err);
return;
}
}
}
}
static void my_flush_events(SoundIoPrivate *si, bool wait) {
SoundIo *soundio = &si->pub;
SoundIoAlsa *sia = &si->backend_data.alsa;
bool change = false;
bool cb_shutdown = false;
SoundIoDevicesInfo *old_devices_info = nullptr;
soundio_os_mutex_lock(sia->mutex);
// block until have devices
while (wait || (!sia->have_devices_flag && !sia->shutdown_err)) {
soundio_os_cond_wait(sia->cond, sia->mutex);
wait = false;
}
if (sia->shutdown_err && !sia->emitted_shutdown_cb) {
sia->emitted_shutdown_cb = true;
cb_shutdown = true;
} else if (sia->ready_devices_info) {
old_devices_info = si->safe_devices_info;
si->safe_devices_info = sia->ready_devices_info;
sia->ready_devices_info = nullptr;
change = true;
}
soundio_os_mutex_unlock(sia->mutex);
if (cb_shutdown)
soundio->on_backend_disconnect(soundio, sia->shutdown_err);
else if (change)
soundio->on_devices_change(soundio);
soundio_destroy_devices_info(old_devices_info);
}
static void flush_events_alsa(SoundIoPrivate *si) {
my_flush_events(si, false);
}
static void wait_events_alsa(SoundIoPrivate *si) {
my_flush_events(si, false);
my_flush_events(si, true);
}
static void wakeup_alsa(SoundIoPrivate *si) {
SoundIoAlsa *sia = &si->backend_data.alsa;
soundio_os_mutex_lock(sia->mutex);
soundio_os_cond_signal(sia->cond, sia->mutex);
soundio_os_mutex_unlock(sia->mutex);
}
static void force_device_scan_alsa(SoundIoPrivate *si) {
SoundIoAlsa *sia = &si->backend_data.alsa;
wakeup_device_poll(sia);
}
static void outstream_destroy_alsa(SoundIoPrivate *si, SoundIoOutStreamPrivate *os) {
SoundIoOutStreamAlsa *osa = &os->backend_data.alsa;
if (osa->thread) {
osa->thread_exit_flag.clear();
soundio_os_thread_destroy(osa->thread);
}
if (osa->handle)
snd_pcm_close(osa->handle);
free(osa->poll_fds);
free(osa->chmap);
free(osa->sample_buffer);
}
static int outstream_xrun_recovery(SoundIoOutStreamPrivate *os, int err) {
SoundIoOutStream *outstream = &os->pub;
SoundIoOutStreamAlsa *osa = &os->backend_data.alsa;
if (err == -EPIPE) {
err = snd_pcm_prepare(osa->handle);
if (err >= 0)
outstream->underflow_callback(outstream);
} else if (err == -ESTRPIPE) {
while ((err = snd_pcm_resume(osa->handle)) == -EAGAIN) {
// wait until suspend flag is released
poll(nullptr, 0, 1);
}
if (err < 0)
err = snd_pcm_prepare(osa->handle);
if (err >= 0)
outstream->underflow_callback(outstream);
}
return err;
}
static int instream_xrun_recovery(SoundIoInStreamPrivate *is, int err) {
SoundIoInStream *instream = &is->pub;
SoundIoInStreamAlsa *isa = &is->backend_data.alsa;
if (err == -EPIPE) {
err = snd_pcm_prepare(isa->handle);
if (err >= 0)
instream->overflow_callback(instream);
} else if (err == -ESTRPIPE) {
while ((err = snd_pcm_resume(isa->handle)) == -EAGAIN) {
// wait until suspend flag is released
poll(nullptr, 0, 1);
}
if (err < 0)
err = snd_pcm_prepare(isa->handle);
if (err >= 0)
instream->overflow_callback(instream);
}
return err;
}
static int outstream_wait_for_poll(SoundIoOutStreamPrivate *os) {
SoundIoOutStreamAlsa *osa = &os->backend_data.alsa;
int err;
unsigned short revents;
for (;;) {
if ((err = poll(osa->poll_fds, osa->poll_fd_count, -1)) < 0) {
return err;
}
if ((err = snd_pcm_poll_descriptors_revents(osa->handle,
osa->poll_fds, osa->poll_fd_count, &revents)) < 0)
{
return err;
}
if (revents & (POLLERR|POLLNVAL|POLLHUP)) {
return 0;
}
if (revents & POLLOUT)
return 0;
}
}
static int instream_wait_for_poll(SoundIoInStreamPrivate *is) {
SoundIoInStreamAlsa *isa = &is->backend_data.alsa;
int err;