This repository has been archived by the owner on Jun 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
alsa-capabilities
executable file
·1475 lines (1411 loc) · 50 KB
/
alsa-capabilities
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
#!/usr/bin/env bash
# shellcheck disable=SC2191
## ^^ we frequently use arrays for passing arguments to functions.
## This script for linux with bash 4.x displays a list with the audio
## capabilities of each alsa audio output interface and stores them in
## arrays for use in other scripts. This functionality is exposed by
## the `return_alsa_interface' function which is avaliable after
## sourcing the file. When ran from a shell, it will call that
## function.
##
## Copyright (C) 2014 Ronald van Engelen <ronalde+github@lacocina.nl>
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Source: https://github.com/ronalde/mpd-configure
## See also: https://lacocina.nl/detect-alsa-output-capabilities
LANG=C
APP_NAME_AC="alsa-capabilities"
APP_VERSION="0.9.5"
APP_INFO_URL="https://lacocina.nl/detect-alsa-output-capabilities"
## set DEBUG to a non empty value to display internal program flow to
## stderr
DEBUG="${DEBUG:-}"
## set PROFILE to a non empty value to get detailed timing
## information. Normal output is suppressed.
PROFILE="${PROFILE:-}"
## to see how the script behaves with a certain output of aplay -l
## on a particular host, store it's output in a file and supply
## the file path as the value of TESTFILE, eg:
## `TESTFILE=/tmp/somefile ./bash-capabilities
## All hardware and device tests will fail or produce fake outputs
## (hopefully with some grace).
TESTFILE="${TESTFILE:-}"
### generic functions
function die() {
printf 1>&2 "\nError:\n%s\n\n" "$@"
exit 1
}
function debug() {
lineno="$1"
message="$2"
printf 1>&2 "=%.0s" {1..100}
printf 1>&2 "\nDEBUG *** %s (%4d): %s\n" \
"${APP_NAME_AC}" \
"${lineno}" \
"${message}"
}
function command_not_found() {
## give installation instructions for package $2 when command $1
## is not available, optional with non default instructions $3
## and exit with error
command="$1"
package="$2"
instructions="${3:-}"
msg="command \`${command}' (package \`${package}') not found. "
if [[ -z "${instructions}" ]]; then
msg+="See 'Requirements' on ${APP_INFO_URL}."
else
msg+="${instructions}"
fi
die "${msg}"
}
### alsa related functions
function get_aplay_output() {
## use aplay to do a basic alsa sanity check using aplay -l, or
## optionally using $TESTFILE containing the stored output of
## 'aplay -l'.
## returns the raw output of aplay or an error.
res=""
aplay_msg_nosoundcards_regexp="no[[:space:]]soundcards"
if [[ "${TESTFILE}x" != "x" ]]; then
if [[ ! -f "${TESTFILE}" ]]; then
# shellcheck disable=SC2059
printf 1>&2 "${MSG_APLAY_ERROR_NOSUCHTESTFILE}" \
"${TESTFILE}"
return 1
else
## get the output from a file for testing purposes
# shellcheck disable=SC2059
printf 1>&2 "${MSG_APLAY_USINGTESTFILE}\n" \
"${TESTFILE}"
# shellcheck disable=SC2059
res="$(< "${TESTFILE}")" || \
( printf "${MSG_APLAY_ERROR_OPENINGTESTFILE}" && \
return 1 )
fi
else
## run aplay -l to check for alsa errors or display audio cards
res="$(${CMD_APLAY} -l 2>&1)" || \
(
# shellcheck disable=SC2059
printf "${MSG_APLAY_ERROR_GENERAL}\n" "${res}"
## TODO: react on specific aplay error
[[ ${DEBUG} ]] && debug "${LINENO}" "\`${CMD_APLAY} -l' returned error: \`${res}'"
return 1
)
## check for no soundcards
if [[ "${res}" =~ ${aplay_msg_nosoundcards_regexp} ]]; then
printf "%s\n" "${MSG_APLAY_ERROR_NOSOUNDCARDS}"
## TODO: react on specific aplay error
[[ ${DEBUG} ]] && debug "${LINENO}" "\`${CMD_APLAY} -l' returned no cards: \`${res}'"
return 1
fi
fi
## return the result to the calling function
printf "%s" "${res}"
}
function handle_doublebrackets() {
## return the name of the alsa card / device, even when they
## contain brackets.
string="$*"
bracketcounter=0
for (( i=0; i<${#string}; i++ )); do
char="${string:$i:1}"
if [[ "${char}" = "[" ]]; then
(( bracketcounter++ ))
elif [[ "${char}" = "]" ]]; then
(( bracketcounter-- ))
fi
if (( bracketcounter > 0 )); then
## inside outer brackets
if (( bracketcounter < 2 )) && [[ "${char}" == "[" ]]; then
[[ ${DEBUG} ]] && \
debug "${LINENO}" "name with brackets found."
else
# shellcheck disable=SC2059
printf "${char}"
fi
fi
done
}
function return_output_human() {
## print default output to std_err.
## called by fetch_alsa_outputinterfaces.
printf "%s\n" "${alsa_if_display_title}" 1>&2;
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_DEVNAME}" \
"${alsa_dev_label}" 1>&2;
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_IFNAME}" "${alsa_if_label}" 1>&2;
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_UACCLASS}" "${alsa_if_uacclass}" 1>&2;
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_CHARDEV}" "${alsa_if_chardev}" 1>&2;
if [[ ! -z ${formats_res_err} ]]; then
## device is locked by an unspecified process
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_ENCODINGFORMATS}" \
"${MSG_ERROR_GETTINGFORMATS}" 1>&2;
printf " %-17s %-60s\n" \
" " \
"${formats_res[@]}" 1>&2;
else
formatcounter=0
if [[ ! -z ${OPT_SAMPLERATES} ]]; then
MSG_ALSA_ENCODINGFORMATS="samplerates (Hz)"
fi
printf " - %-17s = " \
"${MSG_ALSA_ENCODINGFORMATS}" 1>&2;
# shellcheck disable=SC2141
while IFS="\n" read -r line; do
(( formatcounter++ ))
if (( formatcounter > 1 )); then
printf "%-23s" " " 1>&2;
fi
printf "%-60s\n" "${line}" 1>&2;
done<<<"${alsa_if_formats[@]}"
fi
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_MONITORFILE}" "${alsa_if_monitorfile}" 1>&2;
printf " - %-17s = %-60s\n" \
"${MSG_ALSA_STREAMFILE}" "${alsa_if_streamfile}" 1>&2;
printf "\n"
}
function key_val_to_json() {
## returns a json "key": "val" pair.
key="$1"
val="$2"
## check if val is a number
if printf -v numval "%d" "${val}" 2>/dev/null; then
## it is
printf '"%s": %d' \
"${key}" "${numval}"
else
printf '"%s": "%s"' \
"${key}" "${val}"
fi
printf "\n"
}
function ret_json_format() {
## returns the json formatted encoding format and possibly sample
## rates.
formats_raw="$1"
declare -a json_formats
if [[ "${formats_raw}" =~ ':' ]]; then
## sample rates included
while read -r line; do
split_re="(.*):(.*)"
if [[ "${line}" =~ ${split_re} ]]; then
format=${BASH_REMATCH[1]}
IFS=" " samplerates=(${BASH_REMATCH[2]})
printf -v sr_out "\t\t\"%s\",\n" \
"${samplerates[@]}"
sr_out="${sr_out%,*}"
label_samplerates='"samplerates"'
output_line="{
$(key_val_to_json format "${format// /}"),
${label_samplerates}: [
${sr_out}
]
},"
output_lines+=("${output_line}")
fi
done<<<"${formats_raw}"
printf -v json_formats "\t%s\n" "${output_lines[@]}"
## strip the continuation comma from the last element
json_formats="${json_formats%,*}"
else
## no sample rates included
IFS="," formats_res=(${formats_raw})
printf -v json_formats '\t\t"%s",\n' \
"${formats_res[@]// /}"
## strip the continuation comma from the last element
json_formats="${json_formats%,*}"
fi
printf "%s" "${json_formats}"
}
function ret_json_card() {
## print json formatted output to std_out.
## called by fetch_alsa_outputinterfaces.
#cur_aif_no="$1"
local str_formats_res="$1"
last_aif="$2"
printf -v encoding_formats_val "[\n %s\n\t]" \
"$(ret_json_format "${str_formats_res}")"
## using to indexed arrays in order to preserve order of fields
declare -a json_keyvals
json_fields=(
id
hwaddr
description
cardnumber
interfacenumber
cardname
interfacename
chardev
monitorfile
streamfile
usbaudioclass
)
json_values=(${cur_aif_no})
json_values+=(${alsa_if_hwaddress})
#a_json_keyvals[description]=
json_values+=("${alsa_if_title_label}")
#a_json_keyvals[cardnumber]=
json_values+=(${alsa_dev_nr})
#a_json_keyvals[interfacenumber]=
json_values+=(${alsa_if_nr})
#a_json_keyvals[cardname]=
json_values+=("${alsa_dev_label}")
#a_json_keyvals[interfacename]=
json_values+=("${alsa_if_label}")
#a_json_keyvals[chardev]=
json_values+=(${alsa_if_chardev})
#a_json_keyvals[monitorfile]=
json_values+=(${alsa_if_monitorfile})
#a_json_keyvals[streamfile]=
json_values+=(${alsa_if_streamfile})
#a_json_keyvals[usbaudioclass]=
json_values+=("${alsa_if_uacclass}")
for json_fieldno in "${!json_fields[@]}"; do
json_keyvals+=("$(key_val_to_json \
"${json_fields[${json_fieldno}]}" "${json_values[${json_fieldno}]}")")
done
printf -v str_json_keyvals "\t%s,\n" "${json_keyvals[@]}"
# shellcheck disable=SC1078,SC1079,SC2027
aif_json="""\
{
${str_json_keyvals%,*}
\"encodingformats\": "${encoding_formats_val}"
}\
"""
printf "%s" "${aif_json}"
if [[ "${last_aif}x" == "x" ]]; then
printf ","
fi
printf "\n"
}
function return_output_json() {
## print json formatted output to std_out.
## called by fetch_alsa_outputinterfaces.
json_cards="$1"
json='{
"alsa_outputdevices": [
%s
]
}'
# shellcheck disable=SC2059
printf "${json}\n" "${json_cards%,*}"
}
function fetch_alsa_outputinterfaces() {
## parses each output interface returned by `get_aplay_output'
## after filtering (when the appropriate commandline options are
## given), stores its capabilities in the appropriate global
## indexed arrays and displays them.
json_output=
msg=()
aplay_lines=()
integer_regexp='^[0-9]+$'
aplay_card_regexp="^card[[:space:]][0-9]+:"
## exit on error
#aplay_output="$
## reset the counter for interfaces without filtering
NR_AIFS_BEFOREFILTERING=0
## modify the filter for aplay -l when OPT_HWFILTER is set
if [[ ! -z "${OPT_HWFILTER}" ]]; then
# the portion without `hw:', eg 0,1
alsa_filtered_hwaddr="${OPT_HWFILTER#hw:*}"
alsa_filtered_cardnr="${alsa_filtered_hwaddr%%,*}"
alsa_filtered_devicenr="${alsa_filtered_hwaddr##*,}"
if [[ ! ${alsa_filtered_cardnr} =~ ${integer_regexp} ]] || \
[[ ! ${alsa_filtered_devicenr} =~ ${integer_regexp} ]]; then
msg+=("Invalid OPT_HWFILTER (\`${OPT_HWFILTER}') specified.")
msg+=("Should be \`hw:x,y' were x and y are both integers.")
printf -v msg_str "%s\n" "${msg[@]}"
die "${msg_str}"
fi
aplay_card_regexp="^card[[:space:]]${alsa_filtered_cardnr}:[[:space:]].*"
aplay_device_regexp="[[:space:]]device[[:space:]]${alsa_filtered_devicenr}:"
aplay_card_device_regexp="${aplay_card_regexp}${aplay_device_regexp}"
else
aplay_card_device_regexp="${aplay_card_regexp}"
fi
## iterate each line of aplay output
while read -r line ; do
## filter for `^card' and then for `OPT_CUSTOMFILTER' to get matching
## lines from aplay and store them in an array
if [[ "${line}" =~ ${aplay_card_device_regexp} ]]; then
[[ ${DEBUG} ]] && \
( msg_debug="aplay -l output line: \`${line}'. with OPT_CUSTOMFILTER: ${OPT_CUSTOMFILTER}"
debug "${LINENO}" "${msg_debug}")
## raise the counter for interfaces without filtering
((NR_AIFS_BEFOREFILTERING++))
if [[ "${OPT_CUSTOMFILTER}x" != "x" ]]; then
## check if line matches `OPT_CUSTOMFILTER'
if [[ "${line}" =~ ${OPT_CUSTOMFILTER} ]]; then
[[ ${DEBUG} ]] && \
debug "${LINENO}" "match: ${line}"
## store the line in an array
aplay_lines+=("${line}")
else
[[ ${DEBUG} ]] && \
debug "${LINENO}" "no match with filter ${OPT_CUSTOMFILTER}: ${line}"
fi
else
## store the line in an array
aplay_lines+=("${line}")
fi
fi
done< <(get_aplay_output "${aplay_card_regexp}") || \
die "get_aplay_output '${aplay_card_regexp}' returned an error."
#< "${aplay_output}"
## check whether soundcards were found
NR_AIFS_AFTERFILTERING=${#aplay_lines[@]}
if (( NR_AIFS_AFTERFILTERING < 1 )); then
die "${#aplay_lines[@]} soundcards found"
fi
## loop through each item in the array
cur_aif_no=0
for line in "${aplay_lines[@]}"; do
((cur_aif_no++))
## set if type to default (ie analog)
alsa_if_type="ao"
## construct bash regexp for sound device
## based on aplay.c:
## printf(_("card %i: %s [%s], device %i: %s [%s]\n"),
## 1 card,
## 2 snd_ctl_card_info_get_id(info),
## 3 snd_ctl_card_info_get_name(info),
## 4 dev,
## 5 snd_pcm_info_get_id(pcminfo),
## 6 snd_pcm_info_get_name(pcminfo));
##
## portion (ie before `,')
## caution: snd_{pcm,ctl}_card_info_get_name(info) could
## return an empty string between square brackets, while
## string returned by snd_{pcm,ctl}_card_info_get_id may
## contain square brackets
alsa_regexp_common="[[:space:]]([0-9]+):[[:space:]](.*)\]"
alsa_dev_regexp="card${alsa_regexp_common}"
alsa_if_regexp="device${alsa_regexp_common}"
## same for interface portion
alsa_dev_if_regexp="^${alsa_dev_regexp},[[:space:]]${alsa_if_regexp}$"
## unset / empty out all variables
alsa_dev_nr=""
alsa_dev_label=""
alsa_if_nr=""
alsa_if_name=""
alsa_if_label=""
before_bracket_re="^([^[]+)\["
if [[ "${line}" =~ ${alsa_dev_if_regexp} ]]; then
alsa_dev_nr="${BASH_REMATCH[1]}"
alsa_dev_name_raw="${BASH_REMATCH[2]}"
alsa_if_nr="${BASH_REMATCH[3]}"
alsa_if_name_raw="${BASH_REMATCH[4]}"
if [[ "${alsa_dev_name_raw}" =~ ${before_bracket_re} ]]; then
alsa_dev_name_beforebracket="${BASH_REMATCH[1]}"
alsa_dev_name_betweenbrackets="${alsa_dev_name_raw//${alsa_dev_name_beforebracket}}"
if [[ ${DEBUG} ]]; then
debug "${LINENO}" "#####: alsa_dev_name_beforebracket \`${alsa_dev_name_beforebracket}'"
debug "${LINENO}" "#####: alsa_dev_name_betweenbrackets \`${alsa_dev_name_betweenbrackets}'"
fi
else
printf -v msg_err "%s: alsa_dev_name_raw \`%s' did not match regexp before_bracket_re (\`%s')\n" \
"${LINENO}" "${alsa_dev_name_raw}" "${before_bracket_re}"
die "${msg_err}"
break
fi
if [[ "${alsa_if_name_raw}" =~ ${before_bracket_re} ]]; then
alsa_if_name_beforebracket="${BASH_REMATCH[1]}"
alsa_if_name_betweenbrackets="${alsa_if_name_raw//${alsa_if_name_beforebracket}}"
if [[ ${DEBUG} ]]; then
debug "${LINENO}" "#####: alsa_if_name_beforebracket \`${alsa_if_name_beforebracket}'"
debug "${LINENO}" "#####: alsa_if_name_betweenbrackets \`${alsa_if_name_betweenbrackets}'"
fi
else
printf -v msg_err "%s: alsa_if_name_raw \`%s' did not match regexp before_bracket_re (\`%s')\n" \
"${LINENO}" "${alsa_if_name_raw}" "${before_bracket_re}"
die "${msg_err}"
break
fi
else
printf -v msg_err "%s: aplay line did not match alsa_dev_if_regexp (\`%s'):\n%s\n" \
"${LINENO}" "${alsa_dev_if_regexp}" "${line}"
die "${msg_err}"
break
fi
## format the names
## alsa_{dev,if}_name_beforebracket includes trailing space
## alsa_{dev,if}_name_betweenbrackets includes leading square bracket
## strip both
## courtesy: https://unix.stackexchange.com/a/360648
shopt -s extglob
alsa_dev_name_beforebracket="${alsa_dev_name_beforebracket%%+([[:space:]])}"
alsa_dev_name_betweenbrackets="${alsa_dev_name_beforebracket##+([)}"
alsa_if_name_beforebracket="${alsa_if_name_beforebracket%%+([[:space:]])}"
alsa_if_name_betweenbrackets="${alsa_if_name_beforebracket##+([)}"
shopt -u extglob
## do not include identical or empty name between square brackets
if [[ "${alsa_dev_name_beforebracket}x" == "${alsa_dev_name_betweenbrackets}x" ]] || \
[[ "${alsa_dev_name_betweenbrackets}x" == "x" ]]; then
alsa_dev_label="${alsa_dev_name_beforebracket}"
else
alsa_dev_label="${alsa_dev_name_beforebracket} [${alsa_dev_name_betweenbrackets}]"
fi
if [[ "${alsa_if_name_beforebracket}x" == "${alsa_if_name_betweenbrackets}x" ]] || \
[[ "${alsa_if_name_betweenbrackets}x" == "x" ]]; then
alsa_if_label="${alsa_if_name_beforebracket}"
else
alsa_if_label="${alsa_if_name_beforebracket} [${alsa_if_name_betweenbrackets}]"
fi
declare -a alsa_if_formats=()
alsa_if_hwaddress="hw:${alsa_dev_nr},${alsa_if_nr}"
## construct the path to the character device for the
## interface (ie `/dev/snd/xxx')
alsa_if_chardev="/dev/snd/pcmC${alsa_dev_nr}D${alsa_if_nr}p"
## construct the path to the hwparams file
alsa_if_hwparamsfile="/proc/asound/card${alsa_dev_nr}/pcm${alsa_if_nr}p/sub0/hw_params"
## before determining whether this is a usb device, assume
## the monitor file is the hwparams file
alsa_if_monitorfile="${alsa_if_hwparamsfile}"
## assume stream file for the interface (ie
## `/proc/asound/cardX/streamY') to determine whether
## the interface is a uac device, and if so, which class it is
alsa_if_streamfile="/proc/asound/card${alsa_dev_nr}/stream${alsa_if_nr}"
## assume no uac device
alsa_if_uacclass="${MSG_PROP_NOTAPPLICABLE}"
if [[ ! -z ${TESTFILE} ]]; then
## device is not real
alsa_if_formats+=("(${MSG_ERROR_CHARDEV_NOFORMATS})")
alsa_if_uacclass_nr="?"
else
## check if the hwparams file exists
if [[ ! -f "${alsa_if_hwparamsfile}" ]]; then
alsa_if_hwparamsfile="${alsa_if_hwparamsfile} (error: not accessible)"
fi
## check if the chardev exists
if [[ ! -c "${alsa_if_chardev}" ]]; then
msg_err="alsa_if_chardev \`${alsa_if_chardev}': ${MSG_ERROR_NOT_CHARDEV} "
[[ ${DEBUG} ]] && \
debug "${LINENO}" "${msg_err}"
alsa_if_chardev="${alsa_if_chardev} (${MSG_ERROR_NOT_CHARDEV})"
else
[[ ${DEBUG} ]] && \
debug "${LINENO}" "alsa_if_chardev \`${alsa_if_chardev}' is a valid chardev."
fi
## check whether the monitor file exists; it always should
if [[ ! -f ${alsa_if_monitorfile} ]]; then
msg_err="${alsa_if_monitorfile} ${MSG_ERROR_NOFILE} (${MSG_ERROR_UNEXPECTED})"
alsa_if_monitorfile="${msg_err}"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "${msg_err}"
fi
## check whether the streamfile exists; it only should
## exist in the case of a uac interface
if [[ ! -f "${alsa_if_streamfile}" ]]; then
msg_err="${alsa_if_streamfile} ${MSG_ERROR_NOFILE} (${MSG_ERROR_UNEXPECTED})"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "${msg_err}"
## no uac interface
alsa_if_streamfile="${MSG_PROP_NOTAPPLICABLE}"
else
[[ ${DEBUG} ]] && \
debug "${LINENO}" "using alsa_if_streamfile \`${alsa_if_streamfile}'."
## set interface to usb out
alsa_if_type="uo"
## uac devices will use the stream file instead of
## hwparams file to monitor
## alsa_if_monitorfile="${alsa_if_streamfile}"
## get the type of uac endpoint
alsa_if_uac_ep="$(return_alsa_uac_ep "${alsa_if_streamfile}")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
[[ ${DEBUG} ]] && \
debug "${LINENO}" "could not determine alsa_if_uac_ep."
alsa_if_uacclass_nr="?"
else
[[ ${DEBUG} ]] && \
debug "${LINENO}" "alsa_if_uac_ep set to \`${alsa_if_uac_ep}'."
## lookup the uac class in the array for this type of endpoint (EP)
## (for readability)
alsa_if_uacclass="${UO_EP_LABELS[${alsa_if_uac_ep}]}"
## the uac class number (0, 1, 2 or 3) according to ./sound/usb/card.h
alsa_if_uacclass_nr="${alsa_if_uacclass% - *}"
classnr_regexp='^[0-3]+$'
if [[ ! ${alsa_if_uacclass_nr} =~ ${classnr_regexp} ]]; then
[[ ${DEBUG} ]] && \
debug "${LINENO}" "invalid uac class number \`${alsa_if_uacclass_nr}'. \
${MSG_ERROR_UNEXPECTED}"
alsa_if_uacclass_nr="?"
fi
fi
fi
fi
## for non-uac interfaces: check whether it is some other
## digital interface
if [[ ! "${alsa_if_type}" = "uo" ]]; then
for filter in "${DO_INTERFACE_FILTER[@]}"; do
## `,,' downcases the string, while `*var*' does a
## wildcard match
if [[ "${alsa_if_name,,}" == *"${filter}"* ]]; then
[[ ${DEBUG} ]] && \
debug "${LINENO}" "match = ${alsa_if_name,,}: ${filter}"
## set ao type to d(igital)o(out)
alsa_if_type="do"
## exit this for loop
break
fi
done
fi
## see if the interface type matches the user specified
## filters and if so construct titles and store a pair of
## hardware address and monitoring file in the proper array
match=
case "${alsa_if_type}" in
"ao")
## only if neither `OPT_LIMIT_DO' and `OPT_LIMIT_UO' are set
[[ ! -z ${OPT_LIMIT_DO} || ! -z ${OPT_LIMIT_UO} ]] && \
continue || match="true"
;;
"do")
## only if neither `OPT_LIMIT_AO' and `OPT_LIMIT_UO' are set
[[ ! -z ${OPT_LIMIT_AO} || ! -z ${OPT_LIMIT_UO} ]] && \
continue || match="true"
;;
"uo")
## only if `OPT_LIMIT_AO' is not set
[[ ! -z ${OPT_LIMIT_AO} ]] && \
continue || match="true"
esac
if [[ ! -z ${match} ]]; then
## put each encoding format and possibily the sample rates
## in an array
alsa_if_formats=()
formats_res_err=
str_formats_res="$(return_alsa_formats \
"${alsa_dev_nr}" \
"${alsa_if_nr}" \
"${alsa_if_type}" \
"${alsa_if_streamfile}" \
"${alsa_if_chardev}")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
formats_res_err=1
fi
alsa_if_formats+=("${str_formats_res}")
alsa_if_title_label="${ALSA_IF_LABELS[${alsa_if_type}]}"
## reconstruct the label if it contained square brackets
## construct the display title
printf -v alsa_if_display_title \
" %s) %s \`%s'" \
"${cur_aif_no}" \
"${alsa_if_title_label}" \
"${alsa_if_hwaddress}"
## store the details of the current interface in global arrays
ALSA_AIF_HWADDRESSES+=("${alsa_if_hwaddress}")
ALSA_AIF_MONITORFILES+=("${alsa_if_monitorfile}")
ALSA_AIF_DISPLAYTITLES+=("${alsa_if_display_title}")
ALSA_AIF_DEVLABELS+=("${alsa_dev_label}")
ALSA_AIF_LABELS+=("${alsa_if_label}")
ALSA_AIF_UACCLASSES+=("${alsa_if_uacclass}")
ALSA_AIF_FORMATS="${alsa_if_formats[*]}"
ALSA_AIF_CHARDEVS+=("${alsa_if_chardev}")
fi
if [[ -z "${OPT_QUIET}" ]] && [[ "${OPT_JSON}x" == "x" ]]; then
## print the list to std_err
res_human="$(return_output_human)" || exit 1
printf 1>&2 "%s\n" "${res_human}"
fi
if [[ "${OPT_JSON}x" != "x" ]]; then
if [[ ${cur_aif_no} -lt ${#aplay_lines[@]} ]]; then
printf -v json_output "%s%s\n" \
"${json_output}" \
"$(ret_json_card "${str_formats_res}" "")"
fi
fi
done
if [[ "${OPT_JSON}x" != "x" ]]; then
res_json="$(return_output_json "${json_output}")" || exit 1
printf "%s\n" "${res_json}"
fi
}
function get_locking_process() {
## return a string describing the command and id of the
## process locking the audio interface with card nr $1 and dev nr
## $2 based on its status file in /proc/asound.
## returns a comma separated string containing the locking cmd and
## pid, or an error when the interface is not locked (ie
## 'closed').
alsa_card_nr="$1"
alsa_if_nr="$2"
proc_statusfile="/proc/asound/card${alsa_card_nr}/pcm${alsa_if_nr}p/sub0/status"
owner_pid=
owner_stat=
owner_cmd=
parent_pid=
parent_cmd=
locking_cmd=
locking_pid=
## specific for mpd: each alsa output plugin results in a locking
## process indicated by `owner_pid` in
## /proc/asound/cardX/pcmYp/sub0/status: `owner_pid : 28022'
## this is a child process of the mpd parent process (`28017'):
##mpd(28017,mpd)-+-{decoder:flac}(28021)
## |-{io}(28019)
## |-{output:Peachtre}(28022) <<< owner_pid / child
## `-{player}(28020)
owner_pid_re="owner_pid[[:space:]]+:[[:space:]]+([0-9]+)"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "examining status file ${proc_statusfile}."
while read -r line; do
if [[ "${line}" =~ ${owner_pid_re} ]]; then
owner_pid="${BASH_REMATCH[1]}"
break
elif [[ "${line}" == "closed" ]]; then
return 1
fi
done<"${proc_statusfile}"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "done examining status file ${proc_statusfile}."
if [[ -z ${owner_pid} ]]; then
## device is unused
[[ ${DEBUG} ]] && \
debug "${LINENO}" "${FUNCNAME[0]} called, but no owner_pid found in \`${proc_statusfile}'."
return 1
else
[[ ${DEBUG} ]] && \
debug "${LINENO}" "found owner pid in status file \`${proc_statusfile}': \`${owner_pid}'."
fi
## check if owner_pid is a child
## construct regexp for getting the ppid from /proc
## eg: /proc/837/stat:
## 837 (output:Pink Fau) S 1 406 406 0 -1 ...
## ^^^ ^^^
## +++-> owner_pid +++-> parent_pid
parent_pid_re="(${owner_pid})[[:space:]]\(.*\)[[:space:]][A-Z][[:space:]][0-9]+[[:space:]]([0-9]+)"
# shellcheck disable=SC2162
read owner_stat < "/proc/${owner_pid}/stat"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "owner_stat: \`${owner_stat}'"
if [[ "${owner_stat}" =~ ${parent_pid_re} ]]; then
parent_pid="${BASH_REMATCH[2]}"
if [[ "x${parent_pid}" == "x${owner_pid}" ]]; then
## device is locked by the process with id owner_pid, look up command
## eg: /proc/837/cmdline: /usr/bin/mpd --no-daemon /var/lib/mpd/mpd.conf
# shellcheck disable=SC2162
read owner_cmd < "/proc/${owner_pid}/cmdline"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "cmd \`${owner_cmd}' with id \`${owner_pid}' has no parent."
locking_pid="${owner_pid}"
locking_cmd="${owner_cmd}"
else
## device is locked by the parent of the process with owner_pid
# shellcheck disable=SC2162
read owner_cmd < "/proc/${owner_pid}/cmdline"
# shellcheck disable=SC2162
read parent_cmd < "/proc/${parent_pid}/cmdline"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "cmd \`${owner_cmd}' with id \`${owner_pid}' \
has parent cmd \`${parent_cmd}' with id \`${parent_pid}'."
locking_pid="${parent_pid}"
locking_cmd="${parent_cmd}"
fi
## return comma separated list (pid,cmd) to calling function
locking_cmd="$(while read -r -d $'\0' line; do \
printf "%s " "${line}"; \
done< "/proc/${locking_pid}/cmdline")"
printf "%s,%s" "${locking_pid}" "${locking_cmd%% }"
else
## should not happen; TODO: handle
parent_pid=
fi
}
function ret_highest_alsa_samplerate() {
## check the highest supported rate of type $3 for format $2 on
## interface $1
## returns the highest supported rate.
alsa_if_hwaddress="$1"
encoding_format="$2"
type="$3"
if [[ "${type}" == "audio" ]]; then
rates=(${SAMPLERATES_AUDIO[@]})
else
rates=(${SAMPLERATES_VIDEO[@]})
fi
for rate in "${rates[@]}"; do
res="$(check_samplerate "${alsa_if_hwaddress}" "${encoding_format}" "${rate}")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
## too high; try next one
continue
else
## match; return it
printf "%s" "${rate}"
break
fi
done
}
function ret_supported_alsa_samplerates() {
## use aplay to get supported sample rates for playback for
## specified non-uac interface ($1) and encoding format ($2).
## returns a space separated list of valid rates.
alsa_if_hwaddress="$1"
encoding_format="$2"
declare -a rates
[[ ${DEBUG} ]] && \
debug "${LINENO}" "getting sample rates for device \`${alsa_if_hwaddress}' \
using encoding_format \`${encoding_format}'."
## check all audio/video rates from high to low; break when rate is
## supported while adding all the lower frequencies
highest_audiorate="$(ret_highest_alsa_samplerate \
"${alsa_if_hwaddress}" "${encoding_format}" "audio")"
highest_videorate="$(ret_highest_alsa_samplerate \
"${alsa_if_hwaddress}" "${encoding_format}" "video")"
for rate in "${SAMPLERATES_AUDIO[@]}"; do
if [[ ${rate} -le ${highest_audiorate} ]]; then
## supported; assume all lower rates are supported too
rates+=("${rate}")
fi
done
for rate in "${SAMPLERATES_VIDEO[@]}"; do
if [[ ${rate} -le ${highest_videorate} ]]; then
## supported; assume all lower rates are supported too
rates+=("${rate}")
fi
done
## sort and retrun trhe newline separated sample rates
sort -u -n <(printf "%s\n" "${rates[@]}")
}
function check_samplerate() {
## use aplay to check if the specified alsa interface ($1)
## supports encoding format $2 and sample rate $3
## returns a string with the supported sample rate or nothing
alsa_if_hwaddress="$1"
format="$2"
samplerate="$3"
declare -a aplay_args_early
aplay_args_early+=(--device="${alsa_if_hwaddress}")
aplay_args_early+=(--format="${format}")
aplay_args_early+=(--channels="2")
aplay_args_early+=(--nonblock)
declare -a aplay_args_late
## set up regular expressions to match aplay's output errors
## unused
# shellcheck disable=SC2034
rate_notaccurate_re=".*Warning:.*not[[:space:]]accurate[[:space:]]\(requested[[:space:]]=[[:space:]]([0-9]+)Hz,[[:space:]]got[[:space:]]=[[:space:]]([0-9]+)Hz\).*"
# shellcheck disable=SC2034
badspeed_re=".*bad[[:space:]]speed[[:space:]]value.*"
# shellcheck disable=SC2034
sampleformat_nonavailable_re=".*Sample[[:space:]]format[[:space:]]non[[:space:]]available.*"
# shellcheck disable=SC2034
wrongformat_re=".*wrong[[:space:]]extended[[:space:]]format.*"
## used
default_re=".*Playing[[:space:]]raw[[:space:]]data.*"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "testing rate ${samplerate}"
unset aplay_args_late
## set fixed sample rate
aplay_args_late+=(--rate="${samplerate}")
## generate aplay error using random noise to check whether sample
## rate is supported for this interface and format
# shellcheck disable=SC2145
printf -v aplay_args "%s " "${aplay_args_early[@]} ${aplay_args_late[@]}"
read -r firstline<<<"$(return_reversed_aplay_error "${aplay_args}")" || return 1
if [[ "${firstline}" =~ ${default_re} ]]; then
[[ ${DEBUG} ]] && \
debug "${LINENO}" "success"
printf "%s" "${samplerate}"
else
return 1
fi
}
function return_reversed_aplay_error() {
## force aplay to output error message containing supported
## encoding formats, by playing PSEUDO_AUDIO in a non-existing
## format.
## returns the output of aplay while reversing its return code
aplay_args="$1"
cmd_aplay="${CMD_APLAY} ${aplay_args}"
LANG=C ${cmd_aplay} 2>&1 <<< "${PSEUDO_SILENT_AUDIO}" || \
( [[ ${DEBUG} ]] && \
debug "${LINENO}" "\`${cmd_aplay}' returned error (which is good)."
return 0 ) && \
( [[ ${DEBUG} ]] && \
debug "${LINENO}" "\`${cmd_aplay}' returned error (which is not good)."
return 1 )
}
function return_nonuac_formats() {
## use aplay to determine supported formats of non-uac interface (hw:$1,$2)
alsa_dev_nr="$1"
alsa_if_nr="$2"
aplay_args=(--device=hw:${alsa_dev_nr},${alsa_if_nr})
aplay_args+=(--channels=2)
aplay_args+=(--format=MPEG)
aplay_args+=(--nonblock)
printf -v str_args "%s " "${aplay_args[@]}"
return_reversed_aplay_error "${str_args}" || \
return 1
}
function return_uac_formats_rates() {
## get encodings formats with samplerates for uac type interface
## using its streamfile $1 (which saves calls to applay).
## returns newline separated list (FORMAT:RATE,RATE,...).
alsa_if_streamfile="$1"
interface_re="^[[:space:]]*Interface[[:space:]]([0-9])"
format_re="^[[:space:]]*Format:[[:space:]](.*)"
rates_re="^[[:space:]]*Rates:[[:space:]](.*)"
capture_re="^Capture:"
inside_interface=
format_found=
declare -A uac_formats_rates
## iterate lines in the streamfile
while read -r line; do
if [[ "${line}" =~ ${capture_re} ]]; then
## end of playback interfaces
break
else
## we're not dealing with a capture interface
if [[ "${line}" =~ ${interface_re} ]]; then
## new interface found
inside_interface=true
## reset (previous) format_found
format_found=
## continue with next line
else
## continuation of interface
if [[ "${inside_interface}x" != "x" ]]; then
## parse lines below `Interface:`
if [[ "${format_found}x" == "x" ]]; then
## check for new `Format:`
if [[ "${line}" =~ ${format_re} ]]; then
## new format found
format_found="${BASH_REMATCH[1]}"
uac_formats_rates[${format_found}]=""
[[ ${DEBUG} ]] && \
debug "${LINENO}" "format found: \`${format_found}'"
## next: sample rates or new interface
fi
else
## parse lines below `Format:`
if [[ "${line}" =~ ${rates_re} ]]; then
## sample rates for interface/format found;
## return and reset both
uac_formats_rates[${format_found}]="${BASH_REMATCH[1]}"
[[ ${DEBUG} ]] && \
debug "${LINENO}" "(format=${format_found}) \
rates=${BASH_REMATCH[1]}"
format_found=
inside_interface=
continue
fi
fi
fi
fi
fi
done<"${alsa_if_streamfile}"
for format in "${!uac_formats_rates[@]}"; do
printf "%s:%s\n" \
"${format}" "${uac_formats_rates[${format}]// /}"
done
}
function return_alsa_formats() {
## fetch and return a comma separated string of playback formats
## for the interface specified in $1, of type $2. For non-uac
## interfaces: feed dummy input to aplay (--format=MPEG). For uac
## types: filter it directly from its stream file $3.
alsa_dev_nr="$1"
alsa_if_nr="$2"
alsa_if_type="$3"
alsa_if_streamfile="$4"
alsa_if_chardev="$5"
format="${format:-}"
rawformat="${rawformat:-}"
parent_pid=
parent_cmd=
declare -A uac_formats
if [[ "${alsa_if_type}" = "uo" ]]; then
## uac type; use streamfile to get encoding formats and/or
## samplerates (in the form of 'FORMAT: RATE RATE ...').
while read -r line; do
key="${line%:*}"
value="${line//${key}:/}"
uac_formats["${key}"]="${value}"
done< <(return_uac_formats_rates "${alsa_if_streamfile}")
## return the formatted line(s)
if [[ "${OPT_SAMPLERATES}x" == "x" ]]; then
## print comma separated list of formats
# shellcheck disable=SC2068
printf -v str_formats "%s, " "${!uac_formats[@]}"
printf "%-20s" "${str_formats%*, }"
else
## for each format, print "FORMAT1:rate1,rate2,..."
# shellcheck disable=SC2068
for key in ${!uac_formats[@]}; do
printf "%s:%s\n" "${key}" "${uac_formats[${key}]}"
done
fi
else
## non-uac type: if interface is not locked, use aplay to
## determine formats
## because of invalid file format, aplay is forced to return
## supported formats (=200 times faster than --dump-hw-params)
declare -a rawformats
format_re="^-[[:space:]]+([[:alnum:]_]*)$"
res="$(get_locking_process "${alsa_dev_nr}" "${alsa_if_nr}")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
## device is not locked, iterate aplay output