File: cras_audio_handler.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (3497 lines) | stat: -rw-r--r-- 121,252 bytes parent folder | download | duplicates (7)
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
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/audio/cras_audio_handler.h"

#include <stddef.h>
#include <stdint.h>

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "ash/constants/ash_features.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "base/system/system_monitor.h"
#include "base/task/single_thread_task_runner.h"
#include "chromeos/ash/components/audio/audio_device.h"
#include "chromeos/ash/components/audio/audio_device_encoding.h"
#include "chromeos/ash/components/audio/audio_device_id.h"
#include "chromeos/ash/components/audio/audio_devices_pref_handler_stub.h"
#include "chromeos/ash/components/dbus/audio/cras_audio_client.h"
#include "chromeos/ash/components/dbus/audio/fake_cras_audio_client.h"
#include "chromeos/ash/components/dbus/audio/floss_media_client.h"
#include "chromeos/ash/components/dbus/audio/voice_isolation_ui_appearance.h"
#include "device/bluetooth/floss/floss_features.h"
#include "third_party/cros_system_api/dbus/audio/dbus-constants.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace ash {
namespace {

using ::std::max;
using ::std::min;

// Default value for unmuting, as a percent in the range [0, 100].
// Used when sound is unmuted, but volume was less than kMuteThresholdPercent.
const int kDefaultUnmuteVolumePercent = 4;

// Volume value which should be considered as muted in range [0, 100].
const int kMuteThresholdPercent = 1;

// Mixer matrix, [0.5, 0.5; 0.5, 0.5]
const double kStereoToMono[] = {0.5, 0.5, 0.5, 0.5};
// Mixer matrix, [1, 0; 0, 1]
const double kStereoToStereo[] = {1, 0, 0, 1};

// Number of entries we're willing to store in preferences.
const int kMaxDeviceStoredInPref = 100;

CrasAudioHandler* g_cras_audio_handler = nullptr;

bool IsSameAudioDevice(const AudioDevice& a, const AudioDevice& b) {
  return a.stable_device_id == b.stable_device_id && a.is_input == b.is_input &&
         a.type == b.type && a.device_name == b.device_name;
}

bool IsDeviceInList(const AudioDevice& device, const AudioNodeList& node_list) {
  for (const AudioNode& node : node_list) {
    if (device.stable_device_id == node.StableDeviceId()) {
      return true;
    }
  }
  return false;
}

// Gets the current state of the microphone mute switch. If the switch is on,
// cras will be kept in the muted state. The switch disables the internal audio
// input.
bool IsMicrophoneMuteSwitchOn() {
  return ui::MicrophoneMuteSwitchMonitor::Get()->microphone_mute_switch_on();
}

}  // namespace

// TODO(b/277300962): Clean up the default value and handle the unset case.
CrasAudioHandler::AudioSurvey::AudioSurvey() : type_(SurveyType::kGeneral) {}

CrasAudioHandler::AudioSurvey::~AudioSurvey() = default;

CrasAudioHandler::AudioObserver::AudioObserver() = default;

CrasAudioHandler::AudioObserver::~AudioObserver() = default;

void CrasAudioHandler::AudioObserver::OnOutputNodeVolumeChanged(
    uint64_t /* node_id */,
    int /* volume */) {}

void CrasAudioHandler::AudioObserver::OnInputNodeGainChanged(
    uint64_t /* node_id */,
    int /* gain */) {}

void CrasAudioHandler::AudioObserver::OnOutputMuteChanged(bool /* mute_on */) {}

void CrasAudioHandler::AudioObserver::OnInputMuteChanged(
    bool /* mute_on */,
    InputMuteChangeMethod /* method */) {}

void CrasAudioHandler::AudioObserver::OnInputMutedByMicrophoneMuteSwitchChanged(
    bool /* muted */) {}

void CrasAudioHandler::AudioObserver::OnInputMutedBySecurityCurtainChanged(
    bool /* muted */) {}

void CrasAudioHandler::AudioObserver::OnAudioNodesChanged() {}

void CrasAudioHandler::AudioObserver::OnActiveOutputNodeChanged() {}

void CrasAudioHandler::AudioObserver::OnActiveInputNodeChanged() {}

void CrasAudioHandler::AudioObserver::OnOutputChannelRemixingChanged(
    bool /* mono_on */) {}

void CrasAudioHandler::AudioObserver::OnVoiceIsolationUIAppearanceChanged(
    VoiceIsolationUIAppearance appearance) {}

void CrasAudioHandler::AudioObserver::OnNoiseCancellationStateChanged() {}

void CrasAudioHandler::AudioObserver::OnStyleTransferStateChanged() {}

void CrasAudioHandler::AudioObserver::OnForceRespectUiGainsStateChanged() {}

void CrasAudioHandler::AudioObserver::OnHfpMicSrStateChanged() {}

void CrasAudioHandler::AudioObserver::OnSpatialAudioStateChanged() {}

void CrasAudioHandler::AudioObserver::OnHotwordTriggered(
    uint64_t /* tv_sec */,
    uint64_t /* tv_nsec */) {}

void CrasAudioHandler::AudioObserver::OnBluetoothBatteryChanged(
    const std::string& /* address */,
    uint32_t /* level */) {}

void CrasAudioHandler::AudioObserver::
    OnNumberOfInputStreamsWithPermissionChanged() {}

void CrasAudioHandler::AudioObserver::OnOutputStarted() {}

void CrasAudioHandler::AudioObserver::OnOutputStopped() {}

void CrasAudioHandler::AudioObserver::OnNonChromeOutputStarted() {}

void CrasAudioHandler::AudioObserver::OnNonChromeOutputStopped() {}

void CrasAudioHandler::AudioObserver::OnSurveyTriggered(
    const AudioSurvey& /*survey*/) {}

void CrasAudioHandler::AudioObserver::OnSpeakOnMuteDetected() {}

void CrasAudioHandler::AudioObserver::OnNumStreamIgnoreUiGainsChanged(
    int32_t num) {}

void CrasAudioHandler::AudioObserver::OnNumberOfArcStreamsChanged(int32_t num) {
}

void CrasAudioHandler::NumberOfNonChromeOutputStreamsChanged() {
  GetNumberOfNonChromeOutputStreams();
}

void CrasAudioHandler::NumberOfArcStreamsChanged() {
  GetNumberOfArcStreams();
}

// static
void CrasAudioHandler::Initialize(
    mojo::PendingRemote<media_session::mojom::MediaControllerManager>
        media_controller_manager,
    scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler) {
  g_cras_audio_handler = new CrasAudioHandler(
      std::move(media_controller_manager), audio_pref_handler);
}

// static
void CrasAudioHandler::InitializeDelegate(
    mojo::PendingRemote<media_session::mojom::MediaControllerManager>
        media_controller_manager,
    scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler,
    std::unique_ptr<Delegate> delegate) {
  g_cras_audio_handler =
      new CrasAudioHandler(std::move(media_controller_manager),
                           audio_pref_handler, std::move(delegate));
}

// static
void CrasAudioHandler::InitializeForTesting() {
  CHECK(CrasAudioClient::Get()) << "CrasAudioClient must be initialized.";

  // Make sure FlossMediaClient has been initialized.
  // TODO(b/228608730): Remove this after Floss bypasses CRAS to receive media
  // information directly from the provider.
  if (floss::features::IsFlossEnabled() && !FlossMediaClient::Get()) {
    FlossMediaClient::InitializeFake();
  }
  CrasAudioHandler::Initialize(mojo::NullRemote(),
                               new AudioDevicesPrefHandlerStub());
}

// static
void CrasAudioHandler::Shutdown() {
  delete g_cras_audio_handler;
  g_cras_audio_handler = nullptr;
}

// static
CrasAudioHandler* CrasAudioHandler::Get() {
  return g_cras_audio_handler;
}

void CrasAudioHandler::OnVideoCaptureStarted(media::VideoFacingMode facing) {
  DCHECK(main_task_runner_);
  if (!main_task_runner_->BelongsToCurrentThread()) {
    main_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&CrasAudioHandler::OnVideoCaptureStartedOnMainThread,
                       weak_ptr_factory_.GetWeakPtr(), facing));
    return;
  }
  // Unittest may call this from the main thread.
  OnVideoCaptureStartedOnMainThread(facing);
}

void CrasAudioHandler::OnVideoCaptureStopped(media::VideoFacingMode facing) {
  DCHECK(main_task_runner_);
  if (!main_task_runner_->BelongsToCurrentThread()) {
    main_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&CrasAudioHandler::OnVideoCaptureStoppedOnMainThread,
                       weak_ptr_factory_.GetWeakPtr(), facing));
    return;
  }
  // Unittest may call this from the main thread.
  OnVideoCaptureStoppedOnMainThread(facing);
}

void CrasAudioHandler::OnVideoCaptureStartedOnMainThread(
    media::VideoFacingMode facing) {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  // Do nothing if the device doesn't have both front and rear microphones.
  if (!HasDualInternalMic()) {
    return;
  }

  bool camera_is_already_on = IsCameraOn();
  switch (facing) {
    case media::MEDIA_VIDEO_FACING_USER:
      front_camera_on_ = true;
      break;
    case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
      rear_camera_on_ = true;
      break;
    default:
      LOG_IF(WARNING, facing == media::NUM_MEDIA_VIDEO_FACING_MODES)
          << "On the device with dual microphone, got video capture "
          << "notification with invalid camera facing mode value";
      return;
  }

  // If the camera is already on before this notification, don't change active
  // input. In the case that both cameras are turned on at the same time, we
  // won't change the active input after the first camera is turned on. We only
  // support the use case of one camera on at a time. The third party
  // developer can turn on/off both microphones with extension api if they like
  // to.
  if (camera_is_already_on) {
    return;
  }

  // If the current active input is an external device, keep it.
  const AudioDevice* active_input = GetDeviceFromId(active_input_node_id_);
  if (active_input && active_input->IsExternalDevice()) {
    return;
  }

  // Activate the correct mic for the current active camera.
  ActivateMicForCamera(facing);
}

void CrasAudioHandler::OnVideoCaptureStoppedOnMainThread(
    media::VideoFacingMode facing) {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  // Do nothing if the device doesn't have both front and rear microphones.
  if (!HasDualInternalMic()) {
    return;
  }

  switch (facing) {
    case media::MEDIA_VIDEO_FACING_USER:
      front_camera_on_ = false;
      break;
    case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
      rear_camera_on_ = false;
      break;
    default:
      LOG_IF(WARNING, facing == media::NUM_MEDIA_VIDEO_FACING_MODES)
          << "On the device with dual microphone, got video capture "
          << "notification with invalid camera facing mode value";
      return;
  }

  // If not all cameras are turned off, don't change active input. In the case
  // that both cameras are turned on at the same time before one of them is
  // stopped, we won't change active input until all of them are stopped.
  // We only support the use case of one camera on at a time. The third party
  // developer can turn on/off both microphones with extension api if they like
  // to.
  if (IsCameraOn()) {
    return;
  }

  // If the current active input is an external device, keep it.
  const AudioDevice* active_input = GetDeviceFromId(active_input_node_id_);
  if (active_input && active_input->IsExternalDevice()) {
    return;
  }

  // Switch to front mic properly.
  DeviceActivateType activated_by =
      HasExternalDevice(true) ? DeviceActivateType::kActivateByUser
                              : DeviceActivateType::kActivateByPriority;
  SwitchToDevice(*GetDeviceByType(AudioDeviceType::kFrontMic), true,
                 activated_by);
}

void CrasAudioHandler::HandleMediaSessionMetadataReset() {
  const std::map<std::string, std::string> empty_metadata_map = {
      {"title", ""}, {"artist", ""}, {"album", ""}};

  // TODO(b/228608730): Remove this after Floss bypasses CRAS to receive media
  // information directly from the provider.
  if (floss::features::IsFlossEnabled()) {
    FlossMediaClient::Get()->SetPlayerMetadata(empty_metadata_map);
    FlossMediaClient::Get()->SetPlayerIdentity("");
    FlossMediaClient::Get()->SetPlayerPlaybackStatus("stopped");
  } else {
    CrasAudioClient::Get()->SetPlayerMetadata(empty_metadata_map);
    CrasAudioClient::Get()->SetPlayerIdentity("");
    CrasAudioClient::Get()->SetPlayerPlaybackStatus("stopped");
  }
}

void CrasAudioHandler::MediaSessionInfoChanged(
    media_session::mojom::MediaSessionInfoPtr session_info) {
  if (!session_info) {
    return;
  }

  std::string state = session_info->playback_state ==
                              media_session::mojom::MediaPlaybackState::kPlaying
                          ? "playing"
                          : "paused";

  // TODO(b/228608730): Remove this after Floss bypasses CRAS to receive media
  // information directly from the provider.
  if (floss::features::IsFlossEnabled()) {
    FlossMediaClient::Get()->SetPlayerPlaybackStatus(state);
  } else {
    CrasAudioClient::Get()->SetPlayerPlaybackStatus(state);
  }
}

void CrasAudioHandler::MediaSessionMetadataChanged(
    const std::optional<media_session::MediaMetadata>& metadata) {
  if (!metadata || metadata->IsEmpty()) {
    HandleMediaSessionMetadataReset();
    return;
  }

  const std::map<std::string, std::string> metadata_map = {
      {"title", base::UTF16ToUTF8(metadata->title)},
      {"artist", base::UTF16ToUTF8(metadata->artist)},
      {"album", base::UTF16ToUTF8(metadata->album)}};
  const std::string source_title = base::UTF16ToUTF8(metadata->source_title);

  // Assume media duration/length should always change with new metadata.
  fetch_media_session_duration_ = true;

  // TODO(b/228608730): Remove this after Floss bypasses CRAS to receive media
  // information directly from the provider.
  if (floss::features::IsFlossEnabled()) {
    FlossMediaClient::Get()->SetPlayerMetadata(metadata_map);
    FlossMediaClient::Get()->SetPlayerIdentity(source_title);
  } else {
    CrasAudioClient::Get()->SetPlayerMetadata(metadata_map);
    CrasAudioClient::Get()->SetPlayerIdentity(source_title);
  }
}

void CrasAudioHandler::MediaSessionPositionChanged(
    const std::optional<media_session::MediaPosition>& position) {
  if (!position) {
    return;
  }

  int64_t duration = 0;
  if (fetch_media_session_duration_) {
    duration = position->duration().InMicroseconds();
    if (duration > 0) {
      // TODO(b/228608730): Remove this after Floss bypasses the media
      // information from CRAS.
      if (floss::features::IsFlossEnabled()) {
        FlossMediaClient::Get()->SetPlayerDuration(duration);
      } else {
        CrasAudioClient::Get()->SetPlayerDuration(duration);
      }
      fetch_media_session_duration_ = false;
    }
  }

  int64_t current_position = position->GetPosition().InMicroseconds();
  if (current_position < 0 || (duration > 0 && current_position > duration)) {
    return;
  }

  // TODO(b/228608730): Remove this after Floss bypasses CRAS to receive media
  // information directly from the provider.
  if (floss::features::IsFlossEnabled()) {
    FlossMediaClient::Get()->SetPlayerPosition(current_position);
  } else {
    CrasAudioClient::Get()->SetPlayerPosition(current_position);
  }
}

void CrasAudioHandler::OnMicrophoneMuteSwitchValueChanged(bool muted) {
  input_muted_by_microphone_mute_switch_ = muted;
  SetInputMute(muted, InputMuteChangeMethod::kPhysicalShutter);

  for (auto& observer : observers_) {
    observer.OnInputMutedByMicrophoneMuteSwitchChanged(muted);
  }
}

void CrasAudioHandler::AddAudioObserver(AudioObserver* observer) {
  observers_.AddObserver(observer);
}

void CrasAudioHandler::RemoveAudioObserver(AudioObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool CrasAudioHandler::HasKeyboardMic() {
  return GetKeyboardMic() != nullptr;
}

bool CrasAudioHandler::HasHotwordDevice() {
  return GetHotwordDevice() != nullptr;
}

bool CrasAudioHandler::IsOutputMuted() {
  return output_mute_on_;
}

bool CrasAudioHandler::IsOutputMutedForDevice(uint64_t device_id) {
  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device) {
    return false;
  }
  DCHECK(!device->is_input);
  return audio_pref_handler_->GetMuteValue(*device);
}

bool CrasAudioHandler::IsOutputMutedByPolicy() {
  return output_mute_forced_by_policy_;
}

bool CrasAudioHandler::IsOutputMutedBySecurityCurtain() {
  return output_mute_forced_by_security_curtain_;
}

bool CrasAudioHandler::IsOutputVolumeBelowDefaultMuteLevel() {
  return output_volume_ <= kMuteThresholdPercent;
}

bool CrasAudioHandler::IsInputMuted() {
  return input_mute_on_;
}

bool CrasAudioHandler::IsInputMutedBySecurityCurtain() {
  return input_mute_forced_by_security_curtain_;
}

bool CrasAudioHandler::IsInputMutedForDevice(uint64_t device_id) {
  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device) {
    return false;
  }
  DCHECK(device->is_input);
  // We don't record input mute state for each device in the prefs,
  // for any non-active input device, we assume mute is off.
  if (device->id == active_input_node_id_) {
    return input_mute_on_;
  }
  return false;
}

int CrasAudioHandler::GetOutputDefaultVolumeMuteThreshold() const {
  return kMuteThresholdPercent;
}

int CrasAudioHandler::GetOutputVolumePercent() {
  return output_volume_;
}

int CrasAudioHandler::GetOutputVolumePercentForDevice(uint64_t device_id) {
  if (device_id == active_output_node_id_) {
    return output_volume_;
  }
  const AudioDevice* device = GetDeviceFromId(device_id);
  return static_cast<int>(audio_pref_handler_->GetOutputVolumeValue(device));
}

int CrasAudioHandler::GetInputGainPercent() {
  return input_gain_;
}

int CrasAudioHandler::GetInputGainPercentForDevice(uint64_t device_id) {
  if (device_id == active_input_node_id_) {
    return input_gain_;
  }
  const AudioDevice* device = GetDeviceFromId(device_id);
  return static_cast<int>(audio_pref_handler_->GetInputGainValue(device));
}

uint64_t CrasAudioHandler::GetPrimaryActiveOutputNode() const {
  return active_output_node_id_;
}

uint64_t CrasAudioHandler::GetPrimaryActiveInputNode() const {
  return active_input_node_id_;
}

void CrasAudioHandler::GetAudioDevices(AudioDeviceList* device_list) const {
  device_list->clear();
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    device_list->push_back(device);
  }
}

// static.
AudioDeviceList CrasAudioHandler::GetSimpleUsageAudioDevices(
    const AudioDeviceMap& audio_devices,
    bool is_input) {
  AudioDeviceList device_list;
  for (const auto& item : audio_devices) {
    const AudioDevice& device = item.second;
    // Do not count non simple usage devices.
    if (!device.is_for_simple_usage()) {
      continue;
    }
    if (device.is_input == is_input) {
      device_list.push_back(device);
    }
  }
  return device_list;
}

const AudioDeviceMap& CrasAudioHandler::GetAudioDevicesMapForTesting(
    bool is_current_device) const {
  return is_current_device ? audio_devices_ : previous_audio_devices_;
}

bool CrasAudioHandler::GetPrimaryActiveOutputDevice(AudioDevice* device) const {
  const AudioDevice* active_device = GetDeviceFromId(active_output_node_id_);
  if (!active_device || !device) {
    return false;
  }
  *device = *active_device;
  return true;
}

bool CrasAudioHandler::GetPrimaryActiveInputDevice(AudioDevice* device) const {
  const AudioDevice* active_device = GetDeviceFromId(active_input_node_id_);
  if (!active_device || !device) {
    return false;
  }
  *device = *active_device;
  return true;
}

const AudioDevice* CrasAudioHandler::GetDeviceByType(AudioDeviceType type) {
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.type == type) {
      return &device;
    }
  }
  return nullptr;
}

base::flat_map<CrasAudioHandler::ClientType, uint32_t>
CrasAudioHandler::GetNumberOfInputStreamsWithPermission() const {
  return number_of_input_streams_with_permission_;
}

void CrasAudioHandler::GetDefaultOutputBufferSize(int32_t* buffer_size) const {
  *buffer_size = default_output_buffer_size_;
}

void CrasAudioHandler::RequestGetAudioEffectDlcs() {
  CrasAudioClient::Get()->GetAudioEffectDlcs(
      base::BindOnce(&CrasAudioHandler::HandleGetAudioEffectDlcs,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetAudioEffectDlcs(
    std::optional<std::string> audio_effect_dlcs) {
  if (!audio_effect_dlcs.has_value()) {
    LOG(ERROR) << "cras_audio_handler: Failed to retrieve audio effect dlcs";
  } else {
    audio_effect_dlcs_ =
        base::SplitString(audio_effect_dlcs.value(), ",", base::TRIM_WHITESPACE,
                          base::SPLIT_WANT_NONEMPTY);
  }
}

std::optional<std::vector<std::string>> CrasAudioHandler::GetAudioEffectDlcs()
    const {
  return audio_effect_dlcs_;
}

void CrasAudioHandler::RequestVoiceIsolationUIAppearance() {
  CrasAudioClient::Get()->GetVoiceIsolationUIAppearance(
      base::BindOnce(&CrasAudioHandler::HandleGetVoiceIsolationUIAppearance,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::ResetVoiceIsolationPreferredEffectIfNeeded() {
  uint32_t effect_mode_options =
      voice_isolation_ui_appearance_.effect_mode_options;
  bool pref_is_zero = !audio_pref_handler_->GetVoiceIsolationPreferredEffect();
  if (effect_mode_options != 0 && pref_is_zero) {
    // Default preferred effect is Style Transfer.
    // Currently Style Transfer is always in effect_mode_options if it's not 0.
    audio_pref_handler_->SetVoiceIsolationPreferredEffect(
        cras::AudioEffectType::EFFECT_TYPE_STYLE_TRANSFER);
    RefreshVoiceIsolationPreferredEffect();
  }

  // Reset to NONE if the preferred effect is not in the effect_mode_options.
  if (!(effect_mode_options &
        audio_pref_handler_->GetVoiceIsolationPreferredEffect())) {
    audio_pref_handler_->SetVoiceIsolationPreferredEffect(
        cras::AudioEffectType::EFFECT_TYPE_NONE);
    RefreshVoiceIsolationPreferredEffect();
  }
}

void CrasAudioHandler::HandleGetVoiceIsolationUIAppearance(
    std::optional<VoiceIsolationUIAppearance> appearance) {
  if (!appearance.has_value()) {
    LOG(ERROR) << "cras_audio_handler: Failed to retrieve voice isolation UI "
                  "appearance.";
  } else {
    voice_isolation_ui_appearance_ = appearance.value();
    ResetVoiceIsolationPreferredEffectIfNeeded();
  }

  for (auto& observer : observers_) {
    observer.OnVoiceIsolationUIAppearanceChanged(
        voice_isolation_ui_appearance_);
  }
}

VoiceIsolationUIAppearance CrasAudioHandler::GetVoiceIsolationUIAppearance() {
  return voice_isolation_ui_appearance_;
}

bool CrasAudioHandler::GetVoiceIsolationState() const {
  return audio_pref_handler_->GetVoiceIsolationState();
}

void CrasAudioHandler::RefreshVoiceIsolationState() {
  // Refresh should only update the state in CRAS and leave the preference
  // as-is.
  CrasAudioClient::Get()->SetVoiceIsolationUIEnabled(GetVoiceIsolationState());
}

void CrasAudioHandler::RecordVoiceIsolationEnabledChangeSource(
    AudioSettingsChangeSource source) {
  base::UmaHistogramEnumeration(kVoiceIsolationEnabledChangeSourceHistogramName,
                                source);
}

uint32_t CrasAudioHandler::GetVoiceIsolationPreferredEffect() const {
  return audio_pref_handler_->GetVoiceIsolationPreferredEffect();
}

void CrasAudioHandler::RefreshVoiceIsolationPreferredEffect() {
  CrasAudioClient::Get()->SetVoiceIsolationUIPreferredEffect(
      GetVoiceIsolationPreferredEffect());
}

void CrasAudioHandler::RecordVoiceIsolationPreferredEffectChange(
    audio_config::mojom::AudioEffectType preferred_effect) {
  base::UmaHistogramEnumeration(
      kVoiceIsolationPreferredEffectChangeHistogramName, preferred_effect);
}

bool CrasAudioHandler::IsNoiseCancellationSupportedForDevice(
    uint64_t device_id) {
  if (!noise_cancellation_supported()) {
    return false;
  }

  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device) {
    return false;
  }

  if (!device->is_input) {
    return false;
  }

  return device->audio_effect & cras::EFFECT_TYPE_NOISE_CANCELLATION;
}

bool CrasAudioHandler::GetNoiseCancellationState() const {
  return audio_pref_handler_->GetNoiseCancellationState();
}

void CrasAudioHandler::SetNoiseCancellationState(
    bool noise_cancellation_on,
    AudioSettingsChangeSource source) {
  CrasAudioClient::Get()->SetVoiceIsolationUIEnabled(noise_cancellation_on);
  audio_pref_handler_->SetVoiceIsolationState(noise_cancellation_on);

  for (auto& observer : observers_) {
    observer.OnNoiseCancellationStateChanged();
  }
  base::UmaHistogramEnumeration(kNoiseCancellationEnabledSourceHistogramName,
                                source);
}

void CrasAudioHandler::RequestNoiseCancellationSupported(
    OnNoiseCancellationSupportedCallback callback) {
  CrasAudioClient::Get()->GetNoiseCancellationSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetNoiseCancellationSupported,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void CrasAudioHandler::HandleGetNoiseCancellationSupported(
    OnNoiseCancellationSupportedCallback callback,
    std::optional<bool> noise_cancellation_supported) {
  if (!noise_cancellation_supported.has_value()) {
    LOG(ERROR)
        << "cras_audio_handler: Failed to retrieve noise cancellation support";
  } else {
    noise_cancellation_supported_ = noise_cancellation_supported.value();
  }

  std::move(callback).Run();
}

void CrasAudioHandler::SetVoiceIsolationUIAppearanceForTesting(
    cras::AudioEffectType toggle_type,
    uint32_t effect_mode_options,
    bool show_effect_fallback_message) {
  voice_isolation_ui_appearance_ = VoiceIsolationUIAppearance(
      toggle_type, effect_mode_options, show_effect_fallback_message);
}

void CrasAudioHandler::SetNoiseCancellationSupportedForTesting(bool supported) {
  noise_cancellation_supported_ = supported;
}

bool CrasAudioHandler::IsStyleTransferSupportedForDevice(uint64_t device_id) {
  if (!style_transfer_supported()) {
    return false;
  }

  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device) {
    return false;
  }

  return device->audio_effect & cras::EFFECT_TYPE_STYLE_TRANSFER;
}

bool CrasAudioHandler::GetStyleTransferState() const {
  return audio_pref_handler_->GetVoiceIsolationState();
}

void CrasAudioHandler::SetStyleTransferState(bool style_transfer_on) {
  CrasAudioClient::Get()->SetVoiceIsolationUIEnabled(style_transfer_on);
  audio_pref_handler_->SetVoiceIsolationState(style_transfer_on);

  for (auto& observer : observers_) {
    observer.OnStyleTransferStateChanged();
  }
}

void CrasAudioHandler::RequestStyleTransferSupported(
    OnStyleTransferSupportedCallback callback) {
  CrasAudioClient::Get()->GetStyleTransferSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetStyleTransferSupported,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void CrasAudioHandler::HandleGetStyleTransferSupported(
    OnStyleTransferSupportedCallback callback,
    std::optional<bool> system_style_transfer_supported) {
  if (!system_style_transfer_supported.has_value()) {
    LOG(ERROR)
        << "cras_audio_handler: Failed to retrieve style transfer support";
  } else {
    style_transfer_supported_ = system_style_transfer_supported.value();
  }

  std::move(callback).Run();
}

void CrasAudioHandler::SetStyleTransferSupportedForTesting(bool supported) {
  style_transfer_supported_ = supported;
}

bool CrasAudioHandler::GetForceRespectUiGainsState() const {
  return audio_pref_handler_->GetForceRespectUiGainsState();
}

void CrasAudioHandler::RefreshForceRespectUiGainsState() {
  // Refresh should only update the state in CRAS and leave the preference
  // as-is.
  CrasAudioClient::Get()->SetForceRespectUiGains(GetForceRespectUiGainsState());
}

void CrasAudioHandler::SetForceRespectUiGainsState(bool state) {
  base::UmaHistogramBoolean(CrasAudioHandler::kForceRespectUiGainsHistogramName,
                            state);
  CrasAudioClient::Get()->SetForceRespectUiGains(state);
  audio_pref_handler_->SetForceRespectUiGainsState(state);

  for (auto& observer : observers_) {
    observer.OnForceRespectUiGainsStateChanged();
  }
}

bool CrasAudioHandler::IsHfpMicSrSupportedForDevice(uint64_t device_id) {
  if (!hfp_mic_sr_supported()) {
    return false;
  }

  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device || device->type != AudioDeviceType::kBluetoothNbMic) {
    return false;
  }

  return device->audio_effect & cras::EFFECT_TYPE_HFP_MIC_SR;
}

void CrasAudioHandler::RequestHfpMicSrSupported(
    OnHfpMicSrSupportedCallback callback) {
  CrasAudioClient::Get()->GetHfpMicSrSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetHfpMicSrSupported,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void CrasAudioHandler::SetHfpMicSrSupportedForTesting(bool supported) {
  hfp_mic_sr_supported_ = supported;
}

void CrasAudioHandler::HandleGetHfpMicSrSupported(
    OnHfpMicSrSupportedCallback callback,
    std::optional<bool> hfp_mic_sr_supported) {
  if (!hfp_mic_sr_supported.has_value()) {
    LOG(ERROR) << "cras_audio_handler: Failed to retrieve hfp_mic_sr support";
  } else {
    hfp_mic_sr_supported_ = hfp_mic_sr_supported.value();
  }

  std::move(callback).Run();
}

bool CrasAudioHandler::GetHfpMicSrState() const {
  return audio_pref_handler_->GetHfpMicSrState();
}

void CrasAudioHandler::RefreshHfpMicSrState() {
  if (!hfp_mic_sr_supported()) {
    return;
  }

  const AudioDevice* device = GetDeviceByType(AudioDeviceType::kBluetoothNbMic);
  if (!device) {
    return;
  }

  // Refresh should only update the state in CRAS and leave the preference
  // as-is.
  CrasAudioClient::Get()->SetHfpMicSrEnabled(
      GetHfpMicSrState() &&
      (device->audio_effect & cras::EFFECT_TYPE_HFP_MIC_SR));
}

void CrasAudioHandler::SetHfpMicSrState(bool hfp_mic_sr_on,
                                        AudioSettingsChangeSource source) {
  CrasAudioClient::Get()->SetHfpMicSrEnabled(hfp_mic_sr_on);
  audio_pref_handler_->SetHfpMicSrState(hfp_mic_sr_on);

  for (auto& observer : observers_) {
    observer.OnHfpMicSrStateChanged();
  }
}

bool CrasAudioHandler::IsSpatialAudioSupportedForDevice(uint64_t device_id) {
  if (!spatial_audio_supported()) {
    return false;
  }

  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device || device->type != AudioDeviceType::kInternalSpeaker) {
    return false;
  }

  return true;
}

void CrasAudioHandler::RequestSpatialAudioSupported(
    OnSpatialAudioSupportedCallback callback) {
  CrasAudioClient::Get()->GetSpatialAudioSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetSpatialAudioSupported,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void CrasAudioHandler::HandleGetSpatialAudioSupported(
    OnSpatialAudioSupportedCallback callback,
    std::optional<bool> spatial_audio_supported) {
  if (!spatial_audio_supported.has_value()) {
    LOG(ERROR)
        << "cras_audio_handler: Failed to retrieve spatial audio support";
  } else {
    spatial_audio_supported_ = spatial_audio_supported.value();
  }

  std::move(callback).Run();
}

bool CrasAudioHandler::GetSpatialAudioState() const {
  return audio_pref_handler_->GetSpatialAudioState();
}

void CrasAudioHandler::RefreshSpatialAudioState() {
  // Refresh should only update the state in CRAS and leave the preference
  // as-is.
  CrasAudioClient::Get()->SetSpatialAudio(GetSpatialAudioState());
}

void CrasAudioHandler::SetSpatialAudioState(bool state) {
  base::UmaHistogramBoolean(CrasAudioHandler::kSpatialAudioHistogramName,
                            state);
  CrasAudioClient::Get()->SetSpatialAudio(state);
  audio_pref_handler_->SetSpatialAudioState(state);

  for (auto& observer : observers_) {
    observer.OnSpatialAudioStateChanged();
  }
}

void CrasAudioHandler::SetSpatialAudioSupportedForTesting(bool supported) {
  spatial_audio_supported_ = supported;
}

void CrasAudioHandler::SetKeyboardMicActive(bool active) {
  const AudioDevice* keyboard_mic = GetKeyboardMic();
  if (!keyboard_mic) {
    return;
  }
  // Keyboard mic is invisible to chromeos users. It is always added or removed
  // as additional active node.
  DCHECK(active_input_node_id_ && active_input_node_id_ != keyboard_mic->id);
  if (active) {
    AddActiveNode(keyboard_mic->id, true);
  } else {
    RemoveActiveNodeInternal(keyboard_mic->id, true);
  }
}

void CrasAudioHandler::SetSpeakOnMuteDetection(bool som_on) {
  CrasAudioClient::Get()->SetSpeakOnMuteDetection(som_on);
  speak_on_mute_detection_on_ = som_on;
}

void CrasAudioHandler::SetEwmaPowerReportEnabled(bool enabled) {
  CrasAudioClient::Get()->SetEwmaPowerReportEnabled(enabled);
  ewma_power_report_enabled_ = enabled;
}

double CrasAudioHandler::GetEwmaPower() {
  return ewma_power_;
}

void CrasAudioHandler::SetSidetoneEnabled(bool enabled) {
  CrasAudioClient::Get()->SetSidetoneEnabled(enabled);
  sidetone_enabled_ = enabled;
}

bool CrasAudioHandler::GetSidetoneEnabled() const {
  return sidetone_enabled_;
}

bool CrasAudioHandler::IsSidetoneSupported() const {
  return sidetone_supported_;
}

void CrasAudioHandler::UpdateSidetoneSupportedState() {
  CrasAudioClient::Get()->GetSidetoneSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetSidetoneSupported,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetSidetoneSupported(
    std::optional<bool> supported) {
  if (!supported.has_value()) {
    LOG(ERROR) << "Failed to check whether sidetone is supported.";
    return;
  }

  sidetone_supported_ = *supported;
}

void CrasAudioHandler::AddActiveNode(uint64_t node_id, bool notify) {
  const AudioDevice* device = GetDeviceFromId(node_id);
  if (!device) {
    VLOG(1) << "AddActiveInputNode: Cannot find device id=" << "0x" << std::hex
            << node_id;
    return;
  }

  // If there is no primary active device, set |node_id| to primary active node.
  if ((device->is_input && !active_input_node_id_) ||
      (!device->is_input && !active_output_node_id_)) {
    SwitchToDevice(*device, notify, DeviceActivateType::kActivateByUser);
    return;
  }

  AddAdditionalActiveNode(node_id, notify);
}

void CrasAudioHandler::ChangeActiveNodes(const NodeIdList& new_active_ids) {
  AudioDeviceList input_devices;
  AudioDeviceList output_devices;

  for (uint64_t id : new_active_ids) {
    const AudioDevice* device = GetDeviceFromId(id);
    if (!device) {
      continue;
    }
    if (device->is_input) {
      input_devices.push_back(*device);
    } else {
      output_devices.push_back(*device);
    }
  }
  if (!input_devices.empty()) {
    SetActiveDevices(input_devices, true /* is_input */);
  }
  if (!output_devices.empty()) {
    SetActiveDevices(output_devices, false /* is_input */);
  }
}

bool CrasAudioHandler::SetActiveInputNodes(const NodeIdList& node_ids) {
  return SetActiveNodes(node_ids, true /* is_input */);
}

bool CrasAudioHandler::SetActiveOutputNodes(const NodeIdList& node_ids) {
  return SetActiveNodes(node_ids, false /* is_input */);
}

bool CrasAudioHandler::SetActiveNodes(const NodeIdList& node_ids,
                                      bool is_input) {
  AudioDeviceList devices;
  for (uint64_t id : node_ids) {
    const AudioDevice* device = GetDeviceFromId(id);
    if (!device || device->is_input != is_input) {
      return false;
    }

    devices.push_back(*device);
  }

  SetActiveDevices(devices, is_input);
  return true;
}

void CrasAudioHandler::SetActiveDevices(const AudioDeviceList& devices,
                                        bool is_input) {
  std::set<uint64_t> new_active_ids;
  for (const auto& active_device : devices) {
    CHECK_EQ(is_input, active_device.is_input);
    new_active_ids.insert(active_device.id);
  }

  bool active_devices_changed = false;

  // If  primary active node has to be switched, do that before adding or
  // removing any other active devices. Switching to a device can change
  // activity state of other devices - final device activity may end up being
  // unintended if it is set before active device switches.
  uint64_t primary_active =
      is_input ? active_input_node_id_ : active_output_node_id_;
  if (!new_active_ids.count(primary_active) && !devices.empty()) {
    active_devices_changed = true;
    SwitchToDevice(devices[0], false /* notify */,
                   DeviceActivateType::kActivateByUser);
  }

  AudioDeviceList existing_devices;
  GetAudioDevices(&existing_devices);
  for (const auto& existing_device : existing_devices) {
    if (existing_device.is_input != is_input) {
      continue;
    }

    bool should_be_active = new_active_ids.count(existing_device.id);
    if (existing_device.active == should_be_active) {
      continue;
    }
    active_devices_changed = true;

    if (should_be_active) {
      AddActiveNode(existing_device.id, false /* notify */);
    } else {
      RemoveActiveNodeInternal(existing_device.id, false /* notify */);
    }
  }

  if (active_devices_changed) {
    NotifyActiveNodeChanged(is_input);
  }
}

void CrasAudioHandler::SetHotwordModel(uint64_t node_id,
                                       const std::string& hotword_model,
                                       VoidCrasAudioHandlerCallback callback) {
  CrasAudioClient::Get()->SetHotwordModel(node_id, hotword_model,
                                          std::move(callback));
}

void CrasAudioHandler::SwapInternalSpeakerLeftRightChannel(bool swap) {
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (!device.is_input && device.type == AudioDeviceType::kInternalSpeaker) {
      CrasAudioClient::Get()->SwapLeftRight(device.id, swap);
      break;
    }
  }
}

void CrasAudioHandler::SetDisplayRotation(cras::DisplayRotation rotation) {
  display_rotation_ = rotation;
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.type == AudioDeviceType::kInternalSpeaker) {
      CrasAudioClient::Get()->SetDisplayRotation(device.id, display_rotation_);
      break;
    }
  }
}

void CrasAudioHandler::SetOutputMonoEnabled(bool enabled) {
  if (output_mono_enabled_ == enabled) {
    return;
  }
  output_mono_enabled_ = enabled;
  if (enabled) {
    CrasAudioClient::Get()->SetGlobalOutputChannelRemix(
        output_channels_,
        std::vector<double>(kStereoToMono, std::end(kStereoToMono)));
  } else {
    CrasAudioClient::Get()->SetGlobalOutputChannelRemix(
        output_channels_,
        std::vector<double>(kStereoToStereo, std::end(kStereoToStereo)));
  }

  for (auto& observer : observers_) {
    observer.OnOutputChannelRemixingChanged(enabled);
  }
}

bool CrasAudioHandler::has_alternative_input() const {
  return has_alternative_input_;
}

bool CrasAudioHandler::has_alternative_output() const {
  return has_alternative_output_;
}

void CrasAudioHandler::SetOutputVolumePercent(int volume_percent) {
  // Set all active devices to the same volume.
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (!device.is_input && device.active) {
      SetOutputNodeVolumePercent(device.id, volume_percent);
    }
  }
}

// TODO: Rename the 'Percent' to something more meaningful.
void CrasAudioHandler::SetInputGainPercent(int gain_percent) {
  // TODO(jennyz): Should we set all input devices' gain to the same level?
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.is_input && device.active) {
      SetInputNodeGainPercent(active_input_node_id_, gain_percent);
    }
  }
}

void CrasAudioHandler::AdjustOutputVolumeByPercent(int adjust_by_percent) {
  SetOutputVolumePercent(output_volume_ + adjust_by_percent);
}

void CrasAudioHandler::IncreaseOutputVolumeByOneStep(int one_step_percent) {
  // Set all active devices to the same volume.
  int new_output_volume = 0;
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (!device.is_input && device.active) {
      // only USB device should depend on number_of_volume_steps
      if (device.type == AudioDeviceType::kUsb) {
        int32_t number_of_volume_steps = device.number_of_volume_steps;
        if (number_of_volume_steps == 0) {
          LOG(ERROR)
              << device.ToString()
              << ": No valid number_of_volume_steps. Falling back to default.";
          number_of_volume_steps = NUMBER_OF_VOLUME_STEPS_DEFAULT;
        }
        int32_t volume_level = std::round(
            (double)output_volume_ * (double)number_of_volume_steps * 0.01);
        if (volume_level == 0 && output_volume_ > 0) {
          volume_level = 1;
        }
        // increase one level and convert to volume
        new_output_volume = std::min(
            100, static_cast<int>(std::floor(((double)(volume_level + 1)) /
                                             number_of_volume_steps * 100)));
      } else {
        new_output_volume = std::min(100, output_volume_ + one_step_percent);
      }
      SetOutputNodeVolumePercent(device.id, new_output_volume);
    }
  }
}

void CrasAudioHandler::DecreaseOutputVolumeByOneStep(int one_step_percent) {
  // Set all active devices to the same volume.
  int new_output_volume = 0;
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (!device.is_input && device.active) {
      if (device.type == AudioDeviceType::kUsb) {
        int32_t number_of_volume_steps = device.number_of_volume_steps;
        if (number_of_volume_steps == 0) {
          LOG(ERROR)
              << device.ToString()
              << ": No valid number_of_volume_steps. Falling back to default.";
          number_of_volume_steps = NUMBER_OF_VOLUME_STEPS_DEFAULT;
        }
        int32_t volume_level = std::round(
            (double)output_volume_ * (double)number_of_volume_steps * 0.01);

        // decrease one level and convert to volume
        new_output_volume = std::max(
            0, static_cast<int>(std::floor(((double)(volume_level - 1)) /
                                           number_of_volume_steps * 100)));
      } else {
        new_output_volume = std::max(0, output_volume_ - one_step_percent);
      }
      SetOutputNodeVolumePercent(device.id, new_output_volume);
    }
  }
}

void CrasAudioHandler::SetOutputMute(bool mute_on) {
  if (!SetOutputMuteInternal(mute_on)) {
    return;
  }

  // Save the mute state for all active output audio devices.
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (!device.is_input && device.active) {
      audio_pref_handler_->SetMuteValue(device, output_mute_on_);
    }
  }

  for (auto& observer : observers_) {
    observer.OnOutputMuteChanged(output_mute_on_);
  }
}

void CrasAudioHandler::SetOutputMute(
    bool mute_on,
    CrasAudioHandler::AudioSettingsChangeSource source) {
  SetOutputMute(mute_on);
  base::UmaHistogramEnumeration(
      CrasAudioHandler::kOutputVolumeMuteSourceHistogramName, source);
}

void CrasAudioHandler::SetOutputMuteLockedBySecurityCurtain(bool mute_on) {
  if (output_mute_forced_by_security_curtain_ == mute_on) {
    return;
  }

  output_mute_forced_by_security_curtain_ = mute_on;
  UpdateAudioOutputMute();
}

void CrasAudioHandler::AdjustOutputVolumeToAudibleLevel() {
  if (output_volume_ <= kMuteThresholdPercent) {
    for (const auto& item : audio_devices_) {
      int unmute_volume = kDefaultUnmuteVolumePercent;
      const AudioDevice& device = item.second;
      if (!device.is_input && device.active) {
        if (device.type == AudioDeviceType::kUsb) {
          int32_t number_of_volume_steps = device.number_of_volume_steps;
          DCHECK(number_of_volume_steps > 0);
          unmute_volume = 100 / number_of_volume_steps;
        }
        SetOutputNodeVolumePercent(device.id, unmute_volume);
      }
    }
  }
}

void CrasAudioHandler::SetInputMute(bool mute_on,
                                    InputMuteChangeMethod method) {
  const bool old_mute_on = input_mute_on_;
  SetInputMuteInternal(mute_on);

  if (old_mute_on != input_mute_on_) {
    for (auto& observer : observers_) {
      observer.OnInputMuteChanged(input_mute_on_, method);
    }
  }
}

void CrasAudioHandler::SetInputMute(
    bool mute_on,
    InputMuteChangeMethod method,
    CrasAudioHandler::AudioSettingsChangeSource source) {
  SetInputMute(mute_on, method);
  base::UmaHistogramEnumeration(
      CrasAudioHandler::kInputGainMuteSourceHistogramName, source);
}

void CrasAudioHandler::SetInputMuteLockedBySecurityCurtain(bool mute_on) {
  if (input_mute_forced_by_security_curtain_ == mute_on) {
    return;
  }

  input_mute_forced_by_security_curtain_ = mute_on;
  SetInputMute(mute_on, InputMuteChangeMethod::kOther);

  for (auto& observer : observers_) {
    observer.OnInputMutedBySecurityCurtainChanged(mute_on);
  }
}

void CrasAudioHandler::SetActiveDevice(const AudioDevice& active_device,
                                       bool notify,
                                       DeviceActivateType activate_by) {
  if (activate_by == DeviceActivateType::kActivateByUser) {
    audio_device_metrics_handler_.RecordUserSwitchAudioDevice(
        active_device.is_input);
  } else {
    audio_device_metrics_handler_.MaybeRecordSystemSwitchDecisionAndContext(
        active_device.is_input,
        active_device.is_input ? has_alternative_input_
                               : has_alternative_output_,
        /*is_switched=*/true, audio_devices_, previous_audio_devices_);
  }

  // Update *_selected_by_user_.
  // Including to unset it when selected by priority or by camera.
  if (active_device.is_input) {
    audio_device_metrics_handler_.set_input_device_selected_by_user(
        activate_by == DeviceActivateType::kActivateByUser);
  } else {
    audio_device_metrics_handler_.set_output_device_selected_by_user(
        activate_by == DeviceActivateType::kActivateByUser);
  }

  if (active_device.is_input) {
    CrasAudioClient::Get()->SetActiveInputNode(active_device.id);
  } else {
    CrasAudioClient::Get()->SetActiveOutputNode(active_device.id);
  }

  if (notify) {
    NotifyActiveNodeChanged(active_device.is_input);
  }

  // Active device has changed, update user preference and add the device to
  // most recently activated device list.
  if (features::IsAudioSelectionImprovementEnabled()) {
    SyncDevicePrefSetMap(active_device.is_input);
    audio_pref_handler_->UpdateMostRecentActivatedDeviceIdList(active_device);

    if (activate_by == DeviceActivateType::kActivateByUser) {
      // Remove notification if the hotplugged device that triggered the
      // notification has already been activated by user via settings or quick
      // settings.
      audio_selection_notification_handler_
          .RemoveNotificationIfHotpluggedDeviceActivated({active_device});
    }
  }

  // Save active state for the nodes.
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.is_input != active_device.is_input) {
      continue;
    }
    SaveDeviceState(device, device.active, activate_by);
  }
}

void CrasAudioHandler::SaveDeviceState(const AudioDevice& device,
                                       bool active,
                                       DeviceActivateType activate_by) {
  // Don't save the active state for non-simple usage device, which is invisible
  // to end users.
  if (!device.is_for_simple_usage()) {
    return;
  }

  if (!active) {
    audio_pref_handler_->SetDeviceActive(device, false, false);
  } else {
    switch (activate_by) {
      case DeviceActivateType::kActivateByUser:
        audio_pref_handler_->SetDeviceActive(device, true, true);
        break;
      case DeviceActivateType::kActivateByPriority:
        audio_pref_handler_->SetDeviceActive(device, true, false);
        break;
      default:
        // The device is made active due to its previous active state in prefs,
        // don't change its active state settings in prefs.
        break;
    }
  }
}

void CrasAudioHandler::SetVolumeGainPercentForDevice(uint64_t device_id,
                                                     int value) {
  const AudioDevice* device = GetDeviceFromId(device_id);
  if (!device) {
    return;
  }

  if (device->is_input) {
    SetInputNodeGainPercent(device_id, value);
  } else {
    SetOutputNodeVolumePercent(device_id, value);
  }
}

void CrasAudioHandler::SetMuteForDevice(uint64_t device_id, bool mute_on) {
  if (device_id == active_output_node_id_) {
    SetOutputMute(mute_on);
    return;
  }
  if (device_id == active_input_node_id_) {
    VLOG(1) << "SetMuteForDevice sets active input device id=" << "0x"
            << std::hex << device_id << " mute=" << mute_on;
    SetInputMute(mute_on, InputMuteChangeMethod::kOther);
    return;
  }

  const AudioDevice* device = GetDeviceFromId(device_id);
  // Input device's mute state is not recorded in the pref. crbug.com/365050.
  if (device && !device->is_input) {
    audio_pref_handler_->SetMuteValue(*device, mute_on);
  }
}

void CrasAudioHandler::SetMuteForDevice(
    uint64_t device_id,
    bool mute_on,
    CrasAudioHandler::AudioSettingsChangeSource source) {
  SetMuteForDevice(device_id, mute_on);
  if (device_id == active_output_node_id_) {
    base::UmaHistogramEnumeration(
        CrasAudioHandler::kOutputVolumeMuteSourceHistogramName, source);
  } else if (device_id == active_input_node_id_) {
    base::UmaHistogramEnumeration(
        CrasAudioHandler::kInputGainMuteSourceHistogramName, source);
  }
}

// If the HDMI device is the active output device, when the device enters/exits
// docking mode, or HDMI display changes resolution, or chromeos device
// suspends/resumes, cras will lose the HDMI output node for a short period of
// time, then rediscover it. This hotplug behavior will cause the audio output
// be leaked to the alternatvie active audio output during HDMI re-discovering
// period. See crbug.com/503667.
void CrasAudioHandler::SetActiveHDMIOutoutRediscoveringIfNecessary(
    bool force_rediscovering) {
  if (!GetDeviceFromId(active_output_node_id_)) {
    return;
  }

  // Marks the start of the HDMI re-discovering grace period, during which we
  // will mute the audio output to prevent it to be be leaked to the
  // alternative output device.
  if ((hdmi_rediscovering_ && force_rediscovering) ||
      (!hdmi_rediscovering_ && IsHDMIPrimaryOutputDevice())) {
    StartHDMIRediscoverGracePeriod();
  }
}

CrasAudioHandler::CrasAudioHandler(
    mojo::PendingRemote<media_session::mojom::MediaControllerManager>
        media_controller_manager,
    scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler,
    std::unique_ptr<Delegate> delegate)
    : media_controller_manager_(std::move(media_controller_manager)),
      audio_pref_handler_(audio_pref_handler),
      delegate_(std::move(delegate)) {
  SetupCrasAudioHandler(audio_pref_handler);
}

CrasAudioHandler::CrasAudioHandler(
    mojo::PendingRemote<media_session::mojom::MediaControllerManager>
        media_controller_manager,
    scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler)
    : media_controller_manager_(std::move(media_controller_manager)),
      audio_pref_handler_(audio_pref_handler) {
  SetupCrasAudioHandler(audio_pref_handler);
}

void CrasAudioHandler::SetupCrasAudioHandler(
    scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler) {
  DCHECK(audio_pref_handler);
  DCHECK(CrasAudioClient::Get());
  CrasAudioClient::Get()->AddObserver(this);
  audio_pref_handler_->AddAudioPrefObserver(this);
  ui::MicrophoneMuteSwitchMonitor::Get()->AddObserver(this);

  BindMediaControllerObserver();
  InitializeAudioState();
  // Unittest may not have the task runner for the current thread.
  if (base::SingleThreadTaskRunner::HasCurrentDefault()) {
    main_task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault();
  }

  DCHECK(!g_cras_audio_handler);
  g_cras_audio_handler = this;
}

CrasAudioHandler::~CrasAudioHandler() {
  hdmi_rediscover_timer_.Stop();
  DCHECK(CrasAudioClient::Get());
  CrasAudioClient::Get()->RemoveObserver(this);
  audio_pref_handler_->RemoveAudioPrefObserver(this);
  ui::MicrophoneMuteSwitchMonitor::Get()->RemoveObserver(this);

  DCHECK(g_cras_audio_handler);
  g_cras_audio_handler = nullptr;
}

void CrasAudioHandler::BindMediaControllerObserver() {
  if (!media_controller_manager_) {
    return;
  }
  media_controller_manager_->CreateActiveMediaController(
      media_session_controller_remote_.BindNewPipeAndPassReceiver());
  media_session_controller_remote_->AddObserver(
      media_controller_observer_receiver_.BindNewPipeAndPassRemote());
}

void CrasAudioHandler::AudioClientRestarted() {
  InitializeAudioState();
}

void CrasAudioHandler::NodesChanged() {
  if (cras_service_available_) {
    GetNodes();
    RequestVoiceIsolationUIAppearance();
  }
}

void CrasAudioHandler::OutputNodeVolumeChanged(uint64_t node_id, int volume) {
  const AudioDevice* device = this->GetDeviceFromId(node_id);
  if (!device || device->is_input) {
    LOG(ERROR) << "Unexpected OutputNodeVolumeChanged received on node: 0x"
               << std::hex << node_id;
    return;
  }
  if (volume < 0 || volume > 100) {
    LOG(ERROR) << "Unexpected OutputNodeVolumeChanged received on volume: "
               << volume;
    return;
  }

  // Sync internal volume state and notify UI for the change. We trust cras
  // signal to report the volume state of the device, no matter which source
  // set the volume, i.e., volume could be set from non-chrome source, like
  // Bluetooth headset, etc. Assume all active output devices share a single
  // volume.
  if (device->active) {
    output_volume_ = volume;
  }
  audio_pref_handler_->SetVolumeGainValue(*device, volume);

  if (initializing_audio_state_) {
    // Do not notify the observers for volume changed event if CrasAudioHandler
    // is initializing its state, i.e., the volume change event is in responding
    // to SetOutputNodeVolume request from intializaing audio state, not
    // from user action, no need to notify UI to pop uo the volume slider bar.
    if (init_node_id_ == node_id && init_volume_ == volume) {
      --init_volume_count_;
      if (!init_volume_count_) {
        initializing_audio_state_ = false;
      }
      return;
    } else {
      // Reset the initializing_audio_state_ in case SetOutputNodeVolume request
      // is lost by cras due to cras is not ready when CrasAudioHandler is being
      // initialized.
      initializing_audio_state_ = false;
      init_volume_count_ = 0;
    }
  }

  for (auto& observer : observers_) {
    observer.OnOutputNodeVolumeChanged(node_id, volume);
  }
}

void CrasAudioHandler::InputNodeGainChanged(uint64_t node_id, int gain) {
  const AudioDevice* device = this->GetDeviceFromId(node_id);

  if (!device || !device->is_input) {
    LOG(ERROR) << "Unexpexted InputNodeGainChanged received on node: 0x"
               << std::hex << node_id;
    return;
  }

  if (device->active) {
    input_gain_ = gain;
  }

  audio_pref_handler_->SetVolumeGainValue(*device, gain);

  for (auto& observer : observers_) {
    observer.OnInputNodeGainChanged(node_id, gain);
  }
}

void CrasAudioHandler::ActiveOutputNodeChanged(uint64_t node_id) {
  if (active_output_node_id_ == node_id) {
    return;
  }

  // Active audio output device should always be changed by chrome.
  // During system boot, cras may change active input to unknown device 0x1,
  // we don't need to log it, since it is not an valid device.
  if (GetDeviceFromId(node_id)) {
    LOG(WARNING) << "Active output node changed unexpectedly by system node_id="
                 << "0x" << std::hex << node_id;
  }
}

void CrasAudioHandler::ActiveInputNodeChanged(uint64_t node_id) {
  if (active_input_node_id_ == node_id) {
    return;
  }

  // Active audio input device should always be changed by chrome.
  // During system boot, cras may change active input to unknown device 0x2,
  // we don't need to log it, since it is not an valid device.
  if (GetDeviceFromId(node_id)) {
    LOG(WARNING) << "Active input node changed unexpectedly by system node_id="
                 << "0x" << std::hex << node_id;
  }
}

void CrasAudioHandler::HotwordTriggered(uint64_t tv_sec, uint64_t tv_nsec) {
  for (auto& observer : observers_) {
    observer.OnHotwordTriggered(tv_sec, tv_nsec);
  }
}

void CrasAudioHandler::NumberOfActiveStreamsChanged() {
  GetNumberOfOutputStreams();
}

void CrasAudioHandler::BluetoothBatteryChanged(const std::string& address,
                                               uint32_t level) {
  for (auto& observer : observers_) {
    observer.OnBluetoothBatteryChanged(address, level);
  }
}

void CrasAudioHandler::NumberOfInputStreamsWithPermissionChanged(
    const base::flat_map<std::string, uint32_t>& num_input_streams) {
  HandleGetNumberOfInputStreamsWithPermission(num_input_streams);
  for (auto& observer : observers_) {
    observer.OnNumberOfInputStreamsWithPermissionChanged();
  }
}

// static
std::unique_ptr<CrasAudioHandler::AudioSurvey>
CrasAudioHandler::AbstractAudioSurvey(
    const base::flat_map<std::string, std::string>& survey_specific_data) {
  auto survey = std::make_unique<CrasAudioHandler::AudioSurvey>();
  for (const auto& it : survey_specific_data) {
    if (it.first == CrasAudioHandler::kSurveyNameKey) {
      if (it.second == CrasAudioHandler::kSurveyNameGeneral) {
        survey->set_type(SurveyType::kGeneral);
      } else if (it.second == CrasAudioHandler::kSurveyNameBluetooth) {
        survey->set_type(SurveyType::kBluetooth);
      } else if (it.second == CrasAudioHandler::kSurveyNameOutputProc) {
        survey->set_type(SurveyType::kOutputProc);
      }
    } else {
      survey->AddData(it.first, it.second);
    }
  }
  return survey;
}

void CrasAudioHandler::SurveyTriggered(
    const base::flat_map<std::string, std::string>& survey_specific_data) {
  auto survey = CrasAudioHandler::AbstractAudioSurvey(survey_specific_data);

  for (auto& observer : observers_) {
    observer.OnSurveyTriggered(*survey);
  }
}

void CrasAudioHandler::SpeakOnMuteDetected() {
  for (auto& observer : observers_) {
    observer.OnSpeakOnMuteDetected();
  }
}

void CrasAudioHandler::EwmaPowerReported(double power) {
  ewma_power_ = power;
}

void CrasAudioHandler::NumStreamIgnoreUiGains(int32_t num) {
  num_stream_ignore_ui_gains_ = num;
  for (auto& observer : observers_) {
    observer.OnNumStreamIgnoreUiGainsChanged(num);
  }
}

void CrasAudioHandler::SidetoneSupportedChanged(bool supported) {
  sidetone_supported_ = supported;
}

void CrasAudioHandler::AudioEffectUIAppearanceChanged(
    VoiceIsolationUIAppearance appearance) {
  HandleGetVoiceIsolationUIAppearance(appearance);
}

void CrasAudioHandler::ResendBluetoothBattery() {
  CrasAudioClient::Get()->ResendBluetoothBattery();
}

void CrasAudioHandler::SetPrefHandlerForTesting(
    scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler) {
  audio_pref_handler_->RemoveAudioPrefObserver(this);
  audio_pref_handler_ = audio_pref_handler;
  audio_pref_handler_->AddAudioPrefObserver(this);
}

void CrasAudioHandler::OnAudioPolicyPrefChanged() {
  ApplyAudioPolicy();
}

void CrasAudioHandler::OnVoiceIsolationPrefChanged() {
  RefreshVoiceIsolationState();
  RefreshVoiceIsolationPreferredEffect();
}

const AudioDevice* CrasAudioHandler::GetDeviceFromId(uint64_t device_id) const {
  AudioDeviceMap::const_iterator it = audio_devices_.find(device_id);
  if (it == audio_devices_.end()) {
    return nullptr;
  }
  return &it->second;
}

AudioDevice CrasAudioHandler::ConvertAudioNodeWithModifiedPriority(
    const AudioNode& node) {
  AudioDevice device(node);
  device.user_priority = audio_pref_handler_->GetUserPriority(device);
  return device;
}

const AudioDevice* CrasAudioHandler::GetDeviceFromStableDeviceId(
    bool is_input,
    uint64_t stable_device_id) const {
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.is_input == is_input &&
        device.stable_device_id == stable_device_id) {
      return &device;
    }
  }
  return nullptr;
}

const AudioDevice* CrasAudioHandler::GetKeyboardMic() const {
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.is_input && device.type == AudioDeviceType::kKeyboardMic) {
      return &device;
    }
  }
  return nullptr;
}

const AudioDevice* CrasAudioHandler::GetHotwordDevice() const {
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.is_input && device.type == AudioDeviceType::kHotword) {
      return &device;
    }
  }
  return nullptr;
}

void CrasAudioHandler::SetupAudioInputState() {
  // Set the initial audio state to the ones read from audio prefs.
  const AudioDevice* device = GetDeviceFromId(active_input_node_id_);
  if (!device) {
    LOG(ERROR) << "Can't set up audio state for unknown input device id ="
               << "0x" << std::hex << active_input_node_id_;
    return;
  }
  input_gain_ = audio_pref_handler_->GetInputGainValue(device);
  VLOG(1) << "SetupAudioInputState for active device id=" << "0x" << std::hex
          << device->id << " mute=" << input_mute_on_;
  SetInputMuteInternal(input_mute_on_);

  SetInputNodeGain(active_input_node_id_, input_gain_);
}

void CrasAudioHandler::SetupAudioOutputState() {
  const AudioDevice* device = GetDeviceFromId(active_output_node_id_);
  if (!device) {
    LOG(ERROR) << "Can't set up audio state for unknown output device id ="
               << "0x" << std::hex << active_output_node_id_;
    return;
  }
  DCHECK(!device->is_input);
  // Mute the output during HDMI re-discovering grace period.
  if (hdmi_rediscovering_ && !IsHDMIPrimaryOutputDevice()) {
    VLOG(1) << "Mute the output during HDMI re-discovering grace period";
    SetOutputMuteInternal(true);
  } else {
    SetOutputMuteInternal(audio_pref_handler_->GetMuteValue(*device));
  }
  output_volume_ = audio_pref_handler_->GetOutputVolumeValue(device);

  if (initializing_audio_state_) {
    // During power up, InitializeAudioState() could be called twice, first
    // by CrasAudioHandler constructor, then by cras server restarting signal,
    // both sending SetOutputNodeVolume requests, and could lead to two
    // OutputNodeVolumeChanged signals.
    ++init_volume_count_;
    init_node_id_ = active_output_node_id_;
    init_volume_ = output_volume_;
  }
  SetOutputNodeVolume(active_output_node_id_, output_volume_);
}

// This sets up the state of an additional active node.
void CrasAudioHandler::SetupAdditionalActiveAudioNodeState(uint64_t node_id) {
  const AudioDevice* device = GetDeviceFromId(node_id);
  if (!device) {
    VLOG(1) << "Can't set up audio state for unknown device id =" << "0x"
            << std::hex << node_id;
    return;
  }

  DCHECK(node_id != active_output_node_id_ && node_id != active_input_node_id_);

  // Note: The mute state is a system wide state, we don't set mute per device,
  // but just keep the mute state consistent for the active node in prefs.
  // The output volume should be set to the same value for all active output
  // devices. For input devices, we don't restore their gain value so far.
  // TODO(jennyz): crbug.com/417418, track the status for the decison if
  // we should persist input gain value in prefs.
  if (!device->is_input) {
    audio_pref_handler_->SetMuteValue(*device, IsOutputMuted());
    SetOutputNodeVolumePercent(node_id, GetOutputVolumePercent());
  }
}

void CrasAudioHandler::InitializeAudioState() {
  initializing_audio_state_ = true;
  ApplyAudioPolicy();

  // Defer querying cras for GetNodes until cras service becomes available.
  cras_service_available_ = false;
  CrasAudioClient::Get()->WaitForServiceToBeAvailable(base::BindOnce(
      &CrasAudioHandler::InitializeAudioAfterCrasServiceAvailable,
      weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::InitializeAudioAfterCrasServiceAvailable(
    bool service_is_available) {
  if (!service_is_available) {
    LOG(ERROR) << "Cras service is not available";
    cras_service_available_ = false;
    return;
  }

  cras_service_available_ = true;
  GetDefaultOutputBufferSizeInternal();
  GetSystemAecSupported();
  GetSystemAecGroupId();
  GetSystemNsSupported();
  GetSystemAgcSupported();
  RequestGetAudioEffectDlcs();
  RequestVoiceIsolationUIAppearance();
  RequestNoiseCancellationSupported(base::BindOnce(
      &CrasAudioHandler::GetNodes, weak_ptr_factory_.GetWeakPtr()));
  RequestStyleTransferSupported(base::BindOnce(&CrasAudioHandler::GetNodes,
                                               weak_ptr_factory_.GetWeakPtr()));
  RequestHfpMicSrSupported(base::BindOnce(&CrasAudioHandler::GetNodes,
                                          weak_ptr_factory_.GetWeakPtr()));
  RequestSpatialAudioSupported(base::BindOnce(&CrasAudioHandler::GetNodes,
                                              weak_ptr_factory_.GetWeakPtr()));
  GetNumberOfOutputStreams();
  GetNumberOfNonChromeOutputStreams();
  GetNumberOfInputStreamsWithPermissionInternal();
  GetNumStreamIgnoreUiGains();
  GetNumberOfArcStreams();
  CrasAudioClient::Get()->SetFixA2dpPacketSize(
      base::FeatureList::IsEnabled(features::kBluetoothFixA2dpPacketSize));

  // Sets Floss enabled based on feature flag.
  CrasAudioClient::Get()->SetFlossEnabled(floss::features::IsFlossEnabled());

  input_muted_by_microphone_mute_switch_ = IsMicrophoneMuteSwitchOn();
  if (input_muted_by_microphone_mute_switch_) {
    SetInputMute(true, InputMuteChangeMethod::kPhysicalShutter);
  }

  // Refreshes voice isolation state in CRAS, in case CRAS restarts.
  RefreshVoiceIsolationState();

  // Sets speak-on-mute detection enabled based on local variable, it re-applies
  // the previous state if CRAS restarts.
  CrasAudioClient::Get()->SetSpeakOnMuteDetection(speak_on_mute_detection_on_);

  // Sets force respect ui gains enabled based on audio pref, it re-applies the
  // previous state if CRAS restarts.
  CrasAudioClient::Get()->SetForceRespectUiGains(GetForceRespectUiGainsState());

  UpdateSidetoneSupportedState();
  CrasAudioClient::Get()->SetSidetoneEnabled(sidetone_enabled_);
  CrasAudioClient::Get()->SetEwmaPowerReportEnabled(ewma_power_report_enabled_);
}

void CrasAudioHandler::ApplyAudioPolicy() {
  bool mute_on = !audio_pref_handler_->GetAudioOutputAllowedValue();

  if (output_mute_forced_by_policy_ == mute_on) {
    return;
  }

  output_mute_forced_by_policy_ = mute_on;
  UpdateAudioOutputMute();
  // Policy for audio input is handled by kAudioCaptureAllowed in the Chrome
  // media system.
}

void CrasAudioHandler::UpdateAudioOutputMute() {
  if (output_mute_forced_by_policy_ ||
      output_mute_forced_by_security_curtain_) {
    // Mute the device, but do not update the preference.
    SetOutputMuteInternal(true);
  } else {
    // Restore the mute state.
    const AudioDevice* device = GetDeviceFromId(active_output_node_id_);
    if (device) {
      SetOutputMuteInternal(audio_pref_handler_->GetMuteValue(*device));
    }
  }
}

void CrasAudioHandler::SetOutputNodeVolume(uint64_t node_id, int volume) {
  CrasAudioClient::Get()->SetOutputNodeVolume(node_id, volume);
}

void CrasAudioHandler::SetOutputNodeVolumePercent(uint64_t node_id,
                                                  int volume_percent) {
  const AudioDevice* device = GetDeviceFromId(node_id);
  if (!device || device->is_input) {
    return;
  }

  volume_percent = min(max(volume_percent, 0), 100);
  if (volume_percent <= kMuteThresholdPercent) {
    volume_percent = 0;
  }

  // Save the volume setting in pref in case this is called on non-active
  // node for configuration.
  audio_pref_handler_->SetVolumeGainValue(*device, volume_percent);

  if (device->active) {
    SetOutputNodeVolume(node_id, volume_percent);
  }
}

bool CrasAudioHandler::SetOutputMuteInternal(bool mute_on) {
  bool is_output_mute_forced = (output_mute_forced_by_policy_ ||
                                output_mute_forced_by_security_curtain_);

  if (is_output_mute_forced && !mute_on) {
    // Do not allow unmuting if the policy forces the device to remain muted.
    return false;
  }

  output_mute_on_ = mute_on;
  CrasAudioClient::Get()->SetOutputUserMute(mute_on);
  return true;
}

void CrasAudioHandler::SetInputNodeGain(uint64_t node_id, int gain) {
  CrasAudioClient::Get()->SetInputNodeGain(node_id, gain);
}

void CrasAudioHandler::SetInputNodeGainPercent(uint64_t node_id,
                                               int gain_percent) {
  const AudioDevice* device = GetDeviceFromId(node_id);
  if (!device || !device->is_input) {
    return;
  }

  // NOTE: We do not sanitize input gain values since the range is completely
  // dependent on the device.

  audio_pref_handler_->SetVolumeGainValue(*device, gain_percent);

  if (device->active) {
    SetInputNodeGain(node_id, gain_percent);
  }
}

void CrasAudioHandler::SetInputMuteInternal(bool mute_on) {
  // Do not allow unmuting the device if hardware microphone mute switch is on.
  // The switch disables internal microphone, and cras audio handler is expected
  // to keep system wide cras mute on while the switch is toggled (which should
  // ensure non-internal audio input devices are kept muted).
  //
  // Also do not allow unmuting the device if the security curtain is showing,
  // to prevent a remote admin from spying on the user
  if (!mute_on && (input_muted_by_microphone_mute_switch_ ||
                   input_mute_forced_by_security_curtain_)) {
    return;
  }

  input_mute_on_ = mute_on;
  CrasAudioClient::Get()->SetInputMute(mute_on);
}

void CrasAudioHandler::GetNodes() {
  CrasAudioClient::Get()->GetNodes(base::BindOnce(
      &CrasAudioHandler::HandleGetNodes, weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::GetNumberOfNonChromeOutputStreams() {
  CrasAudioClient::Get()->GetNumberOfNonChromeOutputStreams(
      base::BindOnce(&CrasAudioHandler::HandleGetNumberOfNonChromeOutputStreams,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::GetNumberOfOutputStreams() {
  CrasAudioClient::Get()->GetNumberOfActiveOutputStreams(
      base::BindOnce(&CrasAudioHandler::HandleGetNumActiveOutputStreams,
                     weak_ptr_factory_.GetWeakPtr()));
}

bool CrasAudioHandler::ChangeActiveDevice(
    const AudioDevice& new_active_device) {
  uint64_t& current_active_node_id = new_active_device.is_input
                                         ? active_input_node_id_
                                         : active_output_node_id_;
  // If the device we want to switch to is already the current active device,
  // do nothing.
  if (new_active_device.active &&
      new_active_device.id == current_active_node_id) {
    return false;
  }

  bool found_new_active_device = false;
  // Reset all other input or output devices' active status. The active audio
  // device from the previous user session can be remembered by cras, but not
  // in chrome. see crbug.com/273271.
  for (auto& item : audio_devices_) {
    AudioDevice& device = item.second;
    if (device.is_input == new_active_device.is_input &&
        device.id != new_active_device.id) {
      device.active = false;
    } else if (device.is_input == new_active_device.is_input &&
               device.id == new_active_device.id) {
      found_new_active_device = true;
    }
  }

  if (!found_new_active_device) {
    LOG(ERROR) << "Invalid new active device: " << new_active_device.ToString();
    return false;
  }

  // Update user priority whenever the audio device is activated.
  const AudioDevice* current_active_device =
      GetDeviceFromId(current_active_node_id);
  audio_pref_handler_->SetUserPriorityHigherThan(new_active_device,
                                                 current_active_device);

  // Set the current active input/output device to the new_active_device.
  current_active_node_id = new_active_device.id;
  audio_devices_[current_active_node_id].active = true;
  return true;
}

void CrasAudioHandler::SwitchToDevice(const AudioDevice& device,
                                      bool notify,
                                      DeviceActivateType activate_by) {
  if (!ChangeActiveDevice(device)) {
    // Record the decision of system not switching active device.
    if (activate_by != DeviceActivateType::kActivateByUser) {
      audio_device_metrics_handler_.MaybeRecordSystemSwitchDecisionAndContext(
          device.is_input,
          device.is_input ? has_alternative_input_ : has_alternative_output_,
          /*is_switched=*/false, audio_devices_, previous_audio_devices_);
    }
    return;
  }

  if (device.is_input) {
    SetupAudioInputState();
  } else {
    SetupAudioOutputState();
  }

  SetActiveDevice(device, notify, activate_by);

  // content::MediaStreamManager listens to
  // base::SystemMonitor::DevicesChangedObserver for audio devices,
  // and updates EnumerateDevices when OnDevicesChanged is called.
  base::SystemMonitor* monitor = base::SystemMonitor::Get();
  // In some unittest, |monitor| might be nullptr.
  if (!monitor) {
    return;
  }
  monitor->ProcessDevicesChanged(
      base::SystemMonitor::DeviceType::DEVTYPE_AUDIO);
}

bool CrasAudioHandler::HasDeviceChange(const AudioNodeList& new_nodes,
                                       bool is_input,
                                       AudioDeviceList* new_discovered,
                                       AudioDeviceList* removed_devices,
                                       bool* active_device_removed) {
  removed_devices->clear();
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (is_input != device.is_input) {
      continue;
    }
    if (!IsDeviceInList(device, new_nodes)) {
      removed_devices->push_back(device);
      if ((is_input && device.id == active_input_node_id_) ||
          (!is_input && device.id == active_output_node_id_)) {
        *active_device_removed = true;
      }
    }
  }

  bool new_or_changed_device = false;
  new_discovered->clear();

  for (const AudioNode& node : new_nodes) {
    if (is_input != node.is_input) {
      continue;
    }
    // Check if the new device is not in the old device list.
    AudioDevice device = ConvertAudioNodeWithModifiedPriority(node);
    DeviceStatus status = CheckDeviceStatus(device);
    if (status == NEW_DEVICE) {
      // When audio selection improvement flag is off, always put the new device
      // into the new discovered device list.
      // When audio selection improvement flag is on, only put simple usage
      // device into new discovered device list.
      if (!features::IsAudioSelectionImprovementEnabled() ||
          device.is_for_simple_usage()) {
        new_discovered->push_back(device);
      }
    }
    if (status == NEW_DEVICE || status == CHANGED_DEVICE) {
      new_or_changed_device = true;
    }
  }
  return new_or_changed_device || !removed_devices->empty();
}

CrasAudioHandler::DeviceStatus CrasAudioHandler::CheckDeviceStatus(
    const AudioDevice& device) {
  const AudioDevice* device_found =
      GetDeviceFromStableDeviceId(device.is_input, device.stable_device_id);
  if (!device_found) {
    return NEW_DEVICE;
  }

  if (!IsSameAudioDevice(device, *device_found)) {
    LOG(ERROR) << "Different Audio devices with same stable device id:"
               << " new device: " << device.ToString()
               << " old device: " << device_found->ToString();
    return CHANGED_DEVICE;
  }
  if (device.active != device_found->active) {
    return CHANGED_DEVICE;
  }
  return OLD_DEVICE;
}

void CrasAudioHandler::NotifyActiveNodeChanged(bool is_input) {
  if (is_input) {
    for (auto& observer : observers_) {
      observer.OnActiveInputNodeChanged();
    }
  } else {
    for (auto& observer : observers_) {
      observer.OnActiveOutputNodeChanged();
    }
  }
}

bool CrasAudioHandler::GetActiveDeviceFromUserPref(bool is_input,
                                                   AudioDevice* active_device) {
  bool found_active_device = false;
  bool last_active_device_activate_by_user = false;
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.is_input != is_input || !device.is_for_simple_usage()) {
      continue;
    }

    bool active = false;
    bool activate_by_user = false;
    // If the device entry is not found in prefs, it is likley a new audio
    // device plugged in after the cros is powered down. We should ignore the
    // previously saved active device, and select the active device by priority.
    // crbug.com/622045.
    if (!audio_pref_handler_->GetDeviceActive(device, &active,
                                              &activate_by_user)) {
      return false;
    }

    if (!active) {
      continue;
    }

    if (!found_active_device) {
      found_active_device = true;
      *active_device = device;
      last_active_device_activate_by_user = activate_by_user;
      continue;
    }

    // Choose the best one among multiple active devices from prefs.
    if (activate_by_user) {
      if (last_active_device_activate_by_user) {
        // If there are more than one active devices activated by user in the
        // prefs, most likely, after the device was shut down, and before it
        // is rebooted, user has plugged in some previously unplugged audio
        // devices. For such case, it does not make sense to honor the active
        // states in the prefs.
        VLOG(1) << "Found more than one user activated devices in the prefs.";
        return false;
      }
      // Device activated by user has higher priority than the one
      // is not activated by user.
      *active_device = device;
      last_active_device_activate_by_user = true;
    } else if (!last_active_device_activate_by_user) {
      // If there are more than one active devices activated by priority in the
      // prefs, most likely, cras is still enumerating the audio devices
      // progressively. For such case, it does not make sense to honor the
      // active states in the prefs.
      VLOG(1) << "Found more than one active devices by priority in the prefs.";
      return false;
    }
  }

  if (found_active_device && !active_device->is_for_simple_usage()) {
    // This is an odd case which is rare but possible to happen during cras
    // initialization depeneding the audio device enumation process. The only
    // audio node coming from cras is an internal audio device not visible
    // to user, such as AudioDeviceType::kPostMixLoopback.
    return false;
  }

  return found_active_device;
}

void CrasAudioHandler::PauseAllStreams() {
  if (media_controller_manager_) {
    media_controller_manager_->SuspendAllSessions();
  }
}

void CrasAudioHandler::HandleNonHotplugNodesChange(
    bool is_input,
    const AudioDeviceList& devices,
    const AudioDeviceList& hotplug_devices,
    bool has_device_change,
    bool has_device_removed,
    bool active_device_removed) {
  bool has_current_active_node =
      is_input ? active_input_node_id_ : active_output_node_id_;

  // No device change, extra NodesChanged signal received.
  if (!has_device_change && has_current_active_node) {
    return;
  }

  if (!hotplug_devices.empty()) {
    // Looks like a new chrome session starts.
    if (features::IsAudioSelectionImprovementEnabled()) {
      HandleSystemBoots(is_input, devices);
    } else {
      SwitchToPreviousActiveDeviceIfAvailable(is_input, devices);
    }
    return;
  }

  if (has_device_removed) {
    if (!active_device_removed && has_current_active_node) {
      // Removed a non-active device, keep the current active device.
      // Record the decision of system not switching active device.
      audio_device_metrics_handler_.MaybeRecordSystemSwitchDecisionAndContext(
          is_input, is_input ? has_alternative_input_ : has_alternative_output_,
          /*is_switched=*/false, audio_devices_, previous_audio_devices_);

      // When removing a non-active device, if the preferred device in the new
      // device set is not the currently active device, do not switch but keep
      // the current active device. Record metrics for Rule #2.
      if (features::IsAudioSelectionImprovementEnabled()) {
        const std::optional<AudioDevice> preferred_device =
            GetPreferredDeviceIfDeviceSetSeenBefore(
                is_input, GetSimpleUsageAudioDevices(audio_devices_, is_input));
        if (preferred_device.has_value()) {
          const AudioDevice* current_active_device = GetDeviceFromId(
              is_input ? active_input_node_id_ : active_output_node_id_);
          if (current_active_device &&
              current_active_device->stable_device_id !=
                  preferred_device->stable_device_id) {
            audio_device_metrics_handler_.RecordExceptionRulesMet(
                is_input
                    ? AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                          kInputRule2UnplugNonActiveDevice
                    : AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                          kOutputRule2UnplugNonActiveDevice);
          }
        }
      }

      return;
    }

    // Unplugged the current active device.
    if (active_device_removed) {
      // Pauses active streams when the active output device is
      // removed.
      if (!is_input) {
        PauseAllStreams();
      }

      if (!features::IsAudioSelectionImprovementEnabled()) {
        SwitchToTopPriorityDevice(devices);
        return;
      }

      CHECK(features::IsAudioSelectionImprovementEnabled());

      // If there is only one device left, activate it.
      if (devices.size() == 1) {
        SwitchToDevice(devices.front(), /*notify=*/true,
                       DeviceActivateType::kActivateByPriority);
        return;
      }

      // Check if the remaining device set was seen before, activate the
      // preferred one if so, otherwise, activate the most recently active
      // device.
      const std::optional<AudioDevice> preferred_device =
          GetPreferredDeviceIfDeviceSetSeenBefore(
              is_input, GetSimpleUsageAudioDevices(audio_devices_, is_input));
      if (preferred_device.has_value()) {
        SwitchToDevice(preferred_device.value(), /*notify=*/true,
                       DeviceActivateType::kActivateByPriority);
      } else {
        // Record metrics for Exception Rule #4 that unplugging an active device
        // and the remaining device set was not seen before.
        audio_device_metrics_handler_.RecordExceptionRulesMet(
            is_input ? AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                           kInputRule4UnplugDeviceCausesUnseenSet
                     : AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                           kOutputRule4UnplugDeviceCausesUnseenSet);

        if (!ActivateMostRecentActiveDevice(is_input)) {
          // Fall back to previous approach if no device in the most recently
          // active device list is currently connected.
          SwitchToTopPriorityDevice(devices);
        }
      }

      return;
    }
  }

  // Some unexpected error happens on cras side. See crbug.com/586026.
  // Either cras sent stale nodes to chrome again or cras triggered some
  // error. Restore the previously selected active.
  VLOG(1) << "Odd case from cras, the active node is lost unexpectedly.";
  SwitchToPreviousActiveDeviceIfAvailable(is_input, devices);
}

void CrasAudioHandler::HandleSystemBoots(bool is_input,
                                         const AudioDeviceList& devices) {
  // If there is only one device, activate it.
  if (devices.size() == 1) {
    SwitchToDevice(devices.front(), /*notify=*/true,
                   DeviceActivateType::kActivateByPriority);
    return;
  }

  // If the set of devices was seen before, activate the preferred one.
  const std::optional<AudioDevice> preferred_device =
      GetPreferredDeviceIfDeviceSetSeenBefore(
          is_input, GetSimpleUsageAudioDevices(audio_devices_, is_input));
  if (preferred_device.has_value()) {
    // Activate this device.
    SwitchToDevice(preferred_device.value(), /*notify=*/true,
                   DeviceActivateType::kActivateByPriority);
    return;
  }

  // Otherwise when the device set was not seen before, if a 3.5mm headphone is
  // connected, activate it. Do not show notification.
  for (const AudioDevice& device : devices) {
    if (device.type == AudioDeviceType::kHeadphone ||
        device.type == AudioDeviceType::kMic) {
      SwitchToDevice(device, /*notify=*/true,
                     DeviceActivateType::kActivateByPriority);
      return;
    }
  }

  // Otherwise, activate the most recent activated device and show
  // notification.
  if (ActivateMostRecentActiveDevice(is_input)) {
    should_show_notification_ = true;
    return;
  }

  // Otherwise when no most recent activated device, if there is an internal
  // device, activate it and show notification.
  for (const AudioDevice& device : devices) {
    if (device.type == AudioDeviceType::kInternalSpeaker ||
        device.type == AudioDeviceType::kInternalMic) {
      SwitchToDevice(device, /*notify=*/true,
                     DeviceActivateType::kActivateByPriority);
      should_show_notification_ = true;
      return;
    }
  }

  // Otherwise when no most recent activated device and no internal device (a
  // brand new chromebox), activate the highest priority and show
  // notification.
  // TODO(zhangwenyu): Add metrics for this case to understand how frequent it
  // happens.
  SwitchToTopPriorityDevice(devices);
  should_show_notification_ = true;
}

bool CrasAudioHandler::ActivateMostRecentActiveDevice(bool is_input) {
  const base::Value::List& ids =
      audio_pref_handler_->GetMostRecentActivatedDeviceIdList(is_input);
  for (int i = ids.size() - 1; i >= 0; i--) {
    std::optional<uint64_t> device_stable_id =
        ParseDeviceId(ids[i].GetString());
    if (!device_stable_id.has_value()) {
      continue;
    }
    const AudioDevice* device =
        GetDeviceFromStableDeviceId(is_input, *device_stable_id);
    if (!device) {
      continue;
    }
    SwitchToDevice(*device, /*notify=*/true,
                   DeviceActivateType::kActivateByPriority);
    return true;
  }
  return false;
}

bool CrasAudioHandler::ShouldSwitchToHotPlugDevice(
    const AudioDevice& hotplug_device) const {
  // Whenever 35mm headphone or mic is hot plugged, always pick it as the active
  // device.
  if (hotplug_device.type == AudioDeviceType::kHeadphone ||
      hotplug_device.type == AudioDeviceType::kMic) {
    return true;
  }

  const uint64_t active_node_id =
      hotplug_device.is_input ? active_input_node_id_ : active_output_node_id_;
  const AudioDevice* current_active_device = GetDeviceFromId(active_node_id);

  if (!current_active_device) {
    return true;
  }

  // Use built-in priority if hotplug_device or current_active_device has
  // kUserPriorityNone. Otherwise the newly plugged devices will never be
  // selected due to having user_priority = 0.
  // current_active_device can has kUserPriorityNone, if it is a new device
  // and it is activated when there is no active device (ex: the first active
  // device after boot).
  if ((hotplug_device.user_priority == kUserPriorityNone ||
       current_active_device->user_priority == kUserPriorityNone)) {
    return LessBuiltInPriority(*current_active_device, hotplug_device);
  }

  return LessUserPriority(*current_active_device, hotplug_device);
}

void CrasAudioHandler::HandleHotPlugDeviceByUserPriority(
    const AudioDevice& hotplug_device) {
  // This most likely may happen during the transition period of cras
  // initialization phase, in which a non-simple-usage node may appear like
  // a hotplug node.
  if (!hotplug_device.is_for_simple_usage()) {
    return;
  }

  if (features::IsAudioSelectionImprovementEnabled()) {
    HandleHotPlugDeviceWithNotification(hotplug_device);
    return;
  }

  if (ShouldSwitchToHotPlugDevice(hotplug_device)) {
    SwitchToDevice(hotplug_device, true,
                   DeviceActivateType::kActivateByPriority);
    return;
  } else {
    // Record the decision of system not switching active device.
    audio_device_metrics_handler_.MaybeRecordSystemSwitchDecisionAndContext(
        hotplug_device.is_input,
        hotplug_device.is_input ? has_alternative_input_
                                : has_alternative_output_,
        /*is_switched=*/false, audio_devices_, previous_audio_devices_);
  }

  // Do not active the hotplug device. The hotplug device is not the top
  // priority device.
  VLOG(1) << "Hotplug device remains inactive as its previous state:"
          << hotplug_device.ToString();
}

void CrasAudioHandler::SwitchToTopPriorityDevice(
    const AudioDeviceList& devices) {
  if (devices.empty()) {
    return;
  }

  // When the audio selection improvement flag is on, no user priority will be
  // maintained. Use built-in priority rather than user priority.
  AudioDevice top_device = features::IsAudioSelectionImprovementEnabled()
                               ? std::ranges::max(devices, LessBuiltInPriority)
                               : std::ranges::max(devices, LessUserPriority);
  if (!top_device.is_for_simple_usage()) {
    return;
  }

  // For the dual camera and dual microphone case, choose microphone
  // that is consistent to the active camera.
  if (IsFrontOrRearMic(top_device) && HasDualInternalMic() && IsCameraOn()) {
    ActivateInternalMicForActiveCamera();
    return;
  }

  SwitchToDevice(top_device, true, DeviceActivateType::kActivateByPriority);
}

void CrasAudioHandler::SwitchToPreviousActiveDeviceIfAvailable(
    bool is_input,
    const AudioDeviceList& devices) {
  // With new audio selection mechanism, activate the most recently active
  // device first.
  if (features::IsAudioSelectionImprovementEnabled() &&
      ActivateMostRecentActiveDevice(is_input)) {
    return;
  }

  AudioDevice previous_active_device;
  if (GetActiveDeviceFromUserPref(is_input, &previous_active_device)) {
    DCHECK(previous_active_device.is_for_simple_usage());
    // Switch to previous active device stored in user prefs.
    SwitchToDevice(previous_active_device, true,
                   DeviceActivateType::kActivateByRestorePreviousState);
  } else {
    // No previous active device, switch to the top priority device.
    SwitchToTopPriorityDevice(devices);
  }
}

void CrasAudioHandler::HandleRemoveNotification(bool is_input) {
  audio_selection_notification_handler_
      .RemoveNotificationIfHotpluggedDeviceDisconnected(
          is_input, GetSimpleUsageAudioDevices(audio_devices_, is_input));
}

void CrasAudioHandler::UpdateDevicesAndSwitchActive(
    const AudioNodeList& nodes) {
  AudioDeviceList output_devices;
  AudioDeviceList input_devices;
  AudioDeviceList hotplug_output_devices;
  AudioDeviceList hotplug_input_devices;
  AudioDeviceList removed_output_devices;
  AudioDeviceList removed_input_devices;
  bool active_output_removed = false;
  bool active_input_removed = false;
  bool output_devices_changed =
      HasDeviceChange(nodes, false, &hotplug_output_devices,
                      &removed_output_devices, &active_output_removed);
  bool input_devices_changed =
      HasDeviceChange(nodes, true, &hotplug_input_devices,
                      &removed_input_devices, &active_input_removed);

  if (!removed_input_devices.empty()) {
    // Add grace period in case the USB device is not firmly plugged, making
    // it disconnected and reconnected in a short period of time. In this case,
    // the notification should not be removed.
    remove_notification_timer_for_input_.Start(
        FROM_HERE, kRemoveNotificationDelay,
        base::BindOnce(&CrasAudioHandler::HandleRemoveNotification,
                       weak_ptr_factory_.GetWeakPtr(), /*is_input=*/true));
  }

  if (!removed_output_devices.empty()) {
    remove_notification_timer_for_output_.Start(
        FROM_HERE, kRemoveNotificationDelay,
        base::BindOnce(&CrasAudioHandler::HandleRemoveNotification,
                       weak_ptr_factory_.GetWeakPtr(), /*is_input=*/false));
  }

  // Record consecutive devices change metrics.
  if (input_devices_changed) {
    audio_device_metrics_handler_.RecordConsecutiveAudioDevicsChangeTimeElapsed(
        /*is_input=*/true, /*is_device_added=*/!hotplug_input_devices.empty());
  }
  if (output_devices_changed) {
    audio_device_metrics_handler_.RecordConsecutiveAudioDevicsChangeTimeElapsed(
        /*is_input=*/false,
        /*is_device_added=*/!hotplug_output_devices.empty());
  }

  std::vector<AudioDevice> devices;
  devices.reserve(nodes.size());
  for (AudioNode node : nodes) {
    devices.push_back(ConvertAudioNodeWithModifiedPriority(node));
  }

  // Updates the display_rotation to the internal speaker when it's added.
  for (AudioDevice device : devices) {
    DeviceStatus status = CheckDeviceStatus(device);
    if (status == NEW_DEVICE &&
        device.type == AudioDeviceType::kInternalSpeaker) {
      CrasAudioClient::Get()->SetDisplayRotation(device.id, display_rotation_);
    }
  }

  // Remove the least recently seen devices if there are too many devices.
  audio_pref_handler_->DropLeastRecentlySeenDevices(devices,
                                                    kMaxDeviceStoredInPref);

  // Before audio_devices_ is cleared, saves all audio device types to
  // previous_audio_devices_.
  previous_audio_devices_ = audio_devices_;

  audio_devices_.clear();
  has_alternative_input_ = false;
  has_alternative_output_ = false;

  // Local variables to help determine if there are more than one audio devices
  // currently connected. Note that kInternalMic, kFrontMic and kRearMic are
  // considered one audio device since they are all displayed as internal mic in
  // UI and user can not switch between them.
  bool has_internal_input_device = false;
  bool has_external_input_device = false;
  bool has_internal_output_device = false;
  bool has_external_output_device = false;

  for (AudioDevice device : devices) {
    // When audio selection improvement flag is on, ignore non simple usage
    // devices because users can't see/select them.
    if (features::IsAudioSelectionImprovementEnabled() &&
        !device.is_for_simple_usage()) {
      continue;
    }

    audio_devices_[device.id] = device;

    if (device.is_input) {
      input_devices.push_back(device);

      // If has_alternative_input_ has already been determined as true, no need
      // to calculate it again.
      if (has_alternative_input_) {
        continue;
      }

      bool has_two_external_input_devices =
          has_external_input_device && device.IsExternalDevice();
      bool has_one_internal_and_one_external_input_device =
          has_internal_input_device && device.IsExternalDevice();
      bool has_one_external_and_one_internal_input_device =
          has_external_input_device && device.IsInternalMic();
      if (has_two_external_input_devices ||
          has_one_internal_and_one_external_input_device ||
          has_one_external_and_one_internal_input_device) {
        has_alternative_input_ = true;
      }

      if (device.IsInternalMic()) {
        has_internal_input_device = true;
      } else if (device.IsExternalDevice()) {
        has_external_input_device = true;
      }

    } else {
      output_devices.push_back(device);

      // If has_alternative_output_ has already been determined as true, no need
      // to calculate it again.
      if (has_alternative_output_) {
        continue;
      }

      bool has_two_external_output_devices =
          has_external_output_device && device.IsExternalDevice();
      bool has_one_internal_and_one_external_output_device =
          has_internal_output_device && device.IsExternalDevice();
      bool has_one_external_and_one_internal_output_device =
          has_external_output_device && device.IsInternalSpeaker();
      if (has_two_external_output_devices ||
          has_one_internal_and_one_external_output_device ||
          has_one_external_and_one_internal_output_device) {
        has_alternative_output_ = true;
      }

      if (device.IsInternalSpeaker()) {
        has_internal_output_device = true;
      } else if (device.IsExternalDevice()) {
        has_external_output_device = true;
      }
    }
  }

  // Handle output device changes.
  HandleAudioDeviceChange(
      false, output_devices, hotplug_output_devices, output_devices_changed,
      !removed_output_devices.empty(), active_output_removed);

  // Handle input device changes.
  HandleAudioDeviceChange(true, input_devices, hotplug_input_devices,
                          input_devices_changed, !removed_input_devices.empty(),
                          active_input_removed);

  // At this moment, system has already made the switching or not switching
  // decision, set this flag to false.
  audio_device_metrics_handler_.set_is_chrome_restarts(false);

  if (features::IsAudioSelectionImprovementEnabled() &&
      should_show_notification_) {
    const AudioDevice* active_input_device =
        GetDeviceFromId(active_input_node_id_);
    const AudioDevice* active_output_device =
        GetDeviceFromId(active_output_node_id_);
    audio_selection_notification_handler_.ShowAudioSelectionNotification(
        hotplug_input_devices, hotplug_output_devices,
        active_input_device
            ? std::make_optional(active_input_device->display_name)
            : std::nullopt,
        active_output_device
            ? std::make_optional(active_output_device->display_name)
            : std::nullopt,
        base::BindRepeating(&CrasAudioHandler::SwitchToDevice,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindRepeating(&CrasAudioHandler::OpenSettingsAudioPage,
                            weak_ptr_factory_.GetWeakPtr()));

    // Reset show notification flag.
    should_show_notification_ = false;
  }

  // content::MediaStreamManager listens to
  // base::SystemMonitor::DevicesChangedObserver for audio devices,
  // and updates EnumerateDevices when OnDevicesChanged is called.
  base::SystemMonitor* monitor = base::SystemMonitor::Get();
  // In some unittest, |monitor| might be nullptr.
  if (!monitor) {
    return;
  }
  monitor->ProcessDevicesChanged(
      base::SystemMonitor::DeviceType::DEVTYPE_AUDIO);
}

void CrasAudioHandler::HandleAudioDeviceChange(
    bool is_input,
    const AudioDeviceList& devices,
    const AudioDeviceList& hotplug_devices,
    bool has_device_change,
    bool has_device_removed,
    bool active_device_removed) {
  uint64_t& active_node_id =
      is_input ? active_input_node_id_ : active_output_node_id_;

  if (has_device_change) {
    // Mark device selected by the system, including when the algorithm
    // does nothing ultimately. We still treat not switching the device
    // as a decision of the algorithm.
    if (is_input) {
      audio_device_metrics_handler_.set_input_device_selected_by_user(false);
    } else {
      audio_device_metrics_handler_.set_output_device_selected_by_user(false);
    }
  }

  // No audio devices found.
  if (devices.empty()) {
    VLOG(1) << "No " << (is_input ? "input" : "output") << " devices found";
    active_node_id = 0;
    NotifyActiveNodeChanged(is_input);
    return;
  }

  // If the previous active device is removed from the new node list,
  // or changed to inactive by cras, reset active_node_id.
  // See crbug.com/478968.
  const AudioDevice* active_device = GetDeviceFromId(active_node_id);
  if (!active_device || !active_device->active) {
    active_node_id = 0;
  }

  if (!active_node_id || hotplug_devices.empty() ||
      hotplug_devices.size() > 1) {
    HandleNonHotplugNodesChange(is_input, devices, hotplug_devices,
                                has_device_change, has_device_removed,
                                active_device_removed);
    if (features::IsAudioSelectionImprovementEnabled()) {
      SyncDevicePrefSetMap(is_input);
    }
  } else {
    // Typical user hotplug case.
    HandleHotPlugDeviceByUserPriority(hotplug_devices.front());
  }
}

void CrasAudioHandler::HandleGetNodes(std::optional<AudioNodeList> node_list) {
  if (!node_list.has_value()) {
    LOG(ERROR) << "Failed to retrieve audio nodes data";
    return;
  }

  if (node_list->empty()) {
    return;
  }

  UpdateDevicesAndSwitchActive(node_list.value());

  // Always set the hfp_mic_sr state on NodesChange event.
  RefreshHfpMicSrState();

  for (auto& observer : observers_) {
    observer.OnAudioNodesChanged();
  }
}

void CrasAudioHandler::HandleGetNumberOfNonChromeOutputStreams(
    std::optional<int32_t> new_output_streams_count) {
  if (!new_output_streams_count.has_value()) {
    LOG(ERROR) << "Failed to retrieve number of active output streams.";
    return;
  }
  DCHECK_GE(*new_output_streams_count, 0);

  if (*new_output_streams_count > 0 &&
      num_active_nonchrome_output_streams_ == 0) {
    for (auto& observer : observers_) {
      observer.OnNonChromeOutputStarted();
    }
  } else if (*new_output_streams_count == 0 &&
             num_active_nonchrome_output_streams_ > 0) {
    for (auto& observer : observers_) {
      observer.OnNonChromeOutputStopped();
    }
  }
  num_active_nonchrome_output_streams_ = *new_output_streams_count;
}

void CrasAudioHandler::HandleGetNumActiveOutputStreams(
    std::optional<int> new_output_streams_count) {
  if (!new_output_streams_count.has_value()) {
    LOG(ERROR) << "Failed to retrieve number of active output streams";
    return;
  }

  DCHECK_GE(*new_output_streams_count, 0);
  if (*new_output_streams_count > 0 && num_active_output_streams_ == 0) {
    for (auto& observer : observers_) {
      observer.OnOutputStarted();
    }
  } else if (*new_output_streams_count == 0 && num_active_output_streams_ > 0) {
    for (auto& observer : observers_) {
      observer.OnOutputStopped();
    }
  }
  num_active_output_streams_ = *new_output_streams_count;
}

void CrasAudioHandler::AddAdditionalActiveNode(uint64_t node_id, bool notify) {
  const AudioDevice* device = GetDeviceFromId(node_id);
  if (!device) {
    VLOG(1) << "AddActiveInputNode: Cannot find device id=" << "0x" << std::hex
            << node_id;
    return;
  }

  audio_devices_[node_id].active = true;
  SetupAdditionalActiveAudioNodeState(node_id);

  if (device->is_input) {
    DCHECK(node_id != active_input_node_id_);
    CrasAudioClient::Get()->AddActiveInputNode(node_id);
    if (notify) {
      NotifyActiveNodeChanged(true);
    }
  } else {
    DCHECK(node_id != active_output_node_id_);
    CrasAudioClient::Get()->AddActiveOutputNode(node_id);
    if (notify) {
      NotifyActiveNodeChanged(false);
    }
  }
}

void CrasAudioHandler::RemoveActiveNodeInternal(uint64_t node_id, bool notify) {
  const AudioDevice* device = GetDeviceFromId(node_id);
  if (!device) {
    VLOG(1) << "RemoveActiveInputNode: Cannot find device id=" << "0x"
            << std::hex << node_id;
    return;
  }

  audio_devices_[node_id].active = false;
  if (device->is_input) {
    if (node_id == active_input_node_id_) {
      active_input_node_id_ = 0;
    }
    CrasAudioClient::Get()->RemoveActiveInputNode(node_id);
    if (notify) {
      NotifyActiveNodeChanged(true);
    }
  } else {
    if (node_id == active_output_node_id_) {
      active_output_node_id_ = 0;
    }
    CrasAudioClient::Get()->RemoveActiveOutputNode(node_id);
    if (notify) {
      NotifyActiveNodeChanged(false);
    }
  }
}

void CrasAudioHandler::UpdateAudioAfterHDMIRediscoverGracePeriod() {
  VLOG(1) << "HDMI output re-discover grace period ends.";
  hdmi_rediscovering_ = false;
  if (!IsOutputMutedForDevice(active_output_node_id_)) {
    // Unmute the audio output after the HDMI transition period.
    VLOG(1) << "Unmute output after HDMI rediscovering grace period.";
    SetOutputMuteInternal(false);
  }
}

bool CrasAudioHandler::IsHDMIPrimaryOutputDevice() const {
  const AudioDevice* device = GetDeviceFromId(active_output_node_id_);
  return device && device->type == AudioDeviceType::kHdmi;
}

void CrasAudioHandler::StartHDMIRediscoverGracePeriod() {
  VLOG(1) << "Start HDMI rediscovering grace period.";
  hdmi_rediscovering_ = true;
  hdmi_rediscover_timer_.Stop();
  hdmi_rediscover_timer_.Start(
      FROM_HERE,
      base::Milliseconds(hdmi_rediscover_grace_period_duration_in_ms_), this,
      &CrasAudioHandler::UpdateAudioAfterHDMIRediscoverGracePeriod);
}

void CrasAudioHandler::SetHDMIRediscoverGracePeriodForTesting(
    int duration_in_ms) {
  hdmi_rediscover_grace_period_duration_in_ms_ = duration_in_ms;
}

void CrasAudioHandler::ActivateMicForCamera(
    media::VideoFacingMode camera_facing) {
  const AudioDevice* mic = GetMicForCamera(camera_facing);
  if (!mic || mic->active) {
    return;
  }

  SwitchToDevice(*mic, true, DeviceActivateType::kActivateByCamera);
}

void CrasAudioHandler::ActivateInternalMicForActiveCamera() {
  DCHECK(IsCameraOn());
  if (HasDualInternalMic()) {
    media::VideoFacingMode facing = front_camera_on_
                                        ? media::MEDIA_VIDEO_FACING_USER
                                        : media::MEDIA_VIDEO_FACING_ENVIRONMENT;
    ActivateMicForCamera(facing);
  }
}

// For the dual microphone case, from user point of view, they only see internal
// microphone in UI. Chrome will make the best decision on which one to pick.
// If the camera is off, the front microphone should be picked as the default
// active microphone. Otherwise, it will switch to the microphone that
// matches the active camera, i.e. front microphone for front camera and
// rear microphone for rear camera.
void CrasAudioHandler::SwitchToFrontOrRearMic() {
  DCHECK(HasDualInternalMic());
  if (IsCameraOn()) {
    ActivateInternalMicForActiveCamera();
  } else {
    SwitchToDevice(*GetDeviceByType(AudioDeviceType::kFrontMic), true,
                   DeviceActivateType::kActivateByUser);
  }
}

const AudioDevice* CrasAudioHandler::GetMicForCamera(
    media::VideoFacingMode camera_facing) {
  switch (camera_facing) {
    case media::MEDIA_VIDEO_FACING_USER:
      return GetDeviceByType(AudioDeviceType::kFrontMic);
    case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
      return GetDeviceByType(AudioDeviceType::kRearMic);
    default:
      NOTREACHED();
  }
}

bool CrasAudioHandler::HasDualInternalMic() const {
  bool has_front_mic = false;
  bool has_rear_mic = false;
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (device.type == AudioDeviceType::kFrontMic) {
      has_front_mic = true;
    } else if (device.type == AudioDeviceType::kRearMic) {
      has_rear_mic = true;
    }
    if (has_front_mic && has_rear_mic) {
      break;
    }
  }
  return has_front_mic && has_rear_mic;
}

bool CrasAudioHandler::HasActiveInputDeviceForSimpleUsage() const {
  const AudioDevice* active_input_device =
      GetDeviceFromId(active_input_node_id_);
  if (active_input_device) {
    return active_input_device->is_for_simple_usage();
  }
  return false;
}

bool CrasAudioHandler::IsFrontOrRearMic(const AudioDevice& device) const {
  return device.is_input && (device.type == AudioDeviceType::kFrontMic ||
                             device.type == AudioDeviceType::kRearMic);
}

bool CrasAudioHandler::IsCameraOn() const {
  return front_camera_on_ || rear_camera_on_;
}

bool CrasAudioHandler::HasExternalDevice(bool is_input) const {
  for (const auto& item : audio_devices_) {
    const AudioDevice& device = item.second;
    if (is_input == device.is_input && device.IsExternalDevice()) {
      return true;
    }
  }
  return false;
}

void CrasAudioHandler::GetNumberOfInputStreamsWithPermissionInternal() {
  CrasAudioClient::Get()->GetNumberOfInputStreamsWithPermission(base::BindOnce(
      &CrasAudioHandler::HandleGetNumberOfInputStreamsWithPermission,
      weak_ptr_factory_.GetWeakPtr()));
}

// static
CrasAudioHandler::ClientType CrasAudioHandler::ConvertClientTypeStringToEnum(
    std::string client_type_str) {
  if (client_type_str == "CRAS_CLIENT_TYPE_PLUGIN") {
    return ClientType::VM_PLUGIN;
  } else if (client_type_str == "CRAS_CLIENT_TYPE_CROSVM") {
    return ClientType::VM_TERMINA;
  } else if (client_type_str == "CRAS_CLIENT_TYPE_CHROME") {
    return ClientType::CHROME;
  } else if (client_type_str == "CRAS_CLIENT_TYPE_ARC" ||
             client_type_str == "CRAS_CLIENT_TYPE_ARCVM") {
    return ClientType::ARC;
  } else if (client_type_str == "CRAS_CLIENT_TYPE_BOREALIS") {
    return ClientType::VM_BOREALIS;
  } else {
    return ClientType::UNKNOWN;
  }
}

void CrasAudioHandler::HandleGetNumberOfInputStreamsWithPermission(
    std::optional<base::flat_map<std::string, uint32_t>> num_input_streams) {
  if (!num_input_streams.has_value()) {
    LOG(ERROR) << "Failed to retrieve number of input streams with permission";
    return;
  }
  number_of_input_streams_with_permission_.clear();
  for (const auto& it : *num_input_streams) {
    CrasAudioHandler::ClientType type = ConvertClientTypeStringToEnum(it.first);
    if (type != ClientType::UNKNOWN) {
      number_of_input_streams_with_permission_[type] = it.second;
    }
  }
}

void CrasAudioHandler::GetDefaultOutputBufferSizeInternal() {
  CrasAudioClient::Get()->GetDefaultOutputBufferSize(
      base::BindOnce(&CrasAudioHandler::HandleGetDefaultOutputBufferSize,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetDefaultOutputBufferSize(
    std::optional<int> buffer_size) {
  if (!buffer_size.has_value()) {
    LOG(ERROR) << "Failed to retrieve output buffer size";
    return;
  }

  default_output_buffer_size_ = buffer_size.value();
}

bool CrasAudioHandler::noise_cancellation_supported() const {
  return noise_cancellation_supported_;
}

bool CrasAudioHandler::style_transfer_supported() const {
  return style_transfer_supported_;
}

bool CrasAudioHandler::hfp_mic_sr_supported() const {
  return hfp_mic_sr_supported_;
}

bool CrasAudioHandler::system_aec_supported() const {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  return system_aec_supported_;
}

bool CrasAudioHandler::spatial_audio_supported() const {
  return spatial_audio_supported_;
}

// GetSystemAecSupported() is only called in the same thread
// as the CrasAudioHandler constructor. We are safe here without
// thread check, because unittest may not have the task runner
// for the current thread.
void CrasAudioHandler::GetSystemAecSupported() {
  CrasAudioClient::Get()->GetSystemAecSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetSystemAecSupported,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetSystemAecSupported(
    std::optional<bool> system_aec_supported) {
  if (!system_aec_supported.has_value()) {
    LOG(ERROR) << "Failed to retrieve system aec supported";
    return;
  }
  system_aec_supported_ = system_aec_supported.value();
}

int32_t CrasAudioHandler::system_aec_group_id() const {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  return system_aec_group_id_;
}

// GetSystemAecGroupId() is only called in the same thread
// as the CrasAudioHandler constructor. We are safe here without
// thread check, because unittest may not have the task runner
// for the current thread.
void CrasAudioHandler::GetSystemAecGroupId() {
  CrasAudioClient::Get()->GetSystemAecGroupId(
      base::BindOnce(&CrasAudioHandler::HandleGetSystemAecGroupId,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetSystemAecGroupId(
    std::optional<int32_t> system_aec_group_id) {
  if (!system_aec_group_id.has_value()) {
    // If the group Id is not available, set the ID to reflect that.
    system_aec_group_id_ = kSystemAecGroupIdNotAvailable;
    return;
  }
  system_aec_group_id_ = system_aec_group_id.value();
}

bool CrasAudioHandler::system_ns_supported() const {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  return system_ns_supported_;
}

// GetSystemNsSupported() is only called in the same thread
// as the CrasAudioHandler constructor. We are safe here without
// thread check, because unittest may not have the task runner
// for the current thread.
void CrasAudioHandler::GetSystemNsSupported() {
  CrasAudioClient::Get()->GetSystemNsSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetSystemNsSupported,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetSystemNsSupported(
    std::optional<bool> system_ns_supported) {
  if (!system_ns_supported.has_value()) {
    LOG(ERROR) << "Failed to retrieve system ns supported";
    return;
  }
  system_ns_supported_ = system_ns_supported.value();
}

bool CrasAudioHandler::system_agc_supported() const {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  return system_agc_supported_;
}

int32_t CrasAudioHandler::num_stream_ignore_ui_gains() const {
  return num_stream_ignore_ui_gains_;
}

// GetSystemAgcSupported() is only called in the same thread
// as the CrasAudioHandler constructor. We are safe here without
// thread check, because unittest may not have the task runner
// for the current thread.
void CrasAudioHandler::GetSystemAgcSupported() {
  CrasAudioClient::Get()->GetSystemAgcSupported(
      base::BindOnce(&CrasAudioHandler::HandleGetSystemAgcSupported,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetSystemAgcSupported(
    std::optional<bool> system_agc_supported) {
  if (!system_agc_supported.has_value()) {
    LOG(ERROR) << "Failed to retrieve system agc supported";
    return;
  }
  system_agc_supported_ = system_agc_supported.value();
}

void CrasAudioHandler::GetNumStreamIgnoreUiGains() {
  CrasAudioClient::Get()->GetNumStreamIgnoreUiGains(
      base::BindOnce(&CrasAudioHandler::HandleGetNumStreamIgnoreUiGains,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetNumStreamIgnoreUiGains(
    std::optional<int32_t> new_stream_ignore_ui_gains_count) {
  if (!new_stream_ignore_ui_gains_count.has_value()) {
    LOG(ERROR) << "Failed to retrieve number of ignore ui gains streams.";
    return;
  }
  DCHECK_GE(*new_stream_ignore_ui_gains_count, 0);

  if (*new_stream_ignore_ui_gains_count != num_stream_ignore_ui_gains_) {
    for (auto& observer : observers_) {
      observer.OnNumStreamIgnoreUiGainsChanged(
          *new_stream_ignore_ui_gains_count);
    }
  }

  num_stream_ignore_ui_gains_ = *new_stream_ignore_ui_gains_count;
}

void CrasAudioHandler::GetNumberOfArcStreams() {
  CrasAudioClient::Get()->GetNumberOfArcStreams(
      base::BindOnce(&CrasAudioHandler::HandleGetNumberOfArcStreams,
                     weak_ptr_factory_.GetWeakPtr()));
}

void CrasAudioHandler::HandleGetNumberOfArcStreams(
    std::optional<int32_t> new_num_arc_streams) {
  if (!new_num_arc_streams.has_value()) {
    LOG(ERROR) << "Failed to retrieve number of active ARC streams.";
    return;
  }
  DCHECK_GE(*new_num_arc_streams, 0);

  if (*new_num_arc_streams != num_arc_streams_) {
    for (auto& observer : observers_) {
      observer.OnNumberOfArcStreamsChanged(*new_num_arc_streams);
    }
  }

  num_arc_streams_ = *new_num_arc_streams;
}

const std::optional<AudioDevice>
CrasAudioHandler::GetPreferredDeviceIfDeviceSetSeenBefore(
    bool is_input,
    const AudioDeviceList& devices) const {
  std::optional<uint64_t> id =
      audio_pref_handler_->GetPreferredDeviceFromPreferenceSet(is_input,
                                                               devices);

  if (!id.has_value()) {
    return std::nullopt;
  }

  const AudioDevice* device = GetDeviceFromStableDeviceId(is_input, id.value());
  if (!device) {
    return std::nullopt;
  }

  return *device;
}

void CrasAudioHandler::SyncDevicePrefSetMap(bool is_input) {
  const uint64_t& active_node_id =
      is_input ? active_input_node_id_ : active_output_node_id_;
  const AudioDevice* active_device = GetDeviceFromId(active_node_id);
  if (!active_device) {
    VLOG(1) << "SyncDevicePrefSetMap: No active device found.";
    // Early return since no active_device is available to sync.
    return;
  }

  audio_pref_handler_->UpdateDevicePreferenceSet(
      GetSimpleUsageAudioDevices(audio_devices_, is_input), *active_device);
}

void CrasAudioHandler::HandleHotPlugDeviceWithNotification(
    const AudioDevice& hotplug_device) {
  // Whenever a device with privilege is hot plugged, always pick it as the
  // active device. Make sure has_privilege is called only when the
  // kAudioSelectionImprovement flag is on.
  CHECK(features::IsAudioSelectionImprovementEnabled());
  if (hotplug_device.has_privilege()) {
    SwitchToDevice(hotplug_device, /*notify=*/true,
                   DeviceActivateType::kActivateByPriority);

    // Record audio selection exception rule #1.
    audio_device_metrics_handler_.RecordExceptionRulesMet(
        hotplug_device.is_input
            ? AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                  kInputRule1HotPlugPrivilegedDevice
            : AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                  kOutputRule1HotPlugPrivilegedDevice);
    return;
  }

  // Check if current set of audio devices was seen before.
  const std::optional<AudioDevice> preferred_device =
      GetPreferredDeviceIfDeviceSetSeenBefore(
          hotplug_device.is_input,
          GetSimpleUsageAudioDevices(audio_devices_,
                                     /*is_input=*/hotplug_device.is_input));
  // If the device set was seen and the preferred device is the hotplug device,
  // activate it. This is the only case that the hot plug device will be
  // activated.
  if (preferred_device.has_value() &&
      preferred_device->stable_device_id == hotplug_device.stable_device_id) {
    SwitchToDevice(hotplug_device, /*notify=*/true,
                   DeviceActivateType::kActivateByPriority);
    return;
  }

  // Otherwise sync the device preference set map.
  SyncDevicePrefSetMap(hotplug_device.is_input);

  if (!preferred_device.has_value()) {
    // The device set was not seen. Show notification to let user make decision.
    // Early return here since below metrics are not supposed to be recorded.
    should_show_notification_ = true;
    return;
  }

  // Only record system switch decision metrics when the set of devices is seen
  // but the system decides to not switch to it. Do not record if this set of
  // device is not seen and notification is shown. Because the system
  // technically does not make any decisions but let users make the decision.
  audio_device_metrics_handler_.MaybeRecordSystemSwitchDecisionAndContext(
      /*is_input=*/hotplug_device.is_input,
      /*has_alternative_device=*/hotplug_device.is_input
          ? has_alternative_input_
          : has_alternative_output_,
      /*is_switched=*/false, audio_devices_, previous_audio_devices_);

  // If the preferred device is not the hot plug device and also not the
  // currently activated device, do not switch but keep the currently active
  // device activated, according to audio selection exception rule #3, detailed
  // in go/audio-io.
  const AudioDevice* current_active_device = GetDeviceFromId(
      hotplug_device.is_input ? active_input_node_id_ : active_output_node_id_);
  if (current_active_device && current_active_device->stable_device_id !=
                                   preferred_device->stable_device_id) {
    audio_device_metrics_handler_.RecordExceptionRulesMet(
        hotplug_device.is_input
            ? AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                  kInputRule3HotPlugUnpreferredDevice
            : AudioDeviceMetricsHandler::AudioSelectionExceptionRules::
                  kOutputRule3HotPlugUnpreferredDevice);
  }
}

void CrasAudioHandler::OpenSettingsAudioPage() {
  if (delegate_) {
    delegate_->OpenSettingsAudioPage();
  }
}

ScopedCrasAudioHandlerForTesting::ScopedCrasAudioHandlerForTesting() {
  CHECK(!CrasAudioClient::Get())
      << "ScopedCrasAudioHandlerForTesting expects that there is no "
         "CrasAudioClient running at its constructor.";

  fake_cras_audio_client_ = std::make_unique<FakeCrasAudioClient>();

  CrasAudioHandler::InitializeForTesting();
}

ScopedCrasAudioHandlerForTesting::~ScopedCrasAudioHandlerForTesting() {
  CrasAudioHandler::Shutdown();
}

CrasAudioHandler& ScopedCrasAudioHandlerForTesting::Get() {
  return *CrasAudioHandler::Get();
}

int32_t CrasAudioHandler::NumberOfNonChromeOutputStreams() const {
  return num_active_nonchrome_output_streams_;
}

int32_t CrasAudioHandler::NumberOfChromeOutputStreams() const {
  return num_active_output_streams_;
}

int32_t CrasAudioHandler::NumberOfArcStreams() const {
  return num_arc_streams_;
}

void CrasAudioHandler::SetNumberOfArcStreamsForTesting(int32_t num) {
  num_arc_streams_ = num;
}

}  // namespace ash