summaryrefslogtreecommitdiff
path: root/src/modules/alsa/alsa-ucm.c
blob: 018c01739ba0d28ee23d0dd666a807b3b3fd15d5 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
/***
 This file is part of PulseAudio.

 Copyright 2011 Wolfson Microelectronics PLC
 Author Margarita Olaya <magi@slimlogic.co.uk>
 Copyright 2012 Feng Wei <wei.feng@freescale.com>, Freescale Ltd.

 PulseAudio is free software; you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License,
 or (at your option) any later version.

 PulseAudio 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 Lesser General Public License
 along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.

***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <ctype.h>
#include <sys/types.h>
#include <limits.h>
#include <alsa/asoundlib.h>

#ifdef HAVE_VALGRIND_MEMCHECK_H
#include <valgrind/memcheck.h>
#endif

#include <pulse/sample.h>
#include <pulse/xmalloc.h>
#include <pulse/timeval.h>
#include <pulse/util.h>

#include <pulsecore/log.h>
#include <pulsecore/macro.h>
#include <pulsecore/core-util.h>
#include <pulsecore/atomic.h>
#include <pulsecore/core-error.h>
#include <pulsecore/once.h>
#include <pulsecore/thread.h>
#include <pulsecore/conf-parser.h>
#include <pulsecore/strbuf.h>

#include "alsa-mixer.h"
#include "alsa-util.h"
#include "alsa-ucm.h"

#define PA_UCM_PRE_TAG_OUTPUT                       "[Out] "
#define PA_UCM_PRE_TAG_INPUT                        "[In] "

#define PA_UCM_PLAYBACK_PRIORITY_UNSET(device)      ((device)->playback_channels && !(device)->playback_priority)
#define PA_UCM_CAPTURE_PRIORITY_UNSET(device)       ((device)->capture_channels && !(device)->capture_priority)
#define PA_UCM_DEVICE_PRIORITY_SET(device, priority) \
    do { \
        if (PA_UCM_PLAYBACK_PRIORITY_UNSET(device)) (device)->playback_priority = (priority);   \
        if (PA_UCM_CAPTURE_PRIORITY_UNSET(device))  (device)->capture_priority = (priority);    \
    } while (0)
#define PA_UCM_IS_MODIFIER_MAPPING(m) ((pa_proplist_gets((m)->proplist, PA_ALSA_PROP_UCM_MODIFIER)) != NULL)

#ifdef HAVE_ALSA_UCM

struct ucm_type {
    const char *prefix;
    pa_device_port_type_t type;
};

struct ucm_items {
    const char *id;
    const char *property;
};

struct ucm_info {
    const char *id;
    unsigned priority;
};

static pa_alsa_jack* ucm_get_jack(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *device);
static void device_set_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack);
static void device_add_hw_mute_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack);

static pa_alsa_ucm_device *verb_find_device(pa_alsa_ucm_verb *verb, const char *device_name);


static void ucm_port_data_init(pa_alsa_ucm_port_data *port, pa_alsa_ucm_config *ucm, pa_device_port *core_port,
                               pa_alsa_ucm_device *device);
static void ucm_port_data_free(pa_device_port *port);

static struct ucm_type types[] = {
    {"None", PA_DEVICE_PORT_TYPE_UNKNOWN},
    {"Speaker", PA_DEVICE_PORT_TYPE_SPEAKER},
    {"Line", PA_DEVICE_PORT_TYPE_LINE},
    {"Mic", PA_DEVICE_PORT_TYPE_MIC},
    {"Headphones", PA_DEVICE_PORT_TYPE_HEADPHONES},
    {"Headset", PA_DEVICE_PORT_TYPE_HEADSET},
    {"Handset", PA_DEVICE_PORT_TYPE_HANDSET},
    {"Bluetooth", PA_DEVICE_PORT_TYPE_BLUETOOTH},
    {"Earpiece", PA_DEVICE_PORT_TYPE_EARPIECE},
    {"SPDIF", PA_DEVICE_PORT_TYPE_SPDIF},
    {"HDMI", PA_DEVICE_PORT_TYPE_HDMI},
    {NULL, 0}
};

static struct ucm_items item[] = {
    {"PlaybackPCM", PA_ALSA_PROP_UCM_SINK},
    {"CapturePCM", PA_ALSA_PROP_UCM_SOURCE},
    {"PlaybackCTL", PA_ALSA_PROP_UCM_PLAYBACK_CTL_DEVICE},
    {"PlaybackVolume", PA_ALSA_PROP_UCM_PLAYBACK_VOLUME},
    {"PlaybackSwitch", PA_ALSA_PROP_UCM_PLAYBACK_SWITCH},
    {"PlaybackMixer", PA_ALSA_PROP_UCM_PLAYBACK_MIXER_DEVICE},
    {"PlaybackMixerElem", PA_ALSA_PROP_UCM_PLAYBACK_MIXER_ELEM},
    {"PlaybackMasterElem", PA_ALSA_PROP_UCM_PLAYBACK_MASTER_ELEM},
    {"PlaybackMasterType", PA_ALSA_PROP_UCM_PLAYBACK_MASTER_TYPE},
    {"PlaybackPriority", PA_ALSA_PROP_UCM_PLAYBACK_PRIORITY},
    {"PlaybackRate", PA_ALSA_PROP_UCM_PLAYBACK_RATE},
    {"PlaybackChannels", PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS},
    {"CaptureCTL", PA_ALSA_PROP_UCM_CAPTURE_CTL_DEVICE},
    {"CaptureVolume", PA_ALSA_PROP_UCM_CAPTURE_VOLUME},
    {"CaptureSwitch", PA_ALSA_PROP_UCM_CAPTURE_SWITCH},
    {"CaptureMixer", PA_ALSA_PROP_UCM_CAPTURE_MIXER_DEVICE},
    {"CaptureMixerElem", PA_ALSA_PROP_UCM_CAPTURE_MIXER_ELEM},
    {"CaptureMasterElem", PA_ALSA_PROP_UCM_CAPTURE_MASTER_ELEM},
    {"CaptureMasterType", PA_ALSA_PROP_UCM_CAPTURE_MASTER_TYPE},
    {"CapturePriority", PA_ALSA_PROP_UCM_CAPTURE_PRIORITY},
    {"CaptureRate", PA_ALSA_PROP_UCM_CAPTURE_RATE},
    {"CaptureChannels", PA_ALSA_PROP_UCM_CAPTURE_CHANNELS},
    {"TQ", PA_ALSA_PROP_UCM_QOS},
    {"JackCTL", PA_ALSA_PROP_UCM_JACK_DEVICE},
    {"JackControl", PA_ALSA_PROP_UCM_JACK_CONTROL},
    {"JackHWMute", PA_ALSA_PROP_UCM_JACK_HW_MUTE},
    {NULL, NULL},
};

/* UCM verb info - this should eventually be part of policy manangement */
static struct ucm_info verb_info[] = {
    {SND_USE_CASE_VERB_INACTIVE, 0},
    {SND_USE_CASE_VERB_HIFI, 8000},
    {SND_USE_CASE_VERB_HIFI_LOW_POWER, 7000},
    {SND_USE_CASE_VERB_VOICE, 6000},
    {SND_USE_CASE_VERB_VOICE_LOW_POWER, 5000},
    {SND_USE_CASE_VERB_VOICECALL, 4000},
    {SND_USE_CASE_VERB_IP_VOICECALL, 4000},
    {SND_USE_CASE_VERB_ANALOG_RADIO, 3000},
    {SND_USE_CASE_VERB_DIGITAL_RADIO, 3000},
    {NULL, 0}
};

/* UCM device info - should be overwritten by ucm property */
static struct ucm_info dev_info[] = {
    {SND_USE_CASE_DEV_SPEAKER, 100},
    {SND_USE_CASE_DEV_LINE, 100},
    {SND_USE_CASE_DEV_HEADPHONES, 100},
    {SND_USE_CASE_DEV_HEADSET, 300},
    {SND_USE_CASE_DEV_HANDSET, 200},
    {SND_USE_CASE_DEV_BLUETOOTH, 400},
    {SND_USE_CASE_DEV_EARPIECE, 100},
    {SND_USE_CASE_DEV_SPDIF, 100},
    {SND_USE_CASE_DEV_HDMI, 100},
    {SND_USE_CASE_DEV_NONE, 100},
    {NULL, 0}
};


static char *ucm_verb_value(
    snd_use_case_mgr_t *uc_mgr,
    const char *verb_name,
    const char *id) {

    const char *value;
    char *_id = pa_sprintf_malloc("=%s//%s", id, verb_name);
    int err = snd_use_case_get(uc_mgr, _id, &value);
    pa_xfree(_id);
    if (err < 0)
         return NULL;
    pa_log_debug("Got %s for verb %s: %s", id, verb_name, value);
    /* Use the cast here to allow free() call without casting for callers.
     * The snd_use_case_get() returns mallocated string.
     * See the Note: in use-case.h for snd_use_case_get().
     */
    return (char *)value;
}

static void ucm_add_devices_to_idxset(
        pa_idxset *idxset,
        pa_alsa_ucm_device *me,
        pa_alsa_ucm_device *devices,
        const char **dev_names,
        int n) {

    pa_alsa_ucm_device *d;

    PA_LLIST_FOREACH(d, devices) {
        const char *name;
        int i;

        if (d == me)
            continue;

        name = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME);

        for (i = 0; i < n; i++)
            if (pa_streq(dev_names[i], name))
                pa_idxset_put(idxset, d, NULL);
    }
}

/* Split a string into words. Like pa_split_spaces() but handle '' and "". */
static char *ucm_split_devnames(const char *c, const char **state) {
    const char *current = *state ? *state : c;
    char h;
    size_t l;

    if (!*current || *c == 0)
        return NULL;

    current += strspn(current, "\n\r \t");
    h = *current;
    if (h == '\'' || h =='"') {
        c = ++current;
        for (l = 0; *c && *c != h; l++) c++;
        if (*c != h)
            return NULL;
        *state = c + 1;
    } else {
        l = strcspn(current, "\n\r \t");
        *state = current+l;
    }

    return pa_xstrndup(current, l);
}


static void ucm_volume_free(pa_alsa_ucm_volume *vol) {
    pa_assert(vol);
    pa_xfree(vol->mixer_elem);
    pa_xfree(vol->master_elem);
    pa_xfree(vol->master_type);
    pa_xfree(vol);
}

/* Get the volume identifier */
static char *ucm_get_mixer_id(
        pa_alsa_ucm_device *device,
        const char *mprop,
        const char *cprop,
        const char *cid)
{
#if SND_LIB_VERSION >= 0x10201 /* alsa-lib-1.2.1+ check */
    snd_ctl_elem_id_t *ctl;
    int err;
#endif
    const char *value;
    char *value2;
    int index;

    /* mixer element as first, if it's found, return it without modifications */
    value = pa_proplist_gets(device->proplist, mprop);
    if (value)
        return pa_xstrdup(value);
    /* fallback, get the control element identifier */
    /* and try to do some heuristic to determine the mixer element name */
    value = pa_proplist_gets(device->proplist, cprop);
    if (value == NULL)
        return NULL;
#if SND_LIB_VERSION >= 0x10201 /* alsa-lib-1.2.1+ check */
    /* The new parser may return also element index. */
    snd_ctl_elem_id_alloca(&ctl);
    err = snd_use_case_parse_ctl_elem_id(ctl, cid, value);
    if (err < 0)
        return NULL;
    value = snd_ctl_elem_id_get_name(ctl);
    index = snd_ctl_elem_id_get_index(ctl);
#else
#warning "Upgrade to alsa-lib 1.2.1!"
    index = 0;
#endif
    if (!(value2 = pa_str_strip_suffix(value, " Playback Volume")))
        if (!(value2 = pa_str_strip_suffix(value, " Capture Volume")))
            if (!(value2 = pa_str_strip_suffix(value, " Volume")))
                value2 = pa_xstrdup(value);
    if (index > 0) {
        char *mix = pa_sprintf_malloc("'%s',%d", value2, index);
        pa_xfree(value2);
        return mix;
    }
    return value2;
}

/* Get the volume identifier */
static pa_alsa_ucm_volume *ucm_get_mixer_volume(
        pa_alsa_ucm_device *device,
        const char *mprop,
        const char *cprop,
        const char *cid,
        const char *masterid,
        const char *mastertype)
{
    pa_alsa_ucm_volume *vol;
    char *mixer_elem;

    mixer_elem = ucm_get_mixer_id(device, mprop, cprop, cid);
    if (mixer_elem == NULL)
        return NULL;
    vol = pa_xnew0(pa_alsa_ucm_volume, 1);
    if (vol == NULL) {
        pa_xfree(mixer_elem);
        return NULL;
    }
    vol->mixer_elem = mixer_elem;
    vol->master_elem = pa_xstrdup(pa_proplist_gets(device->proplist, masterid));
    vol->master_type = pa_xstrdup(pa_proplist_gets(device->proplist, mastertype));
    return vol;
}

/* Get the ALSA mixer device for the UCM device */
static const char *get_mixer_device(pa_alsa_ucm_device *dev, bool is_sink)
{
    const char *dev_name;
    
    if (is_sink) {
        dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_PLAYBACK_MIXER_DEVICE);
        if (!dev_name)
            dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_PLAYBACK_CTL_DEVICE);
    } else {
        dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_CAPTURE_MIXER_DEVICE);
        if (!dev_name)
            dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_CAPTURE_CTL_DEVICE);
    }
    return dev_name;
}

/* Get the ALSA mixer device for the UCM jack */
static const char *get_jack_mixer_device(pa_alsa_ucm_device *dev, bool is_sink) {
    const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_JACK_DEVICE);
    if (!dev_name)
        return get_mixer_device(dev, is_sink);
    return dev_name;
}

/* Create a property list for this ucm device */
static int ucm_get_device_property(
        pa_alsa_ucm_device *device,
        snd_use_case_mgr_t *uc_mgr,
        pa_alsa_ucm_verb *verb,
        const char *device_name) {

    const char *value;
    const char **devices;
    char *id, *s;
    int i;
    int err;
    uint32_t ui;
    int n_confdev, n_suppdev;
    pa_alsa_ucm_volume *vol;

    /* determine the device type */
    device->type = PA_DEVICE_PORT_TYPE_UNKNOWN;
    id = s = pa_xstrdup(device_name);
    while (s && *s && isalpha(*s)) s++;
    if (s)
        *s = '\0';
    for (i = 0; types[i].prefix; i++)
        if (pa_streq(id, types[i].prefix)) {
            device->type = types[i].type;
            break;
        }
    pa_xfree(id);

    /* set properties */
    for (i = 0; item[i].id; i++) {
        id = pa_sprintf_malloc("%s/%s", item[i].id, device_name);
        err = snd_use_case_get(uc_mgr, id, &value);
        pa_xfree(id);
        if (err < 0)
            continue;

        pa_log_debug("Got %s for device %s: %s", item[i].id, device_name, value);
        pa_proplist_sets(device->proplist, item[i].property, value);
        free((void*)value);
    }

    /* get direction and channels */
    value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS);
    if (value) { /* output */
        /* get channels */
        if (pa_atou(value, &ui) == 0 && pa_channels_valid(ui))
            device->playback_channels = ui;
        else
            pa_log("UCM playback channels %s for device %s out of range", value, device_name);

        /* get pcm */
        value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SINK);
        if (!value) /* take pcm from verb playback default */
            pa_log("UCM playback device %s fetch pcm failed", device_name);
    }

    if (pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SINK) &&
        device->playback_channels == 0) {
        pa_log_info("UCM file does not specify 'PlaybackChannels' "
                    "for device %s, assuming stereo.", device_name);
        device->playback_channels = 2;
    }

    value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_CAPTURE_CHANNELS);
    if (value) { /* input */
        /* get channels */
        if (pa_atou(value, &ui) == 0 && pa_channels_valid(ui))
            device->capture_channels = ui;
        else
            pa_log("UCM capture channels %s for device %s out of range", value, device_name);

        /* get pcm */
        value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SOURCE);
        if (!value) /* take pcm from verb capture default */
            pa_log("UCM capture device %s fetch pcm failed", device_name);
    }

    if (pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SOURCE) &&
        device->capture_channels == 0) {
        pa_log_info("UCM file does not specify 'CaptureChannels' "
                    "for device %s, assuming stereo.", device_name);
        device->capture_channels = 2;
    }

    /* get rate and priority of device */
    if (device->playback_channels) { /* sink device */
        /* get rate */
        if ((value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_PLAYBACK_RATE))) {
            if (pa_atou(value, &ui) == 0 && pa_sample_rate_valid(ui)) {
                pa_log_debug("UCM playback device %s rate %d", device_name, ui);
                device->playback_rate = ui;
            } else
                pa_log_debug("UCM playback device %s has bad rate %s", device_name, value);
        }

        value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_PLAYBACK_PRIORITY);
        if (value) {
            /* get priority from ucm config */
            if (pa_atou(value, &ui) == 0)
                device->playback_priority = ui;
            else
                pa_log_debug("UCM playback priority %s for device %s error", value, device_name);
        }

        vol = ucm_get_mixer_volume(device,
                                   PA_ALSA_PROP_UCM_PLAYBACK_MIXER_ELEM,
                                   PA_ALSA_PROP_UCM_PLAYBACK_VOLUME,
                                   "PlaybackVolume",
                                   PA_ALSA_PROP_UCM_PLAYBACK_MASTER_ELEM,
                                   PA_ALSA_PROP_UCM_PLAYBACK_MASTER_TYPE);
        if (vol)
            pa_hashmap_put(device->playback_volumes, pa_xstrdup(pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME)), vol);
    }

    if (device->capture_channels) { /* source device */
        /* get rate */
        if ((value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_CAPTURE_RATE))) {
            if (pa_atou(value, &ui) == 0 && pa_sample_rate_valid(ui)) {
                pa_log_debug("UCM capture device %s rate %d", device_name, ui);
                device->capture_rate = ui;
            } else
                pa_log_debug("UCM capture device %s has bad rate %s", device_name, value);
        }

        value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_CAPTURE_PRIORITY);
        if (value) {
            /* get priority from ucm config */
            if (pa_atou(value, &ui) == 0)
                device->capture_priority = ui;
            else
                pa_log_debug("UCM capture priority %s for device %s error", value, device_name);
        }

        vol = ucm_get_mixer_volume(device,
                                   PA_ALSA_PROP_UCM_CAPTURE_MIXER_ELEM,
                                   PA_ALSA_PROP_UCM_CAPTURE_VOLUME,
                                   "CaptureVolume",
                                   PA_ALSA_PROP_UCM_CAPTURE_MASTER_ELEM,
                                   PA_ALSA_PROP_UCM_CAPTURE_MASTER_TYPE);
        if (vol)
          pa_hashmap_put(device->capture_volumes, pa_xstrdup(pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME)), vol);
    }

    if (PA_UCM_PLAYBACK_PRIORITY_UNSET(device) || PA_UCM_CAPTURE_PRIORITY_UNSET(device)) {
        /* get priority from static table */
        for (i = 0; dev_info[i].id; i++) {
            if (strcasecmp(dev_info[i].id, device_name) == 0) {
                PA_UCM_DEVICE_PRIORITY_SET(device, dev_info[i].priority);
                break;
            }
        }
    }

    if (PA_UCM_PLAYBACK_PRIORITY_UNSET(device)) {
        /* fall through to default priority */
        device->playback_priority = 100;
    }

    if (PA_UCM_CAPTURE_PRIORITY_UNSET(device)) {
        /* fall through to default priority */
        device->capture_priority = 100;
    }

    id = pa_sprintf_malloc("%s/%s", "_conflictingdevs", device_name);
    n_confdev = snd_use_case_get_list(uc_mgr, id, &devices);
    pa_xfree(id);

    device->conflicting_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
    if (n_confdev <= 0)
        pa_log_debug("No %s for device %s", "_conflictingdevs", device_name);
    else {
        ucm_add_devices_to_idxset(device->conflicting_devices, device, verb->devices, devices, n_confdev);
        snd_use_case_free_list(devices, n_confdev);
    }

    id = pa_sprintf_malloc("%s/%s", "_supporteddevs", device_name);
    n_suppdev = snd_use_case_get_list(uc_mgr, id, &devices);
    pa_xfree(id);

    device->supported_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
    if (n_suppdev <= 0)
        pa_log_debug("No %s for device %s", "_supporteddevs", device_name);
    else {
        ucm_add_devices_to_idxset(device->supported_devices, device, verb->devices, devices, n_suppdev);
        snd_use_case_free_list(devices, n_suppdev);
    }

    return 0;
};

/* Create a property list for this ucm modifier */
static int ucm_get_modifier_property(
        pa_alsa_ucm_modifier *modifier,
        snd_use_case_mgr_t *uc_mgr,
        pa_alsa_ucm_verb *verb,
        const char *modifier_name) {
    const char *value;
    char *id;
    int i;
    const char **devices;
    int n_confdev, n_suppdev;

    for (i = 0; item[i].id; i++) {
        int err;

        id = pa_sprintf_malloc("=%s/%s", item[i].id, modifier_name);
        err = snd_use_case_get(uc_mgr, id, &value);
        pa_xfree(id);
        if (err < 0)
            continue;

        pa_log_debug("Got %s for modifier %s: %s", item[i].id, modifier_name, value);
        pa_proplist_sets(modifier->proplist, item[i].property, value);
        free((void*)value);
    }

    id = pa_sprintf_malloc("%s/%s", "_conflictingdevs", modifier_name);
    n_confdev = snd_use_case_get_list(uc_mgr, id, &devices);
    pa_xfree(id);

    modifier->conflicting_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
    if (n_confdev <= 0)
        pa_log_debug("No %s for modifier %s", "_conflictingdevs", modifier_name);
    else {
        ucm_add_devices_to_idxset(modifier->conflicting_devices, NULL, verb->devices, devices, n_confdev);
        snd_use_case_free_list(devices, n_confdev);
    }

    id = pa_sprintf_malloc("%s/%s", "_supporteddevs", modifier_name);
    n_suppdev = snd_use_case_get_list(uc_mgr, id, &devices);
    pa_xfree(id);

    modifier->supported_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
    if (n_suppdev <= 0)
        pa_log_debug("No %s for modifier %s", "_supporteddevs", modifier_name);
    else {
        ucm_add_devices_to_idxset(modifier->supported_devices, NULL, verb->devices, devices, n_suppdev);
        snd_use_case_free_list(devices, n_suppdev);
    }

    return 0;
};

/* Create a list of devices for this verb */
static int ucm_get_devices(pa_alsa_ucm_verb *verb, snd_use_case_mgr_t *uc_mgr) {
    const char **dev_list;
    int num_dev, i;

    num_dev = snd_use_case_get_list(uc_mgr, "_devices", &dev_list);
    if (num_dev < 0)
        return num_dev;

    for (i = 0; i < num_dev; i += 2) {
        pa_alsa_ucm_device *d = pa_xnew0(pa_alsa_ucm_device, 1);

        d->proplist = pa_proplist_new();
        pa_proplist_sets(d->proplist, PA_ALSA_PROP_UCM_NAME, pa_strnull(dev_list[i]));
        pa_proplist_sets(d->proplist, PA_ALSA_PROP_UCM_DESCRIPTION, pa_strna(dev_list[i + 1]));
        d->ucm_ports = pa_dynarray_new(NULL);
        d->hw_mute_jacks = pa_dynarray_new(NULL);
        d->available = PA_AVAILABLE_UNKNOWN;

        d->playback_volumes = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree,
                                                  (pa_free_cb_t) ucm_volume_free);
        d->capture_volumes = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree,
                                                 (pa_free_cb_t) ucm_volume_free);

        PA_LLIST_PREPEND(pa_alsa_ucm_device, verb->devices, d);
    }

    snd_use_case_free_list(dev_list, num_dev);

    return 0;
};

static long ucm_device_status(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *dev) {
    const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
    char *devstatus;
    long status = 0;

    if (!ucm->active_verb) {
        pa_log_error("Failed to get status for UCM device %s: no UCM verb set", dev_name);
        return -1;
    }

    devstatus = pa_sprintf_malloc("_devstatus/%s", dev_name);
    if (snd_use_case_geti(ucm->ucm_mgr, devstatus, &status) < 0) {
        pa_log_debug("Failed to get status for UCM device %s", dev_name);
        status = -1;
    }
    pa_xfree(devstatus);

    return status;
}

static int ucm_device_disable(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *dev) {
    const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);

    if (!ucm->active_verb) {
        pa_log_error("Failed to disable UCM device %s: no UCM verb set", dev_name);
        return -1;
    }

    /* If any of dev's conflicting devices is enabled, trying to disable
     * dev gives an error despite the fact that it's already disabled.
     * Check that dev is enabled to avoid this error. */
    if (ucm_device_status(ucm, dev) == 0) {
        pa_log_debug("UCM device %s is already disabled", dev_name);
        return 0;
    }

    pa_log_debug("Disabling UCM device %s", dev_name);
    if (snd_use_case_set(ucm->ucm_mgr, "_disdev", dev_name) < 0) {
        pa_log("Failed to disable UCM device %s", dev_name);
        return -1;
    }

    return 0;
}

static int ucm_device_enable(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *dev) {
    const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);

    if (!ucm->active_verb) {
        pa_log_error("Failed to enable UCM device %s: no UCM verb set", dev_name);
        return -1;
    }

    /* We don't need to enable devices that are already enabled */
    if (ucm_device_status(ucm, dev) > 0) {
        pa_log_debug("UCM device %s is already enabled", dev_name);
        return 0;
    }

    pa_log_debug("Enabling UCM device %s", dev_name);
    if (snd_use_case_set(ucm->ucm_mgr, "_enadev", dev_name) < 0) {
        pa_log("Failed to enable UCM device %s", dev_name);
        return -1;
    }

    return 0;
}

static int ucm_get_modifiers(pa_alsa_ucm_verb *verb, snd_use_case_mgr_t *uc_mgr) {
    const char **mod_list;
    int num_mod, i;

    num_mod = snd_use_case_get_list(uc_mgr, "_modifiers", &mod_list);
    if (num_mod < 0)
        return num_mod;

    for (i = 0; i < num_mod; i += 2) {
        pa_alsa_ucm_modifier *m;

        if (!mod_list[i]) {
            pa_log_warn("Got a modifier with a null name. Skipping.");
            continue;
        }

        m = pa_xnew0(pa_alsa_ucm_modifier, 1);
        m->proplist = pa_proplist_new();

        pa_proplist_sets(m->proplist, PA_ALSA_PROP_UCM_NAME, mod_list[i]);
        pa_proplist_sets(m->proplist, PA_ALSA_PROP_UCM_DESCRIPTION, pa_strna(mod_list[i + 1]));

        PA_LLIST_PREPEND(pa_alsa_ucm_modifier, verb->modifiers, m);
    }

    snd_use_case_free_list(mod_list, num_mod);

    return 0;
};

static long ucm_modifier_status(pa_alsa_ucm_config *ucm, pa_alsa_ucm_modifier *mod) {
    const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);
    char *modstatus;
    long status = 0;

    if (!ucm->active_verb) {
        pa_log_error("Failed to get status for UCM modifier %s: no UCM verb set", mod_name);
        return -1;
    }

    modstatus = pa_sprintf_malloc("_modstatus/%s", mod_name);
    if (snd_use_case_geti(ucm->ucm_mgr, modstatus, &status) < 0) {
        pa_log_debug("Failed to get status for UCM modifier %s", mod_name);
        status = -1;
    }
    pa_xfree(modstatus);

    return status;
}

static int ucm_modifier_disable(pa_alsa_ucm_config *ucm, pa_alsa_ucm_modifier *mod) {
    const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);

    if (!ucm->active_verb) {
        pa_log_error("Failed to disable UCM modifier %s: no UCM verb set", mod_name);
        return -1;
    }

    /* We don't need to disable modifiers that are already disabled */
    if (ucm_modifier_status(ucm, mod) == 0) {
        pa_log_debug("UCM modifier %s is already disabled", mod_name);
        return 0;
    }

    pa_log_debug("Disabling UCM modifier %s", mod_name);
    if (snd_use_case_set(ucm->ucm_mgr, "_dismod", mod_name) < 0) {
        pa_log("Failed to disable UCM modifier %s", mod_name);
        return -1;
    }

    return 0;
}

static int ucm_modifier_enable(pa_alsa_ucm_config *ucm, pa_alsa_ucm_modifier *mod) {
    const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);

    if (!ucm->active_verb) {
        pa_log_error("Failed to disable UCM modifier %s: no UCM verb set", mod_name);
        return -1;
    }

    /* We don't need to enable modifiers that are already enabled */
    if (ucm_modifier_status(ucm, mod) > 0) {
        pa_log_debug("UCM modifier %s is already enabled", mod_name);
        return 0;
    }

    pa_log_debug("Enabling UCM modifier %s", mod_name);
    if (snd_use_case_set(ucm->ucm_mgr, "_enamod", mod_name) < 0) {
        pa_log("Failed to enable UCM modifier %s", mod_name);
        return -1;
    }

    return 0;
}

static void add_role_to_device(pa_alsa_ucm_device *dev, const char *dev_name, const char *role_name, const char *role) {
    const char *cur = pa_proplist_gets(dev->proplist, role_name);

    if (!cur)
        pa_proplist_sets(dev->proplist, role_name, role);
    else if (!pa_str_in_list_spaces(cur, role)) { /* does not exist */
        char *value = pa_sprintf_malloc("%s %s", cur, role);

        pa_proplist_sets(dev->proplist, role_name, value);
        pa_xfree(value);
    }

    pa_log_info("Add role %s to device %s(%s), result %s", role, dev_name, role_name, pa_proplist_gets(dev->proplist,
                role_name));
}

static void add_media_role(pa_alsa_ucm_device *dev, const char *role_name, const char *role, bool is_sink) {
    const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
    const char *sink = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SINK);
    const char *source = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SOURCE);

    if (is_sink && sink)
        add_role_to_device(dev, dev_name, role_name, role);
    else if (!is_sink && source)
        add_role_to_device(dev, dev_name, role_name, role);
}

static char *modifier_name_to_role(const char *mod_name, bool *is_sink) {
    char *sub = NULL, *tmp, *pos;

    *is_sink = false;

    if (pa_startswith(mod_name, "Play")) {
        *is_sink = true;
        sub = pa_xstrdup(mod_name + 4);
    } else if (pa_startswith(mod_name, "Capture"))
        sub = pa_xstrdup(mod_name + 7);

    pos = sub;
    while (pos && *pos == ' ') pos++;

    if (!pos || !*pos) {
        pa_xfree(sub);
        pa_log_warn("Can't match media roles for modifier %s", mod_name);
        return NULL;
    }

    tmp = pos;

    do {
        *tmp = tolower(*tmp);
    } while (*(++tmp));

    tmp = pa_xstrdup(pos);
    pa_xfree(sub);
    return tmp;
}

static void ucm_set_media_roles(pa_alsa_ucm_modifier *modifier, const char *mod_name) {
    pa_alsa_ucm_device *dev;
    bool is_sink = false;
    char *sub = NULL;
    const char *role_name;
    uint32_t idx;

    sub = modifier_name_to_role(mod_name, &is_sink);
    if (!sub)
        return;

    modifier->action_direction = is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT;
    modifier->media_role = sub;

    role_name = is_sink ? PA_ALSA_PROP_UCM_PLAYBACK_ROLES : PA_ALSA_PROP_UCM_CAPTURE_ROLES;
    PA_IDXSET_FOREACH(dev, modifier->supported_devices, idx) {
        /* if modifier has no specific pcm, we add role intent to its supported devices */
        if (!pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_SINK) &&
                !pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_SOURCE))
            add_media_role(dev, role_name, sub, is_sink);
    }
}

static void append_lost_relationship(pa_alsa_ucm_device *dev) {
    uint32_t idx;
    pa_alsa_ucm_device *d;

    PA_IDXSET_FOREACH(d, dev->conflicting_devices, idx)
        if (pa_idxset_put(d->conflicting_devices, dev, NULL) == 0)
            pa_log_warn("Add lost conflicting device %s to %s",
                    pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME),
                    pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME));

    PA_IDXSET_FOREACH(d, dev->supported_devices, idx)
        if (pa_idxset_put(d->supported_devices, dev, NULL) == 0)
            pa_log_warn("Add lost supported device %s to %s",
                    pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME),
                    pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME));
}

int pa_alsa_ucm_query_profiles(pa_alsa_ucm_config *ucm, int card_index) {
    char *card_name;
    const char **verb_list, *value;
    int num_verbs, i, err = 0;

    /* support multiple card instances, address card directly by index */
    card_name = pa_sprintf_malloc("hw:%i", card_index);
    err = snd_use_case_mgr_open(&ucm->ucm_mgr, card_name);
    if (err < 0) {
        /* fallback longname: is UCM available for this card ? */
        pa_xfree(card_name);
        err = snd_card_get_name(card_index, &card_name);
        if (err < 0) {
            pa_log("Card can't get card_name from card_index %d", card_index);
            err = -PA_ALSA_ERR_UNSPECIFIED;
            goto name_fail;
        }

        err = snd_use_case_mgr_open(&ucm->ucm_mgr, card_name);
        if (err < 0) {
            pa_log_info("UCM not available for card %s", card_name);
            err = -PA_ALSA_ERR_UCM_OPEN;
            goto ucm_mgr_fail;
        }
    }

    err = snd_use_case_get(ucm->ucm_mgr, "=Linked", &value);
    if (err >= 0) {
        if (strcasecmp(value, "true") == 0 || strcasecmp(value, "1") == 0) {
            free((void *)value);
            pa_log_info("Empty (linked) UCM for card %s", card_name);
            err = -PA_ALSA_ERR_UCM_LINKED;
            goto ucm_verb_fail;
        }
        free((void *)value);
    }

    pa_log_info("UCM available for card %s", card_name);

    if (snd_use_case_get(ucm->ucm_mgr, "_alibpref", &value) == 0) {
        if (value[0]) {
            ucm->alib_prefix = pa_xstrdup(value);
            pa_log_debug("UCM _alibpref=%s", ucm->alib_prefix);
        }
        free((void *)value);
    }

    /* get a list of all UCM verbs for this card */
    num_verbs = snd_use_case_verb_list(ucm->ucm_mgr, &verb_list);
    if (num_verbs < 0) {
        pa_log("UCM verb list not found for %s", card_name);
        err = -PA_ALSA_ERR_UNSPECIFIED;
        goto ucm_verb_fail;
    }

    /* get the properties of each UCM verb */
    for (i = 0; i < num_verbs; i += 2) {
        pa_alsa_ucm_verb *verb;

        /* Get devices and modifiers for each verb */
        err = pa_alsa_ucm_get_verb(ucm->ucm_mgr, verb_list[i], verb_list[i+1], &verb);
        if (err < 0) {
            pa_log("Failed to get the verb %s", verb_list[i]);
            continue;
        }

        PA_LLIST_PREPEND(pa_alsa_ucm_verb, ucm->verbs, verb);
    }

    if (!ucm->verbs) {
        pa_log("No UCM verb is valid for %s", card_name);
        err = -PA_ALSA_ERR_UCM_NO_VERB;
    }

    snd_use_case_free_list(verb_list, num_verbs);

ucm_verb_fail:
    if (err < 0) {
        snd_use_case_mgr_close(ucm->ucm_mgr);
        ucm->ucm_mgr = NULL;
    }

ucm_mgr_fail:
    pa_xfree(card_name);

name_fail:
    return err;
}

int pa_alsa_ucm_get_verb(snd_use_case_mgr_t *uc_mgr, const char *verb_name, const char *verb_desc, pa_alsa_ucm_verb **p_verb) {
    pa_alsa_ucm_device *d;
    pa_alsa_ucm_modifier *mod;
    pa_alsa_ucm_verb *verb;
    char *value;
    unsigned ui;
    int err = 0;

    *p_verb = NULL;
    pa_log_info("Set UCM verb to %s", verb_name);
    err = snd_use_case_set(uc_mgr, "_verb", verb_name);
    if (err < 0)
        return err;

    verb = pa_xnew0(pa_alsa_ucm_verb, 1);
    verb->proplist = pa_proplist_new();

    pa_proplist_sets(verb->proplist, PA_ALSA_PROP_UCM_NAME, pa_strnull(verb_name));
    pa_proplist_sets(verb->proplist, PA_ALSA_PROP_UCM_DESCRIPTION, pa_strna(verb_desc));

    value = ucm_verb_value(uc_mgr, verb_name, "Priority");
    if (value && !pa_atou(value, &ui))
        verb->priority = ui > 10000 ? 10000 : ui;
    free(value);

    err = ucm_get_devices(verb, uc_mgr);
    if (err < 0)
        pa_log("No UCM devices for verb %s", verb_name);

    err = ucm_get_modifiers(verb, uc_mgr);
    if (err < 0)
        pa_log("No UCM modifiers for verb %s", verb_name);

    PA_LLIST_FOREACH(d, verb->devices) {
        const char *dev_name = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME);

        /* Devices properties */
        ucm_get_device_property(d, uc_mgr, verb, dev_name);
    }
    /* make conflicting or supported device mutual */
    PA_LLIST_FOREACH(d, verb->devices)
        append_lost_relationship(d);

    PA_LLIST_FOREACH(mod, verb->modifiers) {
        const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);

        /* Modifier properties */
        ucm_get_modifier_property(mod, uc_mgr, verb, mod_name);

        /* Set PA_PROP_DEVICE_INTENDED_ROLES property to devices */
        pa_log_debug("Set media roles for verb %s, modifier %s", verb_name, mod_name);
        ucm_set_media_roles(mod, mod_name);
    }

    *p_verb = verb;
    return 0;
}

static int pa_alsa_ucm_device_cmp(const void *a, const void *b) {
    const pa_alsa_ucm_device *d1 = *(pa_alsa_ucm_device **)a;
    const pa_alsa_ucm_device *d2 = *(pa_alsa_ucm_device **)b;

    return strcmp(pa_proplist_gets(d1->proplist, PA_ALSA_PROP_UCM_NAME), pa_proplist_gets(d2->proplist, PA_ALSA_PROP_UCM_NAME));
}

static void set_eld_devices(pa_hashmap *hash)
{
    pa_device_port *port;
    pa_alsa_ucm_port_data *data;
    pa_alsa_ucm_device *dev;
    void *state;

    PA_HASHMAP_FOREACH(port, hash, state) {
        data = PA_DEVICE_PORT_DATA(port);
        dev = data->device;
        data->eld_device = dev->eld_device;
        data->eld_mixer_device_name = pa_xstrdup(dev->eld_mixer_device_name);
    }
}

static void update_mixer_paths(pa_hashmap *ports, const char *verb_name) {
    pa_device_port *port;
    pa_alsa_ucm_port_data *data;
    void *state;

    /* select volume controls on ports */
    PA_HASHMAP_FOREACH(port, ports, state) {
        pa_log_info("Updating mixer path for %s: %s", verb_name, port->name);
        data = PA_DEVICE_PORT_DATA(port);
        data->path = pa_hashmap_get(data->paths, verb_name);
    }
}

static void probe_volumes(pa_hashmap *hash, bool is_sink, snd_pcm_t *pcm_handle, pa_hashmap *mixers, bool ignore_dB) {
    pa_device_port *port;
    pa_alsa_path *path;
    pa_alsa_ucm_port_data *data;
    pa_alsa_ucm_device *dev;
    snd_mixer_t *mixer_handle;
    const char *verb_name, *mdev;
    void *state, *state2;

    PA_HASHMAP_FOREACH(port, hash, state) {
        data = PA_DEVICE_PORT_DATA(port);

        dev = data->device;
        mdev = get_mixer_device(dev, is_sink);
        if (mdev == NULL || !(mixer_handle = pa_alsa_open_mixer_by_name(mixers, mdev, true))) {
            pa_log_error("Failed to find a working mixer device (%s).", mdev);
            goto fail;
        }

        PA_HASHMAP_FOREACH_KV(verb_name, path, data->paths, state2) {
            if (pa_alsa_path_probe(path, NULL, mixer_handle, ignore_dB) < 0) {
                pa_log_warn("Could not probe path: %s, using s/w volume", path->name);
                pa_hashmap_remove(data->paths, verb_name);
            } else if (!path->has_volume && !path->has_mute) {
                pa_log_warn("Path %s is not a volume or mute control", path->name);
                pa_hashmap_remove(data->paths, verb_name);
            } else
                pa_log_debug("Set up h/w %s using '%s' for %s:%s", path->has_volume ? "volume" : "mute",
                                path->name, verb_name, port->name);
        }
    }

    return;

fail:
    /* We could not probe the paths we created. Free them and revert to software volumes. */
    PA_HASHMAP_FOREACH(port, hash, state) {
        data = PA_DEVICE_PORT_DATA(port);
        pa_hashmap_remove_all(data->paths);
    }
}

static char *devset_name(pa_idxset *devices, const char *sep) {
    int i = 0;
    int num = pa_idxset_size(devices);
    pa_alsa_ucm_device *sorted[num], *dev;
    char *dev_names = NULL;
    char *tmp = NULL;
    uint32_t idx;

    PA_IDXSET_FOREACH(dev, devices, idx) {
        sorted[i] = dev;
        i++;
    }

    /* Sort by alphabetical order so as to have a deterministic naming scheme */
    qsort(&sorted[0], num, sizeof(pa_alsa_ucm_device *), pa_alsa_ucm_device_cmp);

    for (i = 0; i < num; i++) {
        dev = sorted[i];
        const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);

        if (!dev_names) {
            dev_names = pa_xstrdup(dev_name);
        } else {
            tmp = pa_sprintf_malloc("%s%s%s", dev_names, sep, dev_name);
            pa_xfree(dev_names);
            dev_names = tmp;
        }
    }

    return dev_names;
}

PA_UNUSED static char *devset_description(pa_idxset *devices, const char *sep) {
    int i = 0;
    int num = pa_idxset_size(devices);
    pa_alsa_ucm_device *sorted[num], *dev;
    char *dev_descs = NULL;
    char *tmp = NULL;
    uint32_t idx;

    PA_IDXSET_FOREACH(dev, devices, idx) {
        sorted[i] = dev;
        i++;
    }

    /* Sort by alphabetical order to match devset_name() */
    qsort(&sorted[0], num, sizeof(pa_alsa_ucm_device *), pa_alsa_ucm_device_cmp);

    for (i = 0; i < num; i++) {
        dev = sorted[i];
        const char *dev_desc = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);

        if (!dev_descs) {
            dev_descs = pa_xstrdup(dev_desc);
        } else {
            tmp = pa_sprintf_malloc("%s%s%s", dev_descs, sep, dev_desc);
            pa_xfree(dev_descs);
            dev_descs = tmp;
        }
    }

    return dev_descs;
}

/* If invert is true, uses the formula 1/p = 1/p1 + 1/p2 + ... 1/pn.
 * This way, the result will always be less than the individual components,
 * yet higher components will lead to higher result. */
static unsigned devset_playback_priority(pa_idxset *devices, bool invert) {
    pa_alsa_ucm_device *dev;
    uint32_t idx;
    double priority = 0;

    PA_IDXSET_FOREACH(dev, devices, idx) {
        if (dev->playback_priority > 0 && invert)
            priority += 1.0 / dev->playback_priority;
        else
            priority += dev->playback_priority;
    }

    if (priority > 0 && invert)
        return 1.0 / priority;

    return (unsigned) priority;
}

static unsigned devset_capture_priority(pa_idxset *devices, bool invert) {
    pa_alsa_ucm_device *dev;
    uint32_t idx;
    double priority = 0;

    PA_IDXSET_FOREACH(dev, devices, idx) {
        if (dev->capture_priority > 0 && invert)
            priority += 1.0 / dev->capture_priority;
        else
            priority += dev->capture_priority;
    }

    if (priority > 0 && invert)
        return 1.0 / priority;

    return (unsigned) priority;
}

void pa_alsa_ucm_add_port(
        pa_hashmap *hash,
        pa_alsa_ucm_mapping_context *context,
        bool is_sink,
        pa_hashmap *ports,
        pa_card_profile *cp,
        pa_core *core) {

    pa_device_port *port;
    unsigned priority;
    char *name, *desc;
    const char *dev_name;
    const char *direction;
    const char *verb_name;
    pa_alsa_ucm_device *dev;
    pa_alsa_ucm_port_data *data;
    pa_alsa_ucm_volume *vol;
    pa_alsa_jack *jack;
    pa_device_port_type_t type;
    void *state;

    dev = context->ucm_device;
    if (!dev)
        return;

    dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
    name = pa_sprintf_malloc("%s%s", is_sink ? PA_UCM_PRE_TAG_OUTPUT : PA_UCM_PRE_TAG_INPUT, dev_name);
    desc = pa_xstrdup(pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_DESCRIPTION));
    priority = is_sink ? dev->playback_priority : dev->capture_priority;
    jack = ucm_get_jack(context->ucm, dev);
    type = dev->type;

    port = pa_hashmap_get(ports, name);
    if (!port) {
        pa_device_port_new_data port_data;

        pa_device_port_new_data_init(&port_data);
        pa_device_port_new_data_set_name(&port_data, name);
        pa_device_port_new_data_set_description(&port_data, desc);
        pa_device_port_new_data_set_type(&port_data, type);
        pa_device_port_new_data_set_direction(&port_data, is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT);
        if (jack)
            pa_device_port_new_data_set_availability_group(&port_data, jack->name);

        port = pa_device_port_new(core, &port_data, sizeof(pa_alsa_ucm_port_data));
        pa_device_port_new_data_done(&port_data);

        data = PA_DEVICE_PORT_DATA(port);
        ucm_port_data_init(data, context->ucm, port, dev);
        port->impl_free = ucm_port_data_free;

        pa_hashmap_put(ports, port->name, port);
        pa_log_debug("Add port %s: %s", port->name, port->description);

        PA_HASHMAP_FOREACH_KV(verb_name, vol, is_sink ? dev->playback_volumes : dev->capture_volumes, state) {
            pa_alsa_path *path = pa_alsa_path_synthesize(vol->mixer_elem,
                                                         is_sink ? PA_ALSA_DIRECTION_OUTPUT : PA_ALSA_DIRECTION_INPUT);

            if (!path)
                pa_log_warn("Failed to set up volume control: %s", vol->mixer_elem);
            else {
                if (vol->master_elem) {
                    pa_alsa_element *e = pa_alsa_element_get(path, vol->master_elem, false);
                    e->switch_use = PA_ALSA_SWITCH_MUTE;
                    e->volume_use = PA_ALSA_VOLUME_MERGE;
                }

                pa_hashmap_put(data->paths, pa_xstrdup(verb_name), path);

                /* Add path also to already created empty path set */
                if (is_sink)
                    pa_hashmap_put(dev->playback_mapping->output_path_set->paths, pa_xstrdup(vol->mixer_elem), path);
                else
                    pa_hashmap_put(dev->capture_mapping->input_path_set->paths, pa_xstrdup(vol->mixer_elem), path);
            }
        }
    }

    port->priority = priority;

    pa_xfree(name);
    pa_xfree(desc);

    direction = is_sink ? "output" : "input";
    pa_log_debug("Port %s direction %s, priority %d", port->name, direction, priority);

    if (cp) {
        pa_log_debug("Adding profile %s to port %s.", cp->name, port->name);
        pa_hashmap_put(port->profiles, cp->name, cp);
    }

    if (hash) {
        pa_hashmap_put(hash, port->name, port);
        pa_device_port_ref(port);
    }

    /* ELD devices */
    set_eld_devices(ports);
}

static bool devset_supports_device(pa_idxset *devices, pa_alsa_ucm_device *dev) {
    const char *sink, *sink2, *source, *source2;
    pa_alsa_ucm_device *d;
    uint32_t idx;

    pa_assert(devices);
    pa_assert(dev);

    /* Can add anything to empty group */
    if (pa_idxset_isempty(devices))
        return true;

    /* Device already selected */
    if (pa_idxset_contains(devices, dev))
        return true;

    /* No conflicting device must already be selected */
    if (!pa_idxset_isdisjoint(devices, dev->conflicting_devices))
        return false;

    /* No already selected device must be unsupported */
    if (!pa_idxset_isempty(dev->supported_devices))
        if (!pa_idxset_issubset(devices, dev->supported_devices))
           return false;

    sink = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SINK);
    source = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SOURCE);

    PA_IDXSET_FOREACH(d, devices, idx) {
        /* Must not be unsupported by any selected device */
        if (!pa_idxset_isempty(d->supported_devices))
            if (!pa_idxset_contains(d->supported_devices, dev))
                return false;

        /* PlaybackPCM must not be the same as any selected device */
        sink2 = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_SINK);
        if (sink && sink2 && pa_streq(sink, sink2))
            return false;

        /* CapturePCM must not be the same as any selected device */
        source2 = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_SOURCE);
        if (source && source2 && pa_streq(source, source2))
            return false;
    }

    return true;
}

/* Iterates nonempty subsets of UCM devices that can be simultaneously
 * used, including subsets of previously returned subsets. At start,
 * *state should be NULL. It's not safe to modify the devices argument
 * until iteration ends. The returned idxsets must be freed by the
 * caller. */
static pa_idxset *iterate_device_subsets(pa_idxset *devices, void **state) {
    uint32_t idx;
    pa_alsa_ucm_device *dev;

    pa_assert(devices);
    pa_assert(state);

    if (*state == NULL) {
        /* First iteration, start adding from first device */
        *state = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
        dev = pa_idxset_first(devices, &idx);

    } else {
        /* Backtrack the most recent device we added and skip it */
        dev = pa_idxset_steal_last(*state, NULL);
        pa_idxset_get_by_data(devices, dev, &idx);
        if (dev)
            dev = pa_idxset_next(devices, &idx);
    }

    /* Try adding devices we haven't decided on yet */
    for (; dev; dev = pa_idxset_next(devices, &idx)) {
        if (devset_supports_device(*state, dev))
            pa_idxset_put(*state, dev, NULL);
    }

    if (pa_idxset_isempty(*state)) {
        /* No more choices to backtrack on, therefore no more subsets to
         * return after this. Don't return the empty set, instead clean
         * up and end iteration. */
        pa_idxset_free(*state, NULL);
        *state = NULL;
        return NULL;
    }

    return pa_idxset_copy(*state, NULL);
}

/* This a wrapper around iterate_device_subsets() that only returns the
 * biggest possible groups and not any of their subsets. */
static pa_idxset *iterate_maximal_device_subsets(pa_idxset *devices, void **state) {
    uint32_t idx;
    pa_alsa_ucm_device *dev;
    pa_idxset *subset;

    pa_assert(devices);
    pa_assert(state);

    subset = iterate_device_subsets(devices, state);
    if (!subset)
        return subset;

    /* Skip this group if it's incomplete, by checking if we can add any
     * other device. If we can, this iteration is a subset of another
     * group that we already returned or eventually return. */
    PA_IDXSET_FOREACH(dev, devices, idx) {
        if (!pa_idxset_contains(subset, dev) && devset_supports_device(subset, dev)) {
            pa_idxset_free(subset, NULL);
            return iterate_maximal_device_subsets(devices, state);
        }
    }

    return subset;
}

static char* merge_roles(const char *cur, const char *add) {
    char *r, *ret;
    const char *state = NULL;

    if (add == NULL)
        return pa_xstrdup(cur);
    else if (cur == NULL)
        return pa_xstrdup(add);

    ret = pa_xstrdup(cur);

    while ((r = pa_split_spaces(add, &state))) {
        char *value;

        if (!pa_str_in_list_spaces(ret, r))
            value = pa_sprintf_malloc("%s %s", ret, r);
        else {
            pa_xfree(r);
            continue;
        }

        pa_xfree(ret);
        ret = value;
        pa_xfree(r);
    }

    return ret;
}

void pa_alsa_ucm_add_ports(
        pa_hashmap **p,
        pa_proplist *proplist,
        pa_alsa_ucm_mapping_context *context,
        bool is_sink,
        pa_card *card,
        snd_pcm_t *pcm_handle,
        bool ignore_dB) {

    char *merged_roles;
    const char *role_name = is_sink ? PA_ALSA_PROP_UCM_PLAYBACK_ROLES : PA_ALSA_PROP_UCM_CAPTURE_ROLES;
    pa_alsa_ucm_device *dev;
    pa_alsa_ucm_modifier *mod;
    char *tmp;

    pa_assert(p);
    pa_assert(*p);

    /* add ports first */
    pa_alsa_ucm_add_port(*p, context, is_sink, card->ports, NULL, card->core);

    /* now set up volume paths if any */
    probe_volumes(*p, is_sink, pcm_handle, context->ucm->mixers, ignore_dB);

    /* probe_volumes() removes per-verb paths from ports if probing them
     * fails. The path for the current verb is cached in
     * pa_alsa_ucm_port_data.path, which is not cleared by probe_volumes() if
     * the path gets removed, so we have to call update_mixer_paths() here to
     * unset the cached path if needed. */
    if (context->ucm->active_verb) {
        const char *verb_name;
        verb_name = pa_proplist_gets(context->ucm->active_verb->proplist, PA_ALSA_PROP_UCM_NAME);
        update_mixer_paths(*p, verb_name);
    }

    /* then set property PA_PROP_DEVICE_INTENDED_ROLES */
    merged_roles = pa_xstrdup(pa_proplist_gets(proplist, PA_PROP_DEVICE_INTENDED_ROLES));

    dev = context->ucm_device;
    if (dev) {
        const char *roles = pa_proplist_gets(dev->proplist, role_name);
        tmp = merge_roles(merged_roles, roles);
        pa_xfree(merged_roles);
        merged_roles = tmp;
    }

    mod = context->ucm_modifier;
    if (mod) {
        tmp = merge_roles(merged_roles, mod->media_role);
        pa_xfree(merged_roles);
        merged_roles = tmp;
    }

    if (merged_roles)
        pa_proplist_sets(proplist, PA_PROP_DEVICE_INTENDED_ROLES, merged_roles);

    pa_log_info("ALSA device %s roles: %s", pa_proplist_gets(proplist, PA_PROP_DEVICE_STRING), pa_strnull(merged_roles));
    pa_xfree(merged_roles);
}

/* Change UCM verb and device to match selected card profile */
int pa_alsa_ucm_set_profile(pa_alsa_ucm_config *ucm, pa_card *card, pa_alsa_profile *new_profile, pa_alsa_profile *old_profile) {
    int ret = 0;
    const char *verb_name, *profile_name;
    pa_alsa_ucm_verb *verb;
    pa_alsa_mapping *map;
    uint32_t idx;

    if (new_profile == old_profile)
        return 0;

    if (new_profile == NULL) {
        verb = NULL;
        profile_name = SND_USE_CASE_VERB_INACTIVE;
        verb_name = SND_USE_CASE_VERB_INACTIVE;
    } else {
        verb = new_profile->ucm_context.verb;
        profile_name = new_profile->name;
        verb_name = pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME);
    }

    pa_log_info("Set profile to %s", profile_name);
    if (ucm->active_verb != verb) {
        /* change verb */
        pa_log_info("Set UCM verb to %s", verb_name);
        if ((snd_use_case_set(ucm->ucm_mgr, "_verb", verb_name)) < 0) {
            pa_log("Failed to set verb %s", verb_name);
            ret = -1;
        }

    } else if (ucm->active_verb) {
        /* Disable modifiers not in new profile. Has to be done before
         * devices, because _dismod fails if a modifier's supported
         * devices are disabled. */
        PA_IDXSET_FOREACH(map, old_profile->input_mappings, idx)
            if (new_profile && !pa_idxset_contains(new_profile->input_mappings, map))
                if (map->ucm_context.ucm_modifier && ucm_modifier_disable(ucm, map->ucm_context.ucm_modifier) < 0)
                    ret = -1;

        PA_IDXSET_FOREACH(map, old_profile->output_mappings, idx)
            if (new_profile && !pa_idxset_contains(new_profile->output_mappings, map))
                if (map->ucm_context.ucm_modifier && ucm_modifier_disable(ucm, map->ucm_context.ucm_modifier) < 0)
                    ret = -1;

        /* Disable devices not in new profile */
        PA_IDXSET_FOREACH(map, old_profile->input_mappings, idx)
            if (new_profile && !pa_idxset_contains(new_profile->input_mappings, map))
                if (map->ucm_context.ucm_device && ucm_device_disable(ucm, map->ucm_context.ucm_device) < 0)
                    ret = -1;

        PA_IDXSET_FOREACH(map, old_profile->output_mappings, idx)
            if (new_profile && !pa_idxset_contains(new_profile->output_mappings, map))
                if (map->ucm_context.ucm_device && ucm_device_disable(ucm, map->ucm_context.ucm_device) < 0)
                    ret = -1;
    }
    ucm->active_verb = verb;

    update_mixer_paths(card->ports, verb_name);

    return ret;
}

int pa_alsa_ucm_set_port(pa_alsa_ucm_mapping_context *context, pa_device_port *port) {
    pa_alsa_ucm_config *ucm;
    pa_alsa_ucm_device *dev;
    pa_alsa_ucm_port_data *data;
    const char *dev_name, *ucm_dev_name;

    pa_assert(context && context->ucm);

    ucm = context->ucm;
    pa_assert(ucm->ucm_mgr);

    data = PA_DEVICE_PORT_DATA(port);
    dev = data->device;
    pa_assert(dev);

    if (context->ucm_device) {
        dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
        ucm_dev_name = pa_proplist_gets(context->ucm_device->proplist, PA_ALSA_PROP_UCM_NAME);
        if (!pa_streq(dev_name, ucm_dev_name)) {
            pa_log_error("Failed to set port %s with wrong UCM context: %s", dev_name, ucm_dev_name);
            return -1;
        }
    }

    return ucm_device_enable(ucm, dev);
}

static void ucm_add_mapping(pa_alsa_profile *p, pa_alsa_mapping *m) {

    pa_alsa_path_set *ps;

    /* create empty path set for the future path additions */
    ps = pa_xnew0(pa_alsa_path_set, 1);
    ps->direction = m->direction;
    ps->paths = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);

    switch (m->direction) {
        case PA_ALSA_DIRECTION_ANY:
            pa_idxset_put(p->output_mappings, m, NULL);
            pa_idxset_put(p->input_mappings, m, NULL);
            m->output_path_set = ps;
            m->input_path_set = ps;
            break;
        case PA_ALSA_DIRECTION_OUTPUT:
            pa_idxset_put(p->output_mappings, m, NULL);
            m->output_path_set = ps;
            break;
        case PA_ALSA_DIRECTION_INPUT:
            pa_idxset_put(p->input_mappings, m, NULL);
            m->input_path_set = ps;
            break;
    }
}

static void alsa_mapping_add_ucm_device(pa_alsa_mapping *m, pa_alsa_ucm_device *device) {
    char *cur_desc;
    const char *new_desc, *mdev;
    bool is_sink = m->direction == PA_ALSA_DIRECTION_OUTPUT;

    m->ucm_context.ucm_device = device;

    new_desc = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);
    cur_desc = m->description;
    if (cur_desc)
        m->description = pa_sprintf_malloc("%s + %s", cur_desc, new_desc);
    else
        m->description = pa_xstrdup(new_desc);
    pa_xfree(cur_desc);

    /* walk around null case */
    m->description = m->description ? m->description : pa_xstrdup("");

    /* save mapping to ucm device */
    if (is_sink)
        device->playback_mapping = m;
    else
        device->capture_mapping = m;

    mdev = get_mixer_device(device, is_sink);
    if (mdev)
        pa_proplist_sets(m->proplist, "alsa.mixer_device", mdev);
}

static void alsa_mapping_add_ucm_modifier(pa_alsa_mapping *m, pa_alsa_ucm_modifier *modifier) {
    char *cur_desc;
    const char *new_desc, *mod_name, *channel_str;
    uint32_t channels = 0;

    m->ucm_context.ucm_modifier = modifier;

    new_desc = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);
    cur_desc = m->description;
    if (cur_desc)
        m->description = pa_sprintf_malloc("%s + %s", cur_desc, new_desc);
    else
        m->description = pa_xstrdup(new_desc);
    pa_xfree(cur_desc);

    m->description = m->description ? m->description : pa_xstrdup("");

    /* Modifier sinks should not be routed to by default */
    m->priority = 0;

    mod_name = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_NAME);
    pa_proplist_sets(m->proplist, PA_ALSA_PROP_UCM_MODIFIER, mod_name);

    /* save mapping to ucm modifier */
    if (m->direction == PA_ALSA_DIRECTION_OUTPUT) {
        modifier->playback_mapping = m;
        channel_str = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS);
    } else {
        modifier->capture_mapping = m;
        channel_str = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_CAPTURE_CHANNELS);
    }

    if (channel_str) {
        /* FIXME: channel_str is unsanitized input from the UCM configuration,
         * we should do proper error handling instead of asserting.
         * https://bugs.freedesktop.org/show_bug.cgi?id=71823 */
        pa_assert_se(pa_atou(channel_str, &channels) == 0 && pa_channels_valid(channels));
        pa_log_debug("Got channel count %" PRIu32 " for modifier", channels);
    }

    if (channels)
        pa_channel_map_init_extend(&m->channel_map, channels, PA_CHANNEL_MAP_ALSA);
    else
        pa_channel_map_init(&m->channel_map);
}

static pa_alsa_mapping* ucm_alsa_mapping_get(pa_alsa_ucm_config *ucm, pa_alsa_profile_set *ps, const char *verb_name, const char *ucm_name, bool is_sink) {
    pa_alsa_mapping *m;
    char *mapping_name;

    mapping_name = pa_sprintf_malloc("Mapping %s: %s: %s", verb_name, ucm_name, is_sink ? "sink" : "source");

    m = pa_alsa_mapping_get(ps, mapping_name);

    if (!m)
        pa_log("No mapping for %s", mapping_name);

    pa_xfree(mapping_name);

    return m;
}

static int ucm_create_mapping_direction(
        pa_alsa_ucm_config *ucm,
        pa_alsa_profile_set *ps,
        pa_alsa_ucm_device *device,
        const char *verb_name,
        const char *device_name,
        const char *device_str,
        bool is_sink) {

    pa_alsa_mapping *m;
    unsigned priority, rate, channels;

    m = ucm_alsa_mapping_get(ucm, ps, verb_name, device_name, is_sink);

    if (!m)
        return -1;

    pa_log_debug("UCM mapping: %s dev %s", m->name, device_name);

    priority = is_sink ? device->playback_priority : device->capture_priority;
    rate = is_sink ? device->playback_rate : device->capture_rate;
    channels = is_sink ? device->playback_channels : device->capture_channels;

    if (!m->ucm_context.ucm_device) {   /* new mapping */
        m->ucm_context.ucm = ucm;
        m->ucm_context.direction = is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT;

        m->device_strings = pa_xnew0(char*, 2);
        m->device_strings[0] = pa_xstrdup(device_str);
        m->direction = is_sink ? PA_ALSA_DIRECTION_OUTPUT : PA_ALSA_DIRECTION_INPUT;

        if (rate)
            m->sample_spec.rate = rate;
        pa_channel_map_init_extend(&m->channel_map, channels, PA_CHANNEL_MAP_ALSA);
    }

    /* mapping priority is the highest one of ucm devices */
    if (priority > m->priority)
        m->priority = priority;

    /* mapping channels is the lowest one of ucm devices */
    if (channels < m->channel_map.channels)
        pa_channel_map_init_extend(&m->channel_map, channels, PA_CHANNEL_MAP_ALSA);

    alsa_mapping_add_ucm_device(m, device);

    return 0;
}

static int ucm_create_mapping_for_modifier(
        pa_alsa_ucm_config *ucm,
        pa_alsa_profile_set *ps,
        pa_alsa_ucm_modifier *modifier,
        const char *verb_name,
        const char *mod_name,
        const char *device_str,
        bool is_sink) {

    pa_alsa_mapping *m;

    m = ucm_alsa_mapping_get(ucm, ps, verb_name, mod_name, is_sink);

    if (!m)
        return -1;

    pa_log_info("UCM mapping: %s modifier %s", m->name, mod_name);

    if (!m->ucm_context.ucm_device && !m->ucm_context.ucm_modifier) {   /* new mapping */
        m->ucm_context.ucm = ucm;
        m->ucm_context.direction = is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT;

        m->device_strings = pa_xnew0(char*, 2);
        m->device_strings[0] = pa_xstrdup(device_str);
        m->direction = is_sink ? PA_ALSA_DIRECTION_OUTPUT : PA_ALSA_DIRECTION_INPUT;
        /* Modifier sinks should not be routed to by default */
        m->priority = 0;
    }

    alsa_mapping_add_ucm_modifier(m, modifier);

    return 0;
}

static int ucm_create_mapping(
        pa_alsa_ucm_config *ucm,
        pa_alsa_profile_set *ps,
        pa_alsa_ucm_device *device,
        const char *verb_name,
        const char *device_name,
        const char *sink,
        const char *source) {

    int ret = 0;

    if (!sink && !source) {
        pa_log("No sink and source at %s: %s", verb_name, device_name);
        return -1;
    }

    if (sink)
        ret = ucm_create_mapping_direction(ucm, ps, device, verb_name, device_name, sink, true);
    if (ret == 0 && source)
        ret = ucm_create_mapping_direction(ucm, ps, device, verb_name, device_name, source, false);

    return ret;
}

static pa_alsa_jack* ucm_get_jack(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *device) {
    pa_alsa_jack *j;
    const char *device_name;
    const char *jack_control;
    const char *mixer_device_name;
    char *name;

    pa_assert(ucm);
    pa_assert(device);

    device_name = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_NAME);

    jack_control = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_JACK_CONTROL);
    if (jack_control) {
#if SND_LIB_VERSION >= 0x10201
        snd_ctl_elem_id_t *ctl;
        int err, index;
        snd_ctl_elem_id_alloca(&ctl);
        err = snd_use_case_parse_ctl_elem_id(ctl, "JackControl", jack_control);
        if (err < 0)
            return NULL;
        jack_control = snd_ctl_elem_id_get_name(ctl);
        index = snd_ctl_elem_id_get_index(ctl);
        if (index > 0) {
            pa_log("[%s] Invalid JackControl index value: \"%s\",%d", device_name, jack_control, index);
            return NULL;
        }
#else
#warning "Upgrade to alsa-lib 1.2.1!"
#endif
        if (!pa_endswith(jack_control, " Jack")) {
            pa_log("[%s] Invalid JackControl value: \"%s\"", device_name, jack_control);
            return NULL;
        }

        /* pa_alsa_jack_new() expects a jack name without " Jack" at the
         * end, so drop the trailing " Jack". */
        name = pa_xstrndup(jack_control, strlen(jack_control) - 5);
    } else {
        /* The jack control hasn't been explicitly configured, fail. */
        return NULL;
    }

    PA_LLIST_FOREACH(j, ucm->jacks)
        if (pa_streq(j->name, name))
            goto finish;

    mixer_device_name = get_jack_mixer_device(device, true);
    if (!mixer_device_name)
        mixer_device_name = get_jack_mixer_device(device, false);
    if (!mixer_device_name) {
        pa_log("[%s] No mixer device name for JackControl \"%s\"", device_name, jack_control);
        return NULL;
    }
    j = pa_alsa_jack_new(NULL, mixer_device_name, name, 0);
    PA_LLIST_PREPEND(pa_alsa_jack, ucm->jacks, j);

finish:
    pa_xfree(name);

    return j;
}

static int ucm_create_profile(
        pa_alsa_ucm_config *ucm,
        pa_alsa_profile_set *ps,
        pa_alsa_ucm_verb *verb,
        pa_idxset *mappings,
        const char *profile_name,
        const char *profile_desc,
        unsigned int profile_priority) {

    pa_alsa_profile *p;
    pa_alsa_mapping *map;
    uint32_t idx;

    pa_assert(ps);

    if (pa_hashmap_get(ps->profiles, profile_name)) {
        pa_log("Profile %s already exists", profile_name);
        return -1;
    }

    p = pa_xnew0(pa_alsa_profile, 1);
    p->profile_set = ps;
    p->name = pa_xstrdup(profile_name);
    p->description = pa_xstrdup(profile_desc);
    p->priority = profile_priority;
    p->ucm_context.verb = verb;

    p->output_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
    p->input_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);

    p->supported = true;
    pa_hashmap_put(ps->profiles, p->name, p);

    PA_IDXSET_FOREACH(map, mappings, idx)
        ucm_add_mapping(p, map);

    pa_alsa_profile_dump(p);

    return 0;
}

static int ucm_create_verb_profiles(
        pa_alsa_ucm_config *ucm,
        pa_alsa_profile_set *ps,
        pa_alsa_ucm_verb *verb,
        const char *verb_name,
        const char *verb_desc) {

    pa_idxset *verb_devices, *p_devices, *p_mappings;
    pa_alsa_ucm_device *dev;
    pa_alsa_ucm_modifier *mod;
    int i = 0;
    int n_profiles = 0;
    const char *name, *sink, *source;
    char *p_name, *p_desc, *tmp;
    unsigned int verb_priority, p_priority;
    uint32_t idx;
    void *state = NULL;

    /* TODO: get profile priority from policy management */
    verb_priority = verb->priority;

    if (verb_priority == 0) {
        char *verb_cmp, *c;
        c = verb_cmp = pa_xstrdup(verb_name);
        while (*c) {
            if (*c == '_') *c = ' ';
            c++;
        }
        for (i = 0; verb_info[i].id; i++) {
            if (strcasecmp(verb_info[i].id, verb_cmp) == 0) {
                verb_priority = verb_info[i].priority;
                break;
            }
        }
        pa_xfree(verb_cmp);
    }

    PA_LLIST_FOREACH(dev, verb->devices) {
        pa_alsa_jack *jack;
        const char *jack_hw_mute;

        name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);

        sink = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SINK);
        source = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SOURCE);

        ucm_create_mapping(ucm, ps, dev, verb_name, name, sink, source);

        jack = ucm_get_jack(ucm, dev);
        if (jack)
            device_set_jack(dev, jack);

        /* JackHWMute contains a list of device names. Each listed device must
         * be associated with the jack object that we just created. */
        jack_hw_mute = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_JACK_HW_MUTE);
        if (jack_hw_mute && !jack) {
            pa_log("[%s] JackHWMute set, but JackControl is missing", name);
            jack_hw_mute = NULL;
        }
        if (jack_hw_mute) {
            char *hw_mute_device_name;
            const char *state = NULL;

            while ((hw_mute_device_name = ucm_split_devnames(jack_hw_mute, &state))) {
                pa_alsa_ucm_verb *verb2;
                bool device_found = false;

                /* Search the referenced device from all verbs. If there are
                 * multiple verbs that have a device with this name, we add the
                 * hw mute association to each of those devices. */
                PA_LLIST_FOREACH(verb2, ucm->verbs) {
                    pa_alsa_ucm_device *hw_mute_device;

                    hw_mute_device = verb_find_device(verb2, hw_mute_device_name);
                    if (hw_mute_device) {
                        device_found = true;
                        device_add_hw_mute_jack(hw_mute_device, jack);
                    }
                }

                if (!device_found)
                    pa_log("[%s] JackHWMute references an unknown device: %s", name, hw_mute_device_name);

                pa_xfree(hw_mute_device_name);
            }
        }
    }

    /* Now find modifiers that have their own PlaybackPCM and create
     * separate sinks for them. */
    PA_LLIST_FOREACH(mod, verb->modifiers) {
        name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);

        sink = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_SINK);
        source = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_SOURCE);

        if (sink)
            ucm_create_mapping_for_modifier(ucm, ps, mod, verb_name, name, sink, true);
        else if (source)
            ucm_create_mapping_for_modifier(ucm, ps, mod, verb_name, name, source, false);
    }

    verb_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
    PA_LLIST_FOREACH(dev, verb->devices)
        pa_idxset_put(verb_devices, dev, NULL);

    while ((p_devices = iterate_maximal_device_subsets(verb_devices, &state))) {
        p_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);

        /* Add the mappings that include our selected devices */
        PA_IDXSET_FOREACH(dev, p_devices, idx) {
            if (dev->playback_mapping)
                pa_idxset_put(p_mappings, dev->playback_mapping, NULL);
            if (dev->capture_mapping)
                pa_idxset_put(p_mappings, dev->capture_mapping, NULL);
        }

        /* Add mappings only for the modifiers that can work with our
         * device selection */
        PA_LLIST_FOREACH(mod, verb->modifiers)
            if (pa_idxset_isempty(mod->supported_devices) || pa_idxset_issubset(mod->supported_devices, p_devices))
                if (pa_idxset_isdisjoint(mod->conflicting_devices, p_devices)) {
                    if (mod->playback_mapping)
                        pa_idxset_put(p_mappings, mod->playback_mapping, NULL);
                    if (mod->capture_mapping)
                        pa_idxset_put(p_mappings, mod->capture_mapping, NULL);
                }

        /* If we'll have multiple profiles for this verb, their names
         * must be unique. Use a list of chosen devices to disambiguate
         * them. If the profile contains all devices of a verb, we'll
         * generate only onle profile whose name should be the verb
         * name. GUIs usually show the profile description instead of
         * the name, add the device names to those as well. */
        tmp = devset_name(p_devices, ", ");
        if (pa_idxset_equals(p_devices, verb_devices)) {
            p_name = pa_xstrdup(verb_name);
            p_desc = pa_xstrdup(verb_desc);
        } else {
            p_name = pa_sprintf_malloc("%s (%s)", verb_name, tmp);
            p_desc = pa_sprintf_malloc("%s (%s)", verb_desc, tmp);
        }

        /* Make sure profiles with higher-priority devices are
         * prioritized. */
        p_priority = verb_priority + devset_playback_priority(p_devices, false) + devset_capture_priority(p_devices, false);

        if (ucm_create_profile(ucm, ps, verb, p_mappings, p_name, p_desc, p_priority) == 0) {
            pa_log_debug("Created profile %s for UCM verb %s", p_name, verb_name);
            n_profiles++;
        }

        pa_xfree(tmp);
        pa_xfree(p_name);
        pa_xfree(p_desc);
        pa_idxset_free(p_mappings, NULL);
        pa_idxset_free(p_devices, NULL);
    }

    pa_idxset_free(verb_devices, NULL);

    if (n_profiles == 0) {
        pa_log("UCM verb %s created no profiles", verb_name);
        return -1;
    }

    return 0;
}

static void mapping_init_eld(pa_alsa_mapping *m, snd_pcm_t *pcm)
{
    pa_alsa_ucm_mapping_context *context = &m->ucm_context;
    pa_alsa_ucm_device *dev;
    char *mdev, *alib_prefix;
    snd_pcm_info_t *info;
    int pcm_card, pcm_device;

    snd_pcm_info_alloca(&info);
    if (snd_pcm_info(pcm, info) < 0)
        return;

    if ((pcm_card = snd_pcm_info_get_card(info)) < 0)
        return;
    if ((pcm_device = snd_pcm_info_get_device(info)) < 0)
        return;

    alib_prefix = context->ucm->alib_prefix;

    dev = context->ucm_device;
    mdev = pa_sprintf_malloc("%shw:%i", alib_prefix ? alib_prefix : "", pcm_card);
    if (mdev == NULL)
        return;
    dev->eld_mixer_device_name = mdev;
    dev->eld_device = pcm_device;
}

static snd_pcm_t* mapping_open_pcm(pa_alsa_ucm_config *ucm, pa_alsa_mapping *m, int mode) {
    snd_pcm_t* pcm;
    pa_sample_spec try_ss = ucm->core->default_sample_spec;
    pa_channel_map try_map;
    snd_pcm_uframes_t try_period_size, try_buffer_size;
    bool exact_channels = m->channel_map.channels > 0;

    if (exact_channels) {
        try_map = m->channel_map;
        try_ss.channels = try_map.channels;
    } else
        pa_channel_map_init_extend(&try_map, try_ss.channels, PA_CHANNEL_MAP_ALSA);

    try_period_size =
        pa_usec_to_bytes(ucm->core->default_fragment_size_msec * PA_USEC_PER_MSEC, &try_ss) /
        pa_frame_size(&try_ss);
    try_buffer_size = ucm->core->default_n_fragments * try_period_size;

    pcm = pa_alsa_open_by_device_string(m->device_strings[0], NULL, &try_ss,
            &try_map, mode, &try_period_size, &try_buffer_size, 0, NULL, NULL, NULL, NULL, exact_channels);

    if (pcm) {
        if (!exact_channels)
            m->channel_map = try_map;
        mapping_init_eld(m, pcm);
    }

    return pcm;
}

static void profile_finalize_probing(pa_alsa_profile *p) {
    pa_alsa_mapping *m;
    uint32_t idx;

    PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
        if (p->supported)
            m->supported++;

        if (!m->output_pcm)
            continue;

        snd_pcm_close(m->output_pcm);
        m->output_pcm = NULL;
    }

    PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
        if (p->supported)
            m->supported++;

        if (!m->input_pcm)
            continue;

        snd_pcm_close(m->input_pcm);
        m->input_pcm = NULL;
    }
}

static void ucm_mapping_jack_probe(pa_alsa_mapping *m, pa_hashmap *mixers) {
    snd_mixer_t *mixer_handle;
    pa_alsa_ucm_mapping_context *context = &m->ucm_context;
    pa_alsa_ucm_device *dev;
    bool has_control;

    dev = context->ucm_device;
    if (!dev->jack || !dev->jack->mixer_device_name)
        return;

    mixer_handle = pa_alsa_open_mixer_by_name(mixers, dev->jack->mixer_device_name, true);
    if (!mixer_handle) {
        pa_log_error("Unable to determine open mixer device '%s' for jack %s", dev->jack->mixer_device_name, dev->jack->name);
        return;
    }

    has_control = pa_alsa_mixer_find_card(mixer_handle, &dev->jack->alsa_id, 0) != NULL;
    pa_alsa_jack_set_has_control(dev->jack, has_control);
    pa_log_info("UCM jack %s has_control=%d", dev->jack->name, dev->jack->has_control);
}

static void ucm_probe_profile_set(pa_alsa_ucm_config *ucm, pa_alsa_profile_set *ps) {
    void *state;
    pa_alsa_profile *p;
    pa_alsa_mapping *m;
    const char *verb_name;
    uint32_t idx;

    PA_HASHMAP_FOREACH(p, ps->profiles, state) {
        pa_log_info("Probing profile %s", p->name);

        /* change verb */
        verb_name = pa_proplist_gets(p->ucm_context.verb->proplist, PA_ALSA_PROP_UCM_NAME);
        pa_log_info("Set ucm verb to %s", verb_name);

        if ((snd_use_case_set(ucm->ucm_mgr, "_verb", verb_name)) < 0) {
            pa_log("Failed to set verb %s", verb_name);
            p->supported = false;
            continue;
        }

        PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
            if (PA_UCM_IS_MODIFIER_MAPPING(m)) {
                /* Skip jack probing on modifier PCMs since we expect this to
                 * only be controlled on the main device/verb PCM. */
                continue;
            }

            m->output_pcm = mapping_open_pcm(ucm, m, SND_PCM_STREAM_PLAYBACK);
            if (!m->output_pcm) {
                p->supported = false;
                break;
            }
        }

        if (p->supported) {
            PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
                if (PA_UCM_IS_MODIFIER_MAPPING(m)) {
                    /* Skip jack probing on modifier PCMs since we expect this to
                     * only be controlled on the main device/verb PCM. */
                    continue;
                }

                m->input_pcm = mapping_open_pcm(ucm, m, SND_PCM_STREAM_CAPTURE);
                if (!m->input_pcm) {
                    p->supported = false;
                    break;
                }
            }
        }

        if (!p->supported) {
            profile_finalize_probing(p);
            continue;
        }

        pa_log_debug("Profile %s supported.", p->name);

        PA_IDXSET_FOREACH(m, p->output_mappings, idx)
            if (!PA_UCM_IS_MODIFIER_MAPPING(m))
                ucm_mapping_jack_probe(m, ucm->mixers);

        PA_IDXSET_FOREACH(m, p->input_mappings, idx)
            if (!PA_UCM_IS_MODIFIER_MAPPING(m))
                ucm_mapping_jack_probe(m, ucm->mixers);

        profile_finalize_probing(p);
    }

    /* restore ucm state */
    snd_use_case_set(ucm->ucm_mgr, "_verb", SND_USE_CASE_VERB_INACTIVE);

    pa_alsa_profile_set_drop_unsupported(ps);
}

pa_alsa_profile_set* pa_alsa_ucm_add_profile_set(pa_alsa_ucm_config *ucm, pa_channel_map *default_channel_map) {
    pa_alsa_ucm_verb *verb;
    pa_alsa_profile_set *ps;

    ps = pa_xnew0(pa_alsa_profile_set, 1);
    ps->mappings = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
    ps->profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
    ps->decibel_fixes = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);

    /* create profiles for each verb */
    PA_LLIST_FOREACH(verb, ucm->verbs) {
        const char *verb_name;
        const char *verb_desc;

        verb_name = pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME);
        verb_desc = pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);
        if (verb_name == NULL) {
            pa_log("Verb with no name");
            continue;
        }

        ucm_create_verb_profiles(ucm, ps, verb, verb_name, verb_desc);
    }

    ucm_probe_profile_set(ucm, ps);
    ps->probed = true;

    return ps;
}

static void free_verb(pa_alsa_ucm_verb *verb) {
    pa_alsa_ucm_device *di, *dn;
    pa_alsa_ucm_modifier *mi, *mn;

    PA_LLIST_FOREACH_SAFE(di, dn, verb->devices) {
        PA_LLIST_REMOVE(pa_alsa_ucm_device, verb->devices, di);

        if (di->hw_mute_jacks)
            pa_dynarray_free(di->hw_mute_jacks);

        if (di->ucm_ports)
            pa_dynarray_free(di->ucm_ports);

        if (di->playback_volumes)
            pa_hashmap_free(di->playback_volumes);
        if (di->capture_volumes)
            pa_hashmap_free(di->capture_volumes);

        pa_proplist_free(di->proplist);

        pa_idxset_free(di->conflicting_devices, NULL);
        pa_idxset_free(di->supported_devices, NULL);

        pa_xfree(di->eld_mixer_device_name);

        pa_xfree(di);
    }

    PA_LLIST_FOREACH_SAFE(mi, mn, verb->modifiers) {
        PA_LLIST_REMOVE(pa_alsa_ucm_modifier, verb->modifiers, mi);
        pa_proplist_free(mi->proplist);
        pa_idxset_free(mi->conflicting_devices, NULL);
        pa_idxset_free(mi->supported_devices, NULL);
        pa_xfree(mi->media_role);
        pa_xfree(mi);
    }
    pa_proplist_free(verb->proplist);
    pa_xfree(verb);
}

static pa_alsa_ucm_device *verb_find_device(pa_alsa_ucm_verb *verb, const char *device_name) {
    pa_alsa_ucm_device *device;

    pa_assert(verb);
    pa_assert(device_name);

    PA_LLIST_FOREACH(device, verb->devices) {
        const char *name;

        name = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_NAME);
        if (pa_streq(name, device_name))
            return device;
    }

    return NULL;
}

void pa_alsa_ucm_free(pa_alsa_ucm_config *ucm) {
    pa_alsa_ucm_verb *vi, *vn;
    pa_alsa_jack *ji, *jn;

    PA_LLIST_FOREACH_SAFE(vi, vn, ucm->verbs) {
        PA_LLIST_REMOVE(pa_alsa_ucm_verb, ucm->verbs, vi);
        free_verb(vi);
    }
    PA_LLIST_FOREACH_SAFE(ji, jn, ucm->jacks) {
        PA_LLIST_REMOVE(pa_alsa_jack, ucm->jacks, ji);
        pa_alsa_jack_free(ji);
    }
    if (ucm->ucm_mgr) {
        snd_use_case_mgr_close(ucm->ucm_mgr);
        ucm->ucm_mgr = NULL;
    }
    pa_xfree(ucm->alib_prefix);
    ucm->alib_prefix = NULL;
}

void pa_alsa_ucm_mapping_context_free(pa_alsa_ucm_mapping_context *context) {
    pa_alsa_ucm_device *dev;
    pa_alsa_ucm_modifier *mod;

    dev = context->ucm_device;
    if (dev) {
        /* clear ucm device pointer to mapping */
        if (context->direction == PA_DIRECTION_OUTPUT)
            dev->playback_mapping = NULL;
        else
            dev->capture_mapping = NULL;
    }

    mod = context->ucm_modifier;
    if (mod) {
        if (context->direction == PA_DIRECTION_OUTPUT)
            mod->playback_mapping = NULL;
        else
            mod->capture_mapping = NULL;
    }
}

/* Enable the modifier when the first stream with matched role starts */
void pa_alsa_ucm_roled_stream_begin(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
    pa_alsa_ucm_modifier *mod;

    if (!ucm->active_verb)
        return;

    PA_LLIST_FOREACH(mod, ucm->active_verb->modifiers) {
        if ((mod->action_direction == dir) && (pa_streq(mod->media_role, role))) {
            if (mod->enabled_counter == 0) {
                ucm_modifier_enable(ucm, mod);
            }

            mod->enabled_counter++;
            break;
        }
    }
}

/* Disable the modifier when the last stream with matched role ends */
void pa_alsa_ucm_roled_stream_end(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
    pa_alsa_ucm_modifier *mod;

    if (!ucm->active_verb)
        return;

    PA_LLIST_FOREACH(mod, ucm->active_verb->modifiers) {
        if ((mod->action_direction == dir) && (pa_streq(mod->media_role, role))) {

            mod->enabled_counter--;
            if (mod->enabled_counter == 0)
                ucm_modifier_disable(ucm, mod);

            break;
        }
    }
}

static void device_set_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack) {
    pa_assert(device);
    pa_assert(jack);

    device->jack = jack;
    pa_alsa_jack_add_ucm_device(jack, device);

    pa_alsa_ucm_device_update_available(device);
}

static void device_add_hw_mute_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack) {
    pa_assert(device);
    pa_assert(jack);

    pa_dynarray_append(device->hw_mute_jacks, jack);
    pa_alsa_jack_add_ucm_hw_mute_device(jack, device);

    pa_alsa_ucm_device_update_available(device);
}

static void device_set_available(pa_alsa_ucm_device *device, pa_available_t available) {
    pa_alsa_ucm_port_data *port;
    unsigned idx;

    pa_assert(device);

    if (available == device->available)
        return;

    device->available = available;

    PA_DYNARRAY_FOREACH(port, device->ucm_ports, idx)
        pa_device_port_set_available(port->core_port, port->device->available);
}

void pa_alsa_ucm_device_update_available(pa_alsa_ucm_device *device) {
    pa_available_t available = PA_AVAILABLE_UNKNOWN;
    pa_alsa_jack *jack;
    unsigned idx;

    pa_assert(device);

    if (device->jack && device->jack->has_control)
        available = device->jack->plugged_in ? PA_AVAILABLE_YES : PA_AVAILABLE_NO;

    PA_DYNARRAY_FOREACH(jack, device->hw_mute_jacks, idx) {
        if (jack->plugged_in) {
            available = PA_AVAILABLE_NO;
            break;
        }
    }

    device_set_available(device, available);
}

static void ucm_port_data_init(pa_alsa_ucm_port_data *port, pa_alsa_ucm_config *ucm, pa_device_port *core_port,
                               pa_alsa_ucm_device *device) {
    pa_assert(ucm);
    pa_assert(core_port);
    pa_assert(device);

    port->ucm = ucm;
    port->core_port = core_port;
    port->eld_device = -1;

    port->device = device;
    pa_dynarray_append(device->ucm_ports, port);

    port->paths = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree,
                                      (pa_free_cb_t) pa_alsa_path_free);

    pa_device_port_set_available(port->core_port, port->device->available);
}

static void ucm_port_data_free(pa_device_port *port) {
    pa_alsa_ucm_port_data *ucm_port;

    pa_assert(port);

    ucm_port = PA_DEVICE_PORT_DATA(port);

    if (ucm_port->paths)
        pa_hashmap_free(ucm_port->paths);

    pa_xfree(ucm_port->eld_mixer_device_name);
}

#else /* HAVE_ALSA_UCM */

/* Dummy functions for systems without UCM support */

int pa_alsa_ucm_query_profiles(pa_alsa_ucm_config *ucm, int card_index) {
        pa_log_info("UCM not available.");
        return -1;
}

pa_alsa_profile_set* pa_alsa_ucm_add_profile_set(pa_alsa_ucm_config *ucm, pa_channel_map *default_channel_map) {
    return NULL;
}

int pa_alsa_ucm_set_profile(pa_alsa_ucm_config *ucm, pa_card *card, pa_alsa_profile *new_profile, pa_alsa_profile *old_profile) {
    return -1;
}

int pa_alsa_ucm_get_verb(snd_use_case_mgr_t *uc_mgr, const char *verb_name, const char *verb_desc, pa_alsa_ucm_verb **p_verb) {
    return -1;
}

void pa_alsa_ucm_add_ports(
        pa_hashmap **hash,
        pa_proplist *proplist,
        pa_alsa_ucm_mapping_context *context,
        bool is_sink,
        pa_card *card,
        snd_pcm_t *pcm_handle,
        bool ignore_dB) {
}

void pa_alsa_ucm_add_port(
        pa_hashmap *hash,
        pa_alsa_ucm_mapping_context *context,
        bool is_sink,
        pa_hashmap *ports,
        pa_card_profile *cp,
        pa_core *core) {
}

int pa_alsa_ucm_set_port(pa_alsa_ucm_mapping_context *context, pa_device_port *port) {
    return -1;
}

void pa_alsa_ucm_free(pa_alsa_ucm_config *ucm) {
}

void pa_alsa_ucm_mapping_context_free(pa_alsa_ucm_mapping_context *context) {
}

void pa_alsa_ucm_roled_stream_begin(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
}

void pa_alsa_ucm_roled_stream_end(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
}

#endif