summaryrefslogtreecommitdiffstats
path: root/hal/audio_hw.c
blob: 5bbd595605b459e399838937ff52f6980797fbb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
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
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
/*
 * Copyright (c) 2013-2019, The Linux Foundation. All rights reserved.
 * Not a Contribution.
 *
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file was modified by DTS, Inc. The portions of the
 * code modified by DTS, Inc are copyrighted and
 * licensed separately, as follows:
 *
 * (C) 2014 DTS, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "audio_hw_primary"
#define ATRACE_TAG (ATRACE_TAG_AUDIO|ATRACE_TAG_HAL)
/*#define LOG_NDEBUG 0*/
/*#define VERY_VERY_VERBOSE_LOGGING*/
#ifdef VERY_VERY_VERBOSE_LOGGING
#define ALOGVV ALOGV
#else
#define ALOGVV(a...) do { } while(0)
#endif

#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/time.h>
#include <stdlib.h>
#include <math.h>
#include <dlfcn.h>
#include <sys/resource.h>
#include <sys/prctl.h>

#include <log/log.h>
#include <cutils/trace.h>
#include <cutils/str_parms.h>
#include <cutils/properties.h>
#include <cutils/atomic.h>
#include <cutils/sched_policy.h>
#include <hardware/audio_effect.h>
#include <hardware/audio_alsaops.h>
#include <system/thread_defs.h>
#include <tinyalsa/asoundlib.h>
#include <audio_effects/effect_aec.h>
#include <audio_effects/effect_ns.h>
#include <audio_utils/format.h>
#include "audio_hw.h"
#include "audio_perf.h"
#include "platform_api.h"
#include <platform.h>
#include "audio_extn.h"
#include "voice_extn.h"
#include "ip_hdlr_intf.h"

#include "sound/compress_params.h"
#include "sound/asound.h"

#ifdef DYNAMIC_LOG_ENABLED
#include <log_xml_parser.h>
#define LOG_MASK HAL_MOD_FILE_AUDIO_HW
#include <log_utils.h>
#endif

#define COMPRESS_OFFLOAD_NUM_FRAGMENTS 4
/*DIRECT PCM has same buffer sizes as DEEP Buffer*/
#define DIRECT_PCM_NUM_FRAGMENTS 2
#define COMPRESS_PLAYBACK_VOLUME_MAX 0x2000
#define VOIP_PLAYBACK_VOLUME_MAX 0x2000
#define MMAP_PLAYBACK_VOLUME_MAX 0x2000
#define PCM_PLAYBACK_VOLUME_MAX 0x2000
#define DSD_VOLUME_MIN_DB (-110)
#define INVALID_OUT_VOLUME -1

#define RECORD_GAIN_MIN 0.0f
#define RECORD_GAIN_MAX 1.0f
#define RECORD_VOLUME_CTL_MAX 0x2000

/* treat as unsigned Q1.13 */
#define APP_TYPE_GAIN_DEFAULT         0x2000

#define PROXY_OPEN_RETRY_COUNT           100
#define PROXY_OPEN_WAIT_TIME             20

#define GET_USECASE_AUDIO_PLAYBACK_PRIMARY(db) \
         (db)? USECASE_AUDIO_PLAYBACK_DEEP_BUFFER : \
               USECASE_AUDIO_PLAYBACK_LOW_LATENCY
#define GET_PCM_CONFIG_AUDIO_PLAYBACK_PRIMARY(db) \
         (db)? pcm_config_deep_buffer : pcm_config_low_latency

#define ULL_PERIOD_SIZE (DEFAULT_OUTPUT_SAMPLING_RATE/1000)
#define DEFAULT_VOIP_BUF_DURATION_MS 20
#define DEFAULT_VOIP_BIT_DEPTH_BYTE sizeof(int16_t)
#define DEFAULT_VOIP_SAMP_RATE 48000

#define VOIP_IO_BUF_SIZE(SR, DURATION_MS, BIT_DEPTH) (SR)/1000 * DURATION_MS * BIT_DEPTH

struct pcm_config default_pcm_config_voip_copp = {
    .channels = 1,
    .rate = DEFAULT_VOIP_SAMP_RATE, /* changed when the stream is opened */
    .period_size = VOIP_IO_BUF_SIZE(DEFAULT_VOIP_SAMP_RATE, DEFAULT_VOIP_BUF_DURATION_MS, DEFAULT_VOIP_BIT_DEPTH_BYTE)/2,
    .period_count = 2,
    .format = PCM_FORMAT_S16_LE,
    .avail_min = VOIP_IO_BUF_SIZE(DEFAULT_VOIP_SAMP_RATE, DEFAULT_VOIP_BUF_DURATION_MS, DEFAULT_VOIP_BIT_DEPTH_BYTE)/2,
    .stop_threshold = INT_MAX,
};

#define MIN_CHANNEL_COUNT                1
#define DEFAULT_CHANNEL_COUNT            2
#define MAX_HIFI_CHANNEL_COUNT           8

#ifndef MAX_TARGET_SPECIFIC_CHANNEL_CNT
#define MAX_CHANNEL_COUNT 1
#else
#define MAX_CHANNEL_COUNT atoi(XSTR(MAX_TARGET_SPECIFIC_CHANNEL_CNT))
#define XSTR(x) STR(x)
#define STR(x) #x
#endif

static unsigned int configured_low_latency_capture_period_size =
        LOW_LATENCY_CAPTURE_PERIOD_SIZE;

#define MMAP_PERIOD_SIZE (DEFAULT_OUTPUT_SAMPLING_RATE/1000)
#define MMAP_PERIOD_COUNT_MIN 32
#define MMAP_PERIOD_COUNT_MAX 512
#define MMAP_PERIOD_COUNT_DEFAULT (MMAP_PERIOD_COUNT_MAX)

/* This constant enables extended precision handling.
 * TODO The flag is off until more testing is done.
 */
static const bool k_enable_extended_precision = false;
extern int AUDIO_DEVICE_IN_ALL_CODEC_BACKEND;

struct pcm_config pcm_config_deep_buffer = {
    .channels = 2,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
    .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
    .stop_threshold = INT_MAX,
    .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
};

struct pcm_config pcm_config_low_latency = {
    .channels = 2,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
    .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
    .stop_threshold = INT_MAX,
    .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
};

struct pcm_config pcm_config_haptics_audio = {
    .channels = 1,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
    .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
    .stop_threshold = INT_MAX,
    .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
};

struct pcm_config pcm_config_haptics = {
    .channels = 1,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
    .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
    .stop_threshold = INT_MAX,
    .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
};

static int af_period_multiplier = 4;
struct pcm_config pcm_config_rt = {
    .channels = 2,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = ULL_PERIOD_SIZE, //1 ms
    .period_count = 512, //=> buffer size is 512ms
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = ULL_PERIOD_SIZE*8, //8ms
    .stop_threshold = INT_MAX,
    .silence_threshold = 0,
    .silence_size = 0,
    .avail_min = ULL_PERIOD_SIZE, //1 ms
};

struct pcm_config pcm_config_hdmi_multi = {
    .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
    .period_size = HDMI_MULTI_PERIOD_SIZE,
    .period_count = HDMI_MULTI_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = 0,
    .stop_threshold = INT_MAX,
    .avail_min = 0,
};

struct pcm_config pcm_config_mmap_playback = {
    .channels = 2,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = MMAP_PERIOD_SIZE,
    .period_count = MMAP_PERIOD_COUNT_DEFAULT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = MMAP_PERIOD_SIZE*8,
    .stop_threshold = INT32_MAX,
    .silence_threshold = 0,
    .silence_size = 0,
    .avail_min = MMAP_PERIOD_SIZE, //1 ms
};

struct pcm_config pcm_config_hifi = {
    .channels = DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
    .period_size = HIFI_BUFFER_OUTPUT_PERIOD_SIZE, /* change #define */
    .period_count = HIFI_BUFFER_OUTPUT_PERIOD_COUNT,
    .format = PCM_FORMAT_S24_3LE,
    .start_threshold = 0,
    .stop_threshold = INT_MAX,
    .avail_min = 0,
};

struct pcm_config pcm_config_audio_capture = {
    .channels = 2,
    .period_count = AUDIO_CAPTURE_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
};

struct pcm_config pcm_config_mmap_capture = {
    .channels = 2,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = MMAP_PERIOD_SIZE,
    .period_count = MMAP_PERIOD_COUNT_DEFAULT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = 0,
    .stop_threshold = INT_MAX,
    .silence_threshold = 0,
    .silence_size = 0,
    .avail_min = MMAP_PERIOD_SIZE, //1 ms
};

#define AFE_PROXY_CHANNEL_COUNT 2
#define AFE_PROXY_SAMPLING_RATE 48000

#define AFE_PROXY_PLAYBACK_PERIOD_SIZE  768
#define AFE_PROXY_PLAYBACK_PERIOD_COUNT 4

struct pcm_config pcm_config_afe_proxy_playback = {
    .channels = AFE_PROXY_CHANNEL_COUNT,
    .rate = AFE_PROXY_SAMPLING_RATE,
    .period_size = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    .period_count = AFE_PROXY_PLAYBACK_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    .stop_threshold = INT_MAX,
    .avail_min = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
};

#define AFE_PROXY_RECORD_PERIOD_SIZE  768
#define AFE_PROXY_RECORD_PERIOD_COUNT 4

struct pcm_config pcm_config_audio_capture_rt = {
    .channels = 2,
    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    .period_size = ULL_PERIOD_SIZE,
    .period_count = 512,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = 0,
    .stop_threshold = AFE_PROXY_RECORD_PERIOD_SIZE * AFE_PROXY_RECORD_PERIOD_COUNT,
    .silence_threshold = 0,
    .silence_size = 0,
    .avail_min = ULL_PERIOD_SIZE, //1 ms
};

struct pcm_config pcm_config_afe_proxy_record = {
    .channels = AFE_PROXY_CHANNEL_COUNT,
    .rate = AFE_PROXY_SAMPLING_RATE,
    .period_size = AFE_PROXY_RECORD_PERIOD_SIZE,
    .period_count = AFE_PROXY_RECORD_PERIOD_COUNT,
    .format = PCM_FORMAT_S16_LE,
    .start_threshold = AFE_PROXY_RECORD_PERIOD_SIZE,
    .stop_threshold = INT_MAX,
    .avail_min = AFE_PROXY_RECORD_PERIOD_SIZE,
};

#define AUDIO_MAX_PCM_FORMATS 7

const uint32_t format_to_bitwidth_table[AUDIO_MAX_PCM_FORMATS] = {
    [AUDIO_FORMAT_DEFAULT] = 0,
    [AUDIO_FORMAT_PCM_16_BIT] = sizeof(uint16_t),
    [AUDIO_FORMAT_PCM_8_BIT] = sizeof(uint8_t),
    [AUDIO_FORMAT_PCM_32_BIT] = sizeof(uint32_t),
    [AUDIO_FORMAT_PCM_8_24_BIT] = sizeof(uint32_t),
    [AUDIO_FORMAT_PCM_FLOAT] = sizeof(float),
    [AUDIO_FORMAT_PCM_24_BIT_PACKED] = sizeof(uint8_t) * 3,
};

const char * const use_case_table[AUDIO_USECASE_MAX] = {
    [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = "deep-buffer-playback",
    [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = "low-latency-playback",
    [USECASE_AUDIO_PLAYBACK_WITH_HAPTICS] = "audio-with-haptics-playback",
    [USECASE_AUDIO_PLAYBACK_ULL]         = "audio-ull-playback",
    [USECASE_AUDIO_PLAYBACK_MULTI_CH]    = "multi-channel-playback",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
    //Enabled for Direct_PCM
    [USECASE_AUDIO_PLAYBACK_OFFLOAD2] = "compress-offload-playback2",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD3] = "compress-offload-playback3",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD4] = "compress-offload-playback4",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD5] = "compress-offload-playback5",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD6] = "compress-offload-playback6",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD7] = "compress-offload-playback7",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD8] = "compress-offload-playback8",
    [USECASE_AUDIO_PLAYBACK_OFFLOAD9] = "compress-offload-playback9",
    [USECASE_AUDIO_PLAYBACK_FM] = "play-fm",
    [USECASE_AUDIO_PLAYBACK_MMAP] = "mmap-playback",
    [USECASE_AUDIO_PLAYBACK_HIFI] = "hifi-playback",
    [USECASE_AUDIO_PLAYBACK_TTS] = "audio-tts-playback",

    [USECASE_AUDIO_RECORD] = "audio-record",
    [USECASE_AUDIO_RECORD_COMPRESS] = "audio-record-compress",
    [USECASE_AUDIO_RECORD_COMPRESS2] = "audio-record-compress2",
    [USECASE_AUDIO_RECORD_COMPRESS3] = "audio-record-compress3",
    [USECASE_AUDIO_RECORD_COMPRESS4] = "audio-record-compress4",
    [USECASE_AUDIO_RECORD_COMPRESS5] = "audio-record-compress5",
    [USECASE_AUDIO_RECORD_COMPRESS6] = "audio-record-compress6",
    [USECASE_AUDIO_RECORD_LOW_LATENCY] = "low-latency-record",
    [USECASE_AUDIO_RECORD_FM_VIRTUAL] = "fm-virtual-record",
    [USECASE_AUDIO_RECORD_MMAP] = "mmap-record",
    [USECASE_AUDIO_RECORD_HIFI] = "hifi-record",

    [USECASE_AUDIO_HFP_SCO] = "hfp-sco",
    [USECASE_AUDIO_HFP_SCO_WB] = "hfp-sco-wb",
    [USECASE_VOICE_CALL] = "voice-call",

    [USECASE_VOICE2_CALL] = "voice2-call",
    [USECASE_VOLTE_CALL] = "volte-call",
    [USECASE_QCHAT_CALL] = "qchat-call",
    [USECASE_VOWLAN_CALL] = "vowlan-call",
    [USECASE_VOICEMMODE1_CALL] = "voicemmode1-call",
    [USECASE_VOICEMMODE2_CALL] = "voicemmode2-call",
    [USECASE_COMPRESS_VOIP_CALL] = "compress-voip-call",
    [USECASE_INCALL_REC_UPLINK] = "incall-rec-uplink",
    [USECASE_INCALL_REC_DOWNLINK] = "incall-rec-downlink",
    [USECASE_INCALL_REC_UPLINK_AND_DOWNLINK] = "incall-rec-uplink-and-downlink",
    [USECASE_INCALL_REC_UPLINK_COMPRESS] = "incall-rec-uplink-compress",
    [USECASE_INCALL_REC_DOWNLINK_COMPRESS] = "incall-rec-downlink-compress",
    [USECASE_INCALL_REC_UPLINK_AND_DOWNLINK_COMPRESS] = "incall-rec-uplink-and-downlink-compress",

    [USECASE_INCALL_MUSIC_UPLINK] = "incall_music_uplink",
    [USECASE_INCALL_MUSIC_UPLINK2] = "incall_music_uplink2",
    [USECASE_AUDIO_SPKR_CALIB_RX] = "spkr-rx-calib",
    [USECASE_AUDIO_SPKR_CALIB_TX] = "spkr-vi-record",

    [USECASE_AUDIO_PLAYBACK_AFE_PROXY] = "afe-proxy-playback",
    [USECASE_AUDIO_RECORD_AFE_PROXY] = "afe-proxy-record",
    [USECASE_AUDIO_PLAYBACK_SILENCE] = "silence-playback",

    /* Transcode loopback cases */
    [USECASE_AUDIO_TRANSCODE_LOOPBACK_RX] = "audio-transcode-loopback-rx",
    [USECASE_AUDIO_TRANSCODE_LOOPBACK_TX] = "audio-transcode-loopback-tx",

    [USECASE_AUDIO_PLAYBACK_VOIP] = "audio-playback-voip",
    [USECASE_AUDIO_RECORD_VOIP] = "audio-record-voip",
    /* For Interactive Audio Streams */
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM1] = "audio-interactive-stream1",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM2] = "audio-interactive-stream2",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM3] = "audio-interactive-stream3",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM4] = "audio-interactive-stream4",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM5] = "audio-interactive-stream5",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM6] = "audio-interactive-stream6",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM7] = "audio-interactive-stream7",
    [USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM8] = "audio-interactive-stream8",

    [USECASE_AUDIO_EC_REF_LOOPBACK] = "ec-ref-audio-capture",

    [USECASE_AUDIO_A2DP_ABR_FEEDBACK] = "a2dp-abr-feedback",

    [USECASE_AUDIO_PLAYBACK_MEDIA] = "media-playback",
    [USECASE_AUDIO_PLAYBACK_SYS_NOTIFICATION] = "sys-notification-playback",
    [USECASE_AUDIO_PLAYBACK_NAV_GUIDANCE] = "nav-guidance-playback",
    [USECASE_AUDIO_PLAYBACK_PHONE] = "phone-playback",
    [USECASE_AUDIO_FM_TUNER_EXT] = "fm-tuner-ext",
};

static const audio_usecase_t offload_usecases[] = {
    USECASE_AUDIO_PLAYBACK_OFFLOAD,
    USECASE_AUDIO_PLAYBACK_OFFLOAD2,
    USECASE_AUDIO_PLAYBACK_OFFLOAD3,
    USECASE_AUDIO_PLAYBACK_OFFLOAD4,
    USECASE_AUDIO_PLAYBACK_OFFLOAD5,
    USECASE_AUDIO_PLAYBACK_OFFLOAD6,
    USECASE_AUDIO_PLAYBACK_OFFLOAD7,
    USECASE_AUDIO_PLAYBACK_OFFLOAD8,
    USECASE_AUDIO_PLAYBACK_OFFLOAD9,
};

static const audio_usecase_t interactive_usecases[] = {
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM1,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM2,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM3,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM4,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM5,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM6,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM7,
    USECASE_AUDIO_PLAYBACK_INTERACTIVE_STREAM8,
};

#define STRING_TO_ENUM(string) { #string, string }

struct string_to_enum {
    const char *name;
    uint32_t value;
};

static const struct string_to_enum channels_name_to_enum_table[] = {
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_2POINT1),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_SURROUND),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_PENTA),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_6POINT1),
    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
    STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
    STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
    STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_1),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_2),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_3),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_4),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_5),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_6),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_7),
    STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_8),
};

static const struct string_to_enum formats_name_to_enum_table[] = {
    STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
    STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
    STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
    STRING_TO_ENUM(AUDIO_FORMAT_AC3),
    STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
    STRING_TO_ENUM(AUDIO_FORMAT_E_AC3_JOC),
    STRING_TO_ENUM(AUDIO_FORMAT_DOLBY_TRUEHD),
    STRING_TO_ENUM(AUDIO_FORMAT_DTS),
    STRING_TO_ENUM(AUDIO_FORMAT_DTS_HD),
    STRING_TO_ENUM(AUDIO_FORMAT_IEC61937)
};

//list of all supported sample rates by HDMI specification.
static const int out_hdmi_sample_rates[] = {
    32000, 44100, 48000, 88200, 96000, 176400, 192000,
};

static const struct string_to_enum out_sample_rates_name_to_enum_table[] = {
    STRING_TO_ENUM(32000),
    STRING_TO_ENUM(44100),
    STRING_TO_ENUM(48000),
    STRING_TO_ENUM(88200),
    STRING_TO_ENUM(96000),
    STRING_TO_ENUM(176400),
    STRING_TO_ENUM(192000),
};

struct in_effect_list {
    struct listnode list;
    effect_handle_t handle;
};

static struct audio_device *adev = NULL;
static pthread_mutex_t adev_init_lock = PTHREAD_MUTEX_INITIALIZER;
static unsigned int audio_device_ref_count;
//cache last MBDRC cal step level
static int last_known_cal_step = -1 ;

static int check_a2dp_restore_l(struct audio_device *adev, struct stream_out *out, bool restore);
static int out_set_compr_volume(struct audio_stream_out *stream, float left, float right);
static int out_set_mmap_volume(struct audio_stream_out *stream, float left, float right);
static int out_set_voip_volume(struct audio_stream_out *stream, float left, float right);
static int out_set_pcm_volume(struct audio_stream_out *stream, float left, float right);

static void adev_snd_mon_cb(void *cookie, struct str_parms *parms);
static void in_snd_mon_cb(void * stream, struct str_parms * parms);
static void out_snd_mon_cb(void * stream, struct str_parms * parms);

static int configure_btsco_sample_rate(snd_device_t snd_device);

#ifdef AUDIO_FEATURE_ENABLED_GCOV
extern void  __gcov_flush();
static void enable_gcov()
{
    __gcov_flush();
}
#else
static void enable_gcov()
{
}
#endif

static int in_set_microphone_direction(const struct audio_stream_in *stream,
                                           audio_microphone_direction_t dir);
static int in_set_microphone_field_dimension(const struct audio_stream_in *stream, float zoom);

static bool may_use_noirq_mode(struct audio_device *adev, audio_usecase_t uc_id,
                               int flags __unused)
{
    int dir = 0;
    switch (uc_id) {
        case USECASE_AUDIO_RECORD_LOW_LATENCY:
            dir = 1;
        case USECASE_AUDIO_PLAYBACK_ULL:
            break;
        default:
            return false;
    }

    int dev_id = platform_get_pcm_device_id(uc_id, dir == 0 ?
                                            PCM_PLAYBACK : PCM_CAPTURE);
    if (adev->adm_is_noirq_avail)
        return adev->adm_is_noirq_avail(adev->adm_data,
                                        adev->snd_card, dev_id, dir);
    return false;
}

static void register_out_stream(struct stream_out *out)
{
    struct audio_device *adev = out->dev;
    if (is_offload_usecase(out->usecase) ||
        !adev->adm_register_output_stream)
        return;

    // register stream first for backward compatibility
    adev->adm_register_output_stream(adev->adm_data,
                                     out->handle,
                                     out->flags);

    if (!adev->adm_set_config)
        return;

    if (out->realtime)
        adev->adm_set_config(adev->adm_data,
                             out->handle,
                             out->pcm, &out->config);
}

static void register_in_stream(struct stream_in *in)
{
    struct audio_device *adev = in->dev;
    if (!adev->adm_register_input_stream)
        return;

    adev->adm_register_input_stream(adev->adm_data,
                                    in->capture_handle,
                                    in->flags);

    if (!adev->adm_set_config)
        return;

    if (in->realtime)
        adev->adm_set_config(adev->adm_data,
                             in->capture_handle,
                             in->pcm,
                             &in->config);
}

static void request_out_focus(struct stream_out *out, long ns)
{
    struct audio_device *adev = out->dev;

    if (adev->adm_request_focus_v2)
        adev->adm_request_focus_v2(adev->adm_data, out->handle, ns);
    else if (adev->adm_request_focus)
        adev->adm_request_focus(adev->adm_data, out->handle);
}

static int request_in_focus(struct stream_in *in, long ns)
{
    struct audio_device *adev = in->dev;
    int ret = 0;

    if (adev->adm_request_focus_v2_1)
        ret = adev->adm_request_focus_v2_1(adev->adm_data, in->capture_handle, ns);
    else if (adev->adm_request_focus_v2)
        adev->adm_request_focus_v2(adev->adm_data, in->capture_handle, ns);
    else if (adev->adm_request_focus)
        adev->adm_request_focus(adev->adm_data, in->capture_handle);

    return ret;
}

static void release_out_focus(struct stream_out *out)
{
    struct audio_device *adev = out->dev;

    if (adev->adm_abandon_focus)
        adev->adm_abandon_focus(adev->adm_data, out->handle);
}

static void release_in_focus(struct stream_in *in)
{
    struct audio_device *adev = in->dev;
    if (adev->adm_abandon_focus)
        adev->adm_abandon_focus(adev->adm_data, in->capture_handle);
}

static int parse_snd_card_status(struct str_parms *parms, int *card,
                                 card_status_t *status)
{
    char value[32]={0};
    char state[32]={0};

    int  ret = str_parms_get_str(parms, "SND_CARD_STATUS", value, sizeof(value));
    if (ret < 0)
        return -1;

    // sscanf should be okay as value is of max length 32.
    // same as sizeof state.
    if (sscanf(value, "%d,%s", card, state) < 2)
        return -1;

    *status = !strcmp(state, "ONLINE") ? CARD_STATUS_ONLINE :
                                         CARD_STATUS_OFFLINE;
    return 0;
}

static inline void adjust_frames_for_device_delay(struct stream_out *out,
                                                  uint32_t *dsp_frames) {
    // Adjustment accounts for A2dp encoder latency with offload usecases
    // Note: Encoder latency is returned in ms.
    if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices) {
        unsigned long offset =
                (audio_extn_a2dp_get_encoder_latency() * out->sample_rate / 1000);
        *dsp_frames = (*dsp_frames > offset) ? (*dsp_frames - offset) : 0;
    }
}

__attribute__ ((visibility ("default")))
bool audio_hw_send_gain_dep_calibration(int level) {
    bool ret_val = false;
    ALOGV("%s: called ...", __func__);

    pthread_mutex_lock(&adev_init_lock);

    if (adev != NULL && adev->platform != NULL) {
        pthread_mutex_lock(&adev->lock);
        ret_val = platform_send_gain_dep_cal(adev->platform, level);

        // cache level info for any of the use case which
        // was not started.
        last_known_cal_step = level;;

        pthread_mutex_unlock(&adev->lock);
    } else {
        ALOGE("%s: %s is NULL", __func__, adev == NULL ? "adev" : "adev->platform");
    }

    pthread_mutex_unlock(&adev_init_lock);

    return ret_val;
}

static int check_and_set_gapless_mode(struct audio_device *adev, bool enable_gapless)
{
    bool gapless_enabled = false;
    const char *mixer_ctl_name = "Compress Gapless Playback";
    struct mixer_ctl *ctl;

    ALOGV("%s:", __func__);
    gapless_enabled = property_get_bool("vendor.audio.offload.gapless.enabled", false);

    /*Disable gapless if its AV playback*/
    gapless_enabled = gapless_enabled && enable_gapless;

    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: Could not get ctl for mixer cmd - %s",
                               __func__, mixer_ctl_name);
        return -EINVAL;
    }

    if (mixer_ctl_set_value(ctl, 0, gapless_enabled) < 0) {
        ALOGE("%s: Could not set gapless mode %d",
                       __func__, gapless_enabled);
         return -EINVAL;
    }
    return 0;
}

__attribute__ ((visibility ("default")))
int audio_hw_get_gain_level_mapping(struct amp_db_and_gain_table *mapping_tbl,
                                    int table_size) {
     int ret_val = 0;
     ALOGV("%s: enter ... ", __func__);

     pthread_mutex_lock(&adev_init_lock);
     if (adev == NULL) {
         ALOGW("%s: adev is NULL .... ", __func__);
         goto done;
     }

     pthread_mutex_lock(&adev->lock);
     ret_val = platform_get_gain_level_mapping(mapping_tbl, table_size);
     pthread_mutex_unlock(&adev->lock);
done:
     pthread_mutex_unlock(&adev_init_lock);
     ALOGV("%s: exit ... ", __func__);
     return ret_val;
}

bool audio_hw_send_qdsp_parameter(int stream_type, float vol, bool active)
{
    bool ret = false;
    ALOGV("%s: enter ...", __func__);

    pthread_mutex_lock(&adev_init_lock);

    if (adev != NULL && adev->platform != NULL) {
        pthread_mutex_lock(&adev->lock);
        ret = audio_extn_qdsp_set_state(adev, stream_type, vol, active);
        pthread_mutex_unlock(&adev->lock);
    }

    pthread_mutex_unlock(&adev_init_lock);

    ALOGV("%s: exit with ret %d", __func__, ret);
    return ret;
}

static bool is_supported_format(audio_format_t format)
{
    if (format == AUDIO_FORMAT_MP3 ||
        format == AUDIO_FORMAT_MP2 ||
        format == AUDIO_FORMAT_AAC_LC ||
        format == AUDIO_FORMAT_AAC_HE_V1 ||
        format == AUDIO_FORMAT_AAC_HE_V2 ||
        format == AUDIO_FORMAT_AAC_ADTS_LC ||
        format == AUDIO_FORMAT_AAC_ADTS_HE_V1 ||
        format == AUDIO_FORMAT_AAC_ADTS_HE_V2 ||
        format == AUDIO_FORMAT_AAC_LATM_LC ||
        format == AUDIO_FORMAT_AAC_LATM_HE_V1 ||
        format == AUDIO_FORMAT_AAC_LATM_HE_V2 ||
        format == AUDIO_FORMAT_PCM_24_BIT_PACKED ||
        format == AUDIO_FORMAT_PCM_8_24_BIT ||
        format == AUDIO_FORMAT_PCM_FLOAT ||
        format == AUDIO_FORMAT_PCM_32_BIT ||
        format == AUDIO_FORMAT_PCM_16_BIT ||
        format == AUDIO_FORMAT_AC3 ||
        format == AUDIO_FORMAT_E_AC3 ||
        format == AUDIO_FORMAT_DOLBY_TRUEHD ||
        format == AUDIO_FORMAT_DTS ||
        format == AUDIO_FORMAT_DTS_HD ||
        format == AUDIO_FORMAT_FLAC ||
        format == AUDIO_FORMAT_ALAC ||
        format == AUDIO_FORMAT_APE ||
        format == AUDIO_FORMAT_DSD ||
        format == AUDIO_FORMAT_VORBIS ||
        format == AUDIO_FORMAT_WMA ||
        format == AUDIO_FORMAT_WMA_PRO ||
        format == AUDIO_FORMAT_APTX ||
        format == AUDIO_FORMAT_IEC61937)
           return true;

    return false;
}

static inline bool is_mmap_usecase(audio_usecase_t uc_id)
{
    return (uc_id == USECASE_AUDIO_RECORD_AFE_PROXY) ||
           (uc_id == USECASE_AUDIO_PLAYBACK_AFE_PROXY);
}

static inline bool is_valid_volume(float left, float right)
{
    return ((left >= 0.0f && right >= 0.0f) ? true : false);
}

static int enable_audio_route_for_voice_usecases(struct audio_device *adev,
                                                 struct audio_usecase *uc_info)
{
    struct listnode *node;
    struct audio_usecase *usecase;

    if (uc_info == NULL)
        return -EINVAL;

    /* Re-route all voice usecases on the shared backend other than the
       specified usecase to new snd devices */
    list_for_each(node, &adev->usecase_list) {
        usecase = node_to_item(node, struct audio_usecase, list);
        if ((usecase->type == VOICE_CALL) && (usecase != uc_info))
            enable_audio_route(adev, usecase);
    }
    return 0;
}

static void enable_asrc_mode(struct audio_device *adev)
{
    ALOGV("%s", __func__);
    audio_route_apply_and_update_path(adev->audio_route,
                                  "asrc-mode");
    adev->asrc_mode_enabled = true;
}

static void disable_asrc_mode(struct audio_device *adev)
{
    ALOGV("%s", __func__);
    audio_route_reset_and_update_path(adev->audio_route,
                                  "asrc-mode");
    adev->asrc_mode_enabled = false;
}

/*
 * - Enable ASRC mode for incoming mix path use case(Headphone backend)if Headphone
 *   44.1 or Native DSD backends are enabled for any of current use case.
 *   e.g. 48-> + (Naitve DSD or Headphone 44.1)
 * - Disable current mix path use case(Headphone backend) and re-enable it with
 *   ASRC mode for incoming Headphone 44.1 or Native DSD use case.
 *   e.g. Naitve DSD or Headphone 44.1 -> + 48
 */
static void check_and_set_asrc_mode(struct audio_device *adev,
                                          struct audio_usecase *uc_info,
                                          snd_device_t snd_device)
{
    ALOGV("%s snd device %d", __func__, snd_device);
    int i, num_new_devices = 0;
    snd_device_t split_new_snd_devices[SND_DEVICE_OUT_END];
    /*
    *Split snd device for new combo use case
    *e.g. Headphopne 44.1-> + Ringtone (Headphone + Speaker)
    */
    if (platform_split_snd_device(adev->platform,
                                 snd_device,
                                 &num_new_devices,
                                 split_new_snd_devices) == 0) {
        for (i = 0; i < num_new_devices; i++)
            check_and_set_asrc_mode(adev, uc_info, split_new_snd_devices[i]);
    } else {
        int new_backend_idx = platform_get_backend_index(snd_device);
        if (((new_backend_idx == HEADPHONE_BACKEND) ||
                (new_backend_idx == HEADPHONE_44_1_BACKEND) ||
                (new_backend_idx == DSD_NATIVE_BACKEND)) &&
                !adev->asrc_mode_enabled) {
            struct listnode *node = NULL;
            struct audio_usecase *uc = NULL;
            struct stream_out *curr_out = NULL;
            int usecase_backend_idx = DEFAULT_CODEC_BACKEND;
            int i, num_devices, ret = 0;
            snd_device_t split_snd_devices[SND_DEVICE_OUT_END];

            list_for_each(node, &adev->usecase_list) {
                uc = node_to_item(node, struct audio_usecase, list);
                curr_out = (struct stream_out*) uc->stream.out;
                if (curr_out && PCM_PLAYBACK == uc->type && uc != uc_info) {
                    /*
                    *Split snd device for existing combo use case
                    *e.g. Ringtone (Headphone + Speaker) + Headphopne 44.1
                    */
                    ret = platform_split_snd_device(adev->platform,
                                             uc->out_snd_device,
                                             &num_devices,
                                             split_snd_devices);
                    if (ret < 0 || num_devices == 0) {
                        ALOGV("%s: Unable to split uc->out_snd_device: %d",__func__, uc->out_snd_device);
                        split_snd_devices[0] = uc->out_snd_device;
                        num_devices = 1;
                    }
                    for (i = 0; i < num_devices; i++) {
                        usecase_backend_idx = platform_get_backend_index(split_snd_devices[i]);
                        ALOGD("%s:snd_dev %d usecase_backend_idx %d",__func__, split_snd_devices[i],usecase_backend_idx);
                        if((new_backend_idx == HEADPHONE_BACKEND) &&
                               ((usecase_backend_idx == HEADPHONE_44_1_BACKEND) ||
                               (usecase_backend_idx == DSD_NATIVE_BACKEND))) {
                            ALOGD("%s:DSD or native stream detected enabling asrcmode in hardware",
                                  __func__);
                            enable_asrc_mode(adev);
                            break;
                        } else if(((new_backend_idx == HEADPHONE_44_1_BACKEND) ||
                                  (new_backend_idx == DSD_NATIVE_BACKEND)) &&
                                  (usecase_backend_idx == HEADPHONE_BACKEND)) {
                            ALOGD("%s:48K stream detected, disabling and enabling it with asrcmode in hardware",
                                  __func__);
                            disable_audio_route(adev, uc);
                            disable_snd_device(adev, uc->out_snd_device);
                            // Apply true-high-quality-mode if DSD or > 44.1KHz or >=24-bit
                            if (new_backend_idx == DSD_NATIVE_BACKEND)
                                audio_route_apply_and_update_path(adev->audio_route,
                                                        "hph-true-highquality-mode");
                            else if ((new_backend_idx == HEADPHONE_44_1_BACKEND) &&
                                     (curr_out->bit_width >= 24))
                                audio_route_apply_and_update_path(adev->audio_route,
                                                             "hph-highquality-mode");
                            enable_asrc_mode(adev);
                            enable_snd_device(adev, uc->out_snd_device);
                            enable_audio_route(adev, uc);
                            break;
                        }
                    }
                    // reset split devices count
                    num_devices = 0;
                }
                if (adev->asrc_mode_enabled)
                    break;
            }
        }
    }
}

static int send_effect_enable_disable_mixer_ctl(struct audio_device *adev,
                          struct audio_effect_config effect_config,
                          unsigned int param_value)
{
    char mixer_ctl_name[] = "Audio Effect";
    struct mixer_ctl *ctl;
    long set_values[6];
    struct stream_in *in = adev_get_active_input(adev);

    if (in == NULL) {
        ALOGE("%s: active input stream is NULL", __func__);
        return -EINVAL;
    }

    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: Could not get mixer ctl - %s",
               __func__, mixer_ctl_name);
        return -EINVAL;
    }

    set_values[0] = 1; //0:Rx 1:Tx
    set_values[1] = in->app_type_cfg.app_type;
    set_values[2] = (long)effect_config.module_id;
    set_values[3] = (long)effect_config.instance_id;
    set_values[4] = (long)effect_config.param_id;
    set_values[5] = param_value;

    mixer_ctl_set_array(ctl, set_values, ARRAY_SIZE(set_values));

    return 0;

}

static int update_effect_param_ecns(struct audio_device *adev, unsigned int module_id,
                               int effect_type, unsigned int *param_value)
{
    int ret = 0;
    struct audio_effect_config other_effect_config;
    struct audio_usecase *usecase = NULL;
    struct stream_in *in = adev_get_active_input(adev);

    if (in == NULL) {
        ALOGE("%s: active input stream is NULL", __func__);
        return -EINVAL;
    }

    usecase = get_usecase_from_list(adev, in->usecase);
    if (!usecase)
        return -EINVAL;

    ret = platform_get_effect_config_data(usecase->in_snd_device, &other_effect_config,
                                            effect_type == EFFECT_AEC ? EFFECT_NS : EFFECT_AEC);
    if (ret < 0) {
        ALOGE("%s Failed to get effect params %d", __func__, ret);
        return ret;
    }

    if (module_id == other_effect_config.module_id) {
            //Same module id for AEC/NS. Values need to be combined
            if (((effect_type == EFFECT_AEC) && (in->enable_ns)) ||
                ((effect_type == EFFECT_NS) && (in->enable_aec))) {
                *param_value |= other_effect_config.param_value;
            }
    }

    return ret;
}

static int enable_disable_effect(struct audio_device *adev, int effect_type, bool enable)
{
    struct audio_effect_config effect_config;
    struct audio_usecase *usecase = NULL;
    int ret = 0;
    unsigned int param_value = 0;
    struct stream_in *in = adev_get_active_input(adev);

    if(!voice_extn_is_dynamic_ecns_enabled())
        return ENOSYS;

    if (!in) {
        ALOGE("%s: Invalid input stream", __func__);
        return -EINVAL;
    }

    ALOGD("%s: effect_type:%d enable:%d", __func__, effect_type, enable);

    usecase = get_usecase_from_list(adev, in->usecase);
    if (usecase == NULL) {
        ALOGE("%s: Could not find the usecase (%d) in the list",
              __func__, in->usecase);
        return -EINVAL;
    }

    ret = platform_get_effect_config_data(usecase->in_snd_device, &effect_config, effect_type);
    if (ret < 0) {
        ALOGE("%s Failed to get module id %d", __func__, ret);
        return ret;
    }
    ALOGV("%s: %d %d usecase->id:%d usecase->in_snd_device:%d", __func__, effect_config.module_id,
           in->app_type_cfg.app_type, usecase->id, usecase->in_snd_device);

    if(enable)
        param_value = effect_config.param_value;

    /*Special handling for AEC & NS effects Param values need to be
      updated if module ids are same*/

    if ((effect_type == EFFECT_AEC) || (effect_type == EFFECT_NS)) {
        ret = update_effect_param_ecns(adev, effect_config.module_id, effect_type, &param_value);
        if (ret < 0)
            return ret;
    }

    ret = send_effect_enable_disable_mixer_ctl(adev, effect_config, param_value);

    return ret;
}

static void check_and_enable_effect(struct audio_device *adev)
{
    if(!voice_extn_is_dynamic_ecns_enabled())
        return;

    struct stream_in *in = adev_get_active_input(adev);

    if (in != NULL && !in->standby) {
        if (in->enable_aec)
            enable_disable_effect(adev, EFFECT_AEC, true);

        if (in->enable_ns &&
            in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
            enable_disable_effect(adev, EFFECT_NS, true);
        }
    }
}

int pcm_ioctl(struct pcm *pcm, int request, ...)
{
    va_list ap;
    void * arg;
    int pcm_fd = *(int*)pcm;

    va_start(ap, request);
    arg = va_arg(ap, void *);
    va_end(ap);

    return ioctl(pcm_fd, request, arg);
}

int enable_audio_route(struct audio_device *adev,
                       struct audio_usecase *usecase)
{
    snd_device_t snd_device;
    char mixer_path[MIXER_PATH_MAX_LENGTH];
    struct stream_out *out = NULL;
    struct stream_in *in = NULL;
    int ret = 0;

    if (usecase == NULL)
        return -EINVAL;

    ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);

    if (usecase->type == PCM_CAPTURE) {
        struct stream_in *in = usecase->stream.in;
        struct audio_usecase *uinfo;
        snd_device = usecase->in_snd_device;

        if (in) {
            if (in->enable_aec || in->enable_ec_port) {
                audio_devices_t out_device = AUDIO_DEVICE_OUT_SPEAKER;
                struct listnode *node;
                struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
                                                           USECASE_AUDIO_PLAYBACK_VOIP);
                if (voip_usecase) {
                    out_device = voip_usecase->stream.out->devices;
                } else if (adev->primary_output &&
                              !adev->primary_output->standby) {
                    out_device = adev->primary_output->devices;
                } else {
                    list_for_each(node, &adev->usecase_list) {
                        uinfo = node_to_item(node, struct audio_usecase, list);
                        if (uinfo->type != PCM_CAPTURE) {
                            out_device = uinfo->stream.out->devices;
                            break;
                        }
                    }
                }
                platform_set_echo_reference(adev, true, out_device);
                in->ec_opened = true;
            }
        }
    } else if (usecase->type == TRANSCODE_LOOPBACK_TX) {
        snd_device = usecase->in_snd_device;
    } else {
        snd_device = usecase->out_snd_device;
    }

#ifdef DS1_DOLBY_DAP_ENABLED
    audio_extn_dolby_set_dmid(adev);
    audio_extn_dolby_set_endpoint(adev);
#endif
    audio_extn_dolby_ds2_set_endpoint(adev);
    audio_extn_sound_trigger_update_stream_status(usecase, ST_EVENT_STREAM_BUSY);
    audio_extn_listen_update_stream_status(usecase, LISTEN_EVENT_STREAM_BUSY);
    audio_extn_utils_send_app_type_cfg(adev, usecase);
    if (audio_extn_is_maxx_audio_enabled())
        audio_extn_ma_set_device(usecase);
    audio_extn_utils_send_audio_calibration(adev, usecase);
    if ((usecase->type == PCM_PLAYBACK) && is_offload_usecase(usecase->id)) {
        out = usecase->stream.out;
        if (out && out->compr)
            audio_extn_utils_compress_set_clk_rec_mode(usecase);
    }

    if (usecase->type == PCM_CAPTURE) {
        in = usecase->stream.in;
        if (in && is_loopback_input_device(in->device)) {
            ALOGD("%s: set custom mtmx params v1", __func__);
            audio_extn_set_custom_mtmx_params_v1(adev, usecase, true);
        }
    } else {
        audio_extn_set_custom_mtmx_params_v2(adev, usecase, true);
    }

    // we shouldn't truncate mixer_path
    ALOGW_IF(strlcpy(mixer_path, use_case_table[usecase->id], sizeof(mixer_path))
            >= sizeof(mixer_path), "%s: truncation on mixer path", __func__);
    // this also appends to mixer_path
    platform_add_backend_name(mixer_path, snd_device, usecase);
    ALOGD("%s: apply mixer and update path: %s", __func__, mixer_path);
    ret = audio_route_apply_and_update_path(adev->audio_route, mixer_path);
    if (!ret && usecase->id == USECASE_AUDIO_PLAYBACK_FM) {
        struct str_parms *parms = str_parms_create_str("fm_restore_volume=1");
        if (parms) {
            audio_extn_fm_set_parameters(adev, parms);
            str_parms_destroy(parms);
        }
    }
    ALOGV("%s: exit", __func__);
    return 0;
}

int disable_audio_route(struct audio_device *adev,
                        struct audio_usecase *usecase)
{
    snd_device_t snd_device;
    char mixer_path[MIXER_PATH_MAX_LENGTH];
    struct stream_in *in = NULL;

    if (usecase == NULL || usecase->id == USECASE_INVALID)
        return -EINVAL;

    ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
    if (usecase->type == PCM_CAPTURE || usecase->type == TRANSCODE_LOOPBACK_TX)
        snd_device = usecase->in_snd_device;
    else
        snd_device = usecase->out_snd_device;
    // we shouldn't truncate mixer_path
    ALOGW_IF(strlcpy(mixer_path, use_case_table[usecase->id], sizeof(mixer_path))
            >= sizeof(mixer_path), "%s: truncation on mixer path", __func__);
    // this also appends to mixer_path
    platform_add_backend_name(mixer_path, snd_device, usecase);
    ALOGD("%s: reset and update mixer path: %s", __func__, mixer_path);
    audio_route_reset_and_update_path(adev->audio_route, mixer_path);
    if (usecase->type == PCM_CAPTURE) {
        struct stream_in *in = usecase->stream.in;
        if (in && in->ec_opened) {
            platform_set_echo_reference(in->dev, false, AUDIO_DEVICE_NONE);
            in->ec_opened = false;
        }
    }
    audio_extn_sound_trigger_update_stream_status(usecase, ST_EVENT_STREAM_FREE);
    audio_extn_listen_update_stream_status(usecase, LISTEN_EVENT_STREAM_FREE);

    if (usecase->type == PCM_CAPTURE) {
        in = usecase->stream.in;
        if (in && is_loopback_input_device(in->device)) {
            ALOGD("%s: reset custom mtmx params v1", __func__);
            audio_extn_set_custom_mtmx_params_v1(adev, usecase, false);
        }
    } else {
        audio_extn_set_custom_mtmx_params_v2(adev, usecase, false);
    }

    if ((usecase->type == PCM_PLAYBACK) &&
            (usecase->stream.out != NULL))
        usecase->stream.out->pspd_coeff_sent = false;

    ALOGV("%s: exit", __func__);
    return 0;
}

int enable_snd_device(struct audio_device *adev,
                      snd_device_t snd_device)
{
    int i, num_devices = 0;
    snd_device_t new_snd_devices[SND_DEVICE_OUT_END];
    char device_name[DEVICE_NAME_MAX_SIZE] = {0};

    if (snd_device < SND_DEVICE_MIN ||
        snd_device >= SND_DEVICE_MAX) {
        ALOGE("%s: Invalid sound device %d", __func__, snd_device);
        return -EINVAL;
    }

    if (platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0) {
        ALOGE("%s: Invalid sound device returned", __func__);
        return -EINVAL;
    }

    adev->snd_dev_ref_cnt[snd_device]++;

    if ((adev->snd_dev_ref_cnt[snd_device] > 1) &&
            (platform_split_snd_device(adev->platform,
                                       snd_device,
                                       &num_devices,
                                       new_snd_devices) != 0)) {
        ALOGV("%s: snd_device(%d: %s) is already active",
              __func__, snd_device, device_name);
        return 0;
    }

    if (audio_extn_spkr_prot_is_enabled())
         audio_extn_spkr_prot_calib_cancel(adev);

    audio_extn_dsm_feedback_enable(adev, snd_device, true);

    if (platform_can_enable_spkr_prot_on_device(snd_device) &&
         audio_extn_spkr_prot_is_enabled()) {
        if (platform_get_spkr_prot_acdb_id(snd_device) < 0) {
            goto err;
        }
        audio_extn_dev_arbi_acquire(snd_device);
        if (audio_extn_spkr_prot_start_processing(snd_device)) {
            ALOGE("%s: spkr_start_processing failed", __func__);
            audio_extn_dev_arbi_release(snd_device);
            goto err;
        }
    } else if (platform_split_snd_device(adev->platform,
                                         snd_device,
                                         &num_devices,
                                         new_snd_devices) == 0) {
        for (i = 0; i < num_devices; i++) {
            enable_snd_device(adev, new_snd_devices[i]);
        }
        platform_set_speaker_gain_in_combo(adev, snd_device, true);
    } else {
        ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);


        if ((SND_DEVICE_OUT_BT_A2DP == snd_device) &&
            (audio_extn_a2dp_start_playback() < 0)) {
            ALOGE(" fail to configure A2dp Source control path ");
            goto err;
        }

        if ((SND_DEVICE_IN_BT_A2DP == snd_device) &&
            (audio_extn_a2dp_start_capture() < 0)) {
            ALOGE(" fail to configure A2dp Sink control path ");
            goto err;
        }

        if (((SND_DEVICE_OUT_BT_SCO_SWB == snd_device) ||
             (SND_DEVICE_IN_BT_SCO_MIC_SWB_NREC == snd_device) ||
             (SND_DEVICE_IN_BT_SCO_MIC_SWB == snd_device)) &&
            (audio_extn_sco_start_configuration() < 0)) {
            ALOGE(" fail to configure sco control path ");
            goto err;
        }

        configure_btsco_sample_rate(snd_device);
        /* due to the possibility of calibration overwrite between listen
            and audio, notify listen hal before audio calibration is sent */
        audio_extn_sound_trigger_update_device_status(snd_device,
                                        ST_EVENT_SND_DEVICE_BUSY);
        audio_extn_listen_update_device_status(snd_device,
                                        LISTEN_EVENT_SND_DEVICE_BUSY);
        if (platform_get_snd_device_acdb_id(snd_device) < 0) {
            audio_extn_sound_trigger_update_device_status(snd_device,
                                            ST_EVENT_SND_DEVICE_FREE);
            audio_extn_listen_update_device_status(snd_device,
                                        LISTEN_EVENT_SND_DEVICE_FREE);
            goto err;
        }
        audio_extn_dev_arbi_acquire(snd_device);
        audio_route_apply_and_update_path(adev->audio_route, device_name);

        if (SND_DEVICE_OUT_HEADPHONES == snd_device &&
            !adev->native_playback_enabled &&
            audio_is_true_native_stream_active(adev)) {
            ALOGD("%s: %d: napb: enabling native mode in hardware",
                  __func__, __LINE__);
            audio_route_apply_and_update_path(adev->audio_route,
                                              "true-native-mode");
            adev->native_playback_enabled = true;
        }
        if (((snd_device == SND_DEVICE_IN_HANDSET_6MIC) ||
            (snd_device == SND_DEVICE_IN_HANDSET_QMIC)) &&
            (audio_extn_ffv_get_stream() == adev_get_active_input(adev))) {
            ALOGD("%s: init ec ref loopback", __func__);
            audio_extn_ffv_init_ec_ref_loopback(adev, snd_device);
        }
    }
    return 0;
err:
    adev->snd_dev_ref_cnt[snd_device]--;
    return -EINVAL;;
}

int disable_snd_device(struct audio_device *adev,
                       snd_device_t snd_device)
{
    int i, num_devices = 0;
    snd_device_t new_snd_devices[SND_DEVICE_OUT_END];
    char device_name[DEVICE_NAME_MAX_SIZE] = {0};

    if (snd_device < SND_DEVICE_MIN ||
        snd_device >= SND_DEVICE_MAX) {
        ALOGE("%s: Invalid sound device %d", __func__, snd_device);
        return -EINVAL;
    }

    if (platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0) {
        ALOGE("%s: Invalid sound device returned", __func__);
        return -EINVAL;
    }

    if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
        ALOGE("%s: device ref cnt is already 0", __func__);
        return -EINVAL;
    }

    adev->snd_dev_ref_cnt[snd_device]--;


    if (adev->snd_dev_ref_cnt[snd_device] == 0) {
        ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);

        audio_extn_dsm_feedback_enable(adev, snd_device, false);

        if (platform_can_enable_spkr_prot_on_device(snd_device) &&
             audio_extn_spkr_prot_is_enabled()) {
            audio_extn_spkr_prot_stop_processing(snd_device);

            // when speaker device is disabled, reset swap.
            // will be renabled on usecase start
            platform_set_swap_channels(adev, false);
        } else if (platform_split_snd_device(adev->platform,
                                             snd_device,
                                             &num_devices,
                                             new_snd_devices) == 0) {
            for (i = 0; i < num_devices; i++) {
                disable_snd_device(adev, new_snd_devices[i]);
            }
            platform_set_speaker_gain_in_combo(adev, snd_device, false);
        } else {
            audio_route_reset_and_update_path(adev->audio_route, device_name);
        }

        if (snd_device == SND_DEVICE_OUT_BT_A2DP)
            audio_extn_a2dp_stop_playback();
        else if (snd_device == SND_DEVICE_IN_BT_A2DP)
            audio_extn_a2dp_stop_capture();
        else if ((snd_device == SND_DEVICE_OUT_HDMI) ||
                (snd_device == SND_DEVICE_OUT_DISPLAY_PORT))
            adev->is_channel_status_set = false;
        else if ((snd_device == SND_DEVICE_OUT_HEADPHONES) &&
                 adev->native_playback_enabled) {
            ALOGD("%s: %d: napb: disabling native mode in hardware",
                  __func__, __LINE__);
            audio_route_reset_and_update_path(adev->audio_route,
                                              "true-native-mode");
            adev->native_playback_enabled = false;
        } else if ((snd_device == SND_DEVICE_OUT_HEADPHONES) &&
                 adev->asrc_mode_enabled) {
            ALOGD("%s: %d: disabling asrc mode in hardware", __func__, __LINE__);
            disable_asrc_mode(adev);
            audio_route_apply_and_update_path(adev->audio_route, "hph-lowpower-mode");
        } else if (((snd_device == SND_DEVICE_IN_HANDSET_6MIC) ||
            (snd_device == SND_DEVICE_IN_HANDSET_QMIC)) &&
            (audio_extn_ffv_get_stream() == adev_get_active_input(adev))) {
            ALOGD("%s: deinit ec ref loopback", __func__);
            audio_extn_ffv_deinit_ec_ref_loopback(adev, snd_device);
        }

        audio_extn_utils_release_snd_device(snd_device);
    } else {
        if (platform_split_snd_device(adev->platform,
                    snd_device,
                    &num_devices,
                    new_snd_devices) == 0) {
            for (i = 0; i < num_devices; i++) {
                adev->snd_dev_ref_cnt[new_snd_devices[i]]--;
            }
        }
    }

    return 0;
}

/*
  legend:
  uc - existing usecase
  new_uc - new usecase
  d1, d11, d2 - SND_DEVICE enums
  a1, a2 - corresponding ANDROID device enums
  B1, B2 - backend strings

case 1
  uc->dev  d1 (a1)               B1
  new_uc->dev d1 (a1), d2 (a2)   B1, B2

  resolution: disable and enable uc->dev on d1

case 2
  uc->dev d1 (a1)        B1
  new_uc->dev d11 (a1)   B1

  resolution: need to switch uc since d1 and d11 are related
  (e.g. speaker and voice-speaker)
  use ANDROID_DEVICE_OUT enums to match devices since SND_DEVICE enums may vary

case 3
  uc->dev d1 (a1)        B1
  new_uc->dev d2 (a2)    B2

  resolution: no need to switch uc

case 4
  uc->dev d1 (a1)      B1
  new_uc->dev d2 (a2)  B1

  resolution: disable enable uc-dev on d2 since backends match
  we cannot enable two streams on two different devices if they
  share the same backend. e.g. if offload is on speaker device using
  QUAD_MI2S backend and a low-latency stream is started on voice-handset
  using the same backend, offload must also be switched to voice-handset.

case 5
  uc->dev  d1 (a1)                  B1
  new_uc->dev d1 (a1), d2 (a2)      B1

  resolution: disable enable uc-dev on d2 since backends match
  we cannot enable two streams on two different devices if they
  share the same backend.

case 6
  uc->dev  d1 (a1)    B1
  new_uc->dev d2 (a1) B2

  resolution: no need to switch

case 7
  uc->dev d1 (a1), d2 (a2)       B1, B2
  new_uc->dev d1 (a1)            B1

  resolution: no need to switch

case 8
  uc->dev d1 (a1)                B1
  new_uc->dev d11 (a1), d2 (a2)  B1, B2
  resolution: compared to case 1, for this case, d1 and d11 are related
  then need to do the same as case 2 to siwtch to new uc
*/
static snd_device_t derive_playback_snd_device(void * platform,
                                               struct audio_usecase *uc,
                                               struct audio_usecase *new_uc,
                                               snd_device_t new_snd_device)
{
    audio_devices_t a1, a2;

    snd_device_t d1 = uc->out_snd_device;
    snd_device_t d2 = new_snd_device;

    switch (uc->type) {
        case TRANSCODE_LOOPBACK_RX :
            a1 = uc->stream.inout->out_config.devices;
            a2 = new_uc->stream.inout->out_config.devices;
            break;
        default :
            a1 = uc->stream.out->devices;
            a2 = new_uc->stream.out->devices;
            break;
    }

    // Treat as a special case when a1 and a2 are not disjoint
    if ((a1 != a2) && (a1 & a2)) {
        snd_device_t d3[2];
        int num_devices = 0;
        int ret = platform_split_snd_device(platform,
                                            popcount(a1) > 1 ? d1 : d2,
                                            &num_devices,
                                            d3);
        if (ret < 0) {
            if (ret != -ENOSYS) {
                ALOGW("%s failed to split snd_device %d",
                      __func__,
                      popcount(a1) > 1 ? d1 : d2);
            }
            goto end;
        }

        if (platform_check_backends_match(d3[0], d3[1])) {
            return d2; // case 5
        } else {
            if (popcount(a1) > 1)
                return d1; //case 7
            // check if d1 is related to any of d3's
            if (d1 == d3[0] || d1 == d3[1])
                return d1; // case 1
            else
                return d3[1]; // case 8
        }
    } else {
        if (platform_check_backends_match(d1, d2)) {
            return d2; // case 2, 4
        } else {
            return d1; // case 6, 3
        }
    }

end:
    return d2; // return whatever was calculated before.
}

static void check_usecases_codec_backend(struct audio_device *adev,
                                              struct audio_usecase *uc_info,
                                              snd_device_t snd_device)
{
    struct listnode *node;
    struct audio_usecase *usecase;
    bool switch_device[AUDIO_USECASE_MAX];
    snd_device_t uc_derive_snd_device;
    snd_device_t derive_snd_device[AUDIO_USECASE_MAX];
    snd_device_t split_snd_devices[SND_DEVICE_OUT_END];
    int i, num_uc_to_switch = 0, num_devices = 0;
    int status = 0;
    bool force_restart_session = false;
    /*
     * This function is to make sure that all the usecases that are active on
     * the hardware codec backend are always routed to any one device that is
     * handled by the hardware codec.
     * For example, if low-latency and deep-buffer usecases are currently active
     * on speaker and out_set_parameters(headset) is received on low-latency
     * output, then we have to make sure deep-buffer is also switched to headset,
     * because of the limitation that both the devices cannot be enabled
     * at the same time as they share the same backend.
     */
    /*
     * This call is to check if we need to force routing for a particular stream
     * If there is a backend configuration change for the device when a
     * new stream starts, then ADM needs to be closed and re-opened with the new
     * configuraion. This call check if we need to re-route all the streams
     * associated with the backend. Touch tone + 24 bit + native playback.
     */
    bool force_routing = platform_check_and_set_codec_backend_cfg(adev, uc_info,
                         snd_device);
    /* For a2dp device reconfigure all active sessions
     * with new AFE encoder format based on a2dp state
     */
    if ((SND_DEVICE_OUT_BT_A2DP == snd_device ||
         SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP == snd_device) &&
         audio_extn_a2dp_is_force_device_switch()) {
         force_routing = true;
         force_restart_session = true;
    }
    ALOGD("%s:becf: force routing %d", __func__, force_routing);

    /* Disable all the usecases on the shared backend other than the
     * specified usecase.
     */
    for (i = 0; i < AUDIO_USECASE_MAX; i++)
        switch_device[i] = false;

    list_for_each(node, &adev->usecase_list) {
        usecase = node_to_item(node, struct audio_usecase, list);

        ALOGD("%s:becf: (%d) check_usecases curr device: %s, usecase device:%s "
            "backends match %d",__func__, i,
              platform_get_snd_device_name(snd_device),
              platform_get_snd_device_name(usecase->out_snd_device),
              platform_check_backends_match(snd_device, usecase->out_snd_device));
        if ((usecase->type != PCM_CAPTURE) && (usecase != uc_info) &&
                (usecase->type != PCM_PASSTHROUGH)) {
            uc_derive_snd_device = derive_playback_snd_device(adev->platform,
                                               usecase, uc_info, snd_device);
            if (((uc_derive_snd_device != usecase->out_snd_device) || force_routing) &&
                ((usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
                (usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) ||
                (usecase->devices & AUDIO_DEVICE_OUT_USB_DEVICE) ||
                (usecase->devices &  AUDIO_DEVICE_OUT_USB_HEADSET) ||
                (usecase->devices & AUDIO_DEVICE_OUT_ALL_A2DP) ||
                (usecase->devices & AUDIO_DEVICE_OUT_ALL_SCO)) &&
                ((force_restart_session) ||
                (platform_check_backends_match(snd_device, usecase->out_snd_device)))) {
                ALOGD("%s:becf: check_usecases (%s) is active on (%s) - disabling ..",
                    __func__, use_case_table[usecase->id],
                      platform_get_snd_device_name(usecase->out_snd_device));
                disable_audio_route(adev, usecase);
                switch_device[usecase->id] = true;
                /* Enable existing usecase on derived playback device */
                derive_snd_device[usecase->id] = uc_derive_snd_device;
                num_uc_to_switch++;
            }
        }
    }

    ALOGD("%s:becf: check_usecases num.of Usecases to switch %d", __func__,
        num_uc_to_switch);

    if (num_uc_to_switch) {
        /* All streams have been de-routed. Disable the device */

        /* Make sure the previous devices to be disabled first and then enable the
           selected devices */
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            if (switch_device[usecase->id]) {
                /* Check if output sound device to be switched can be split and if any
                   of the split devices match with derived sound device */
                if (platform_split_snd_device(adev->platform, usecase->out_snd_device,
                                               &num_devices, split_snd_devices) == 0) {
                    adev->snd_dev_ref_cnt[usecase->out_snd_device]--;
                    for (i = 0; i < num_devices; i++) {
                        /* Disable devices that do not match with derived sound device */
                        if (split_snd_devices[i] != derive_snd_device[usecase->id])
                            disable_snd_device(adev, split_snd_devices[i]);
                     }
                } else {
                    disable_snd_device(adev, usecase->out_snd_device);
                }
            }
        }

        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            if (switch_device[usecase->id]) {
                if (platform_split_snd_device(adev->platform, usecase->out_snd_device,
                                               &num_devices, split_snd_devices) == 0) {
                        /* Enable derived sound device only if it does not match with
                           one of the split sound devices. This is because the matching
                           sound device was not disabled */
                        bool should_enable = true;
                        for (i = 0; i < num_devices; i++) {
                            if (derive_snd_device[usecase->id] == split_snd_devices[i]) {
                                 should_enable = false;
                                 break;
                            }
                        }
                        if (should_enable)
                            enable_snd_device(adev, derive_snd_device[usecase->id]);
                } else {
                    enable_snd_device(adev, derive_snd_device[usecase->id]);
                }
            }
        }

        /* Re-route all the usecases on the shared backend other than the
           specified usecase to new snd devices */
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            /* Update the out_snd_device only before enabling the audio route */
            if (switch_device[usecase->id]) {
                usecase->out_snd_device = derive_snd_device[usecase->id];
                if (usecase->type != VOICE_CALL) {
                    ALOGD("%s:becf: enabling usecase (%s) on (%s)", __func__,
                         use_case_table[usecase->id],
                         platform_get_snd_device_name(usecase->out_snd_device));
                    /* Update voc calibration before enabling VoIP route */
                    if (usecase->type == VOIP_CALL)
                        status = platform_switch_voice_call_device_post(adev->platform,
                                                           usecase->out_snd_device,
                                                           platform_get_input_snd_device(
                                                               adev->platform, NULL,
                                                               uc_info->devices));
                    enable_audio_route(adev, usecase);
                    if (usecase->stream.out && usecase->id == USECASE_AUDIO_PLAYBACK_VOIP) {
                        out_set_voip_volume(&usecase->stream.out->stream,
                                            usecase->stream.out->volume_l,
                                            usecase->stream.out->volume_r);
                    }
                }
            }
        }
    }
}

static void check_usecases_capture_codec_backend(struct audio_device *adev,
                                             struct audio_usecase *uc_info,
                                             snd_device_t snd_device)
{
    struct listnode *node;
    struct audio_usecase *usecase;
    bool switch_device[AUDIO_USECASE_MAX];
    int i, num_uc_to_switch = 0;
    int backend_check_cond = AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND;
    int status = 0;

    bool force_routing = platform_check_and_set_capture_codec_backend_cfg(adev, uc_info,
                         snd_device);
    ALOGD("%s:becf: force routing %d", __func__, force_routing);

    /*
     * Make sure out devices is checked against out codec backend device and
     * also in devices against in codec backend. Checking out device against in
     * codec backend or vice versa causes issues.
     */
    if (uc_info->type == PCM_CAPTURE)
        backend_check_cond = AUDIO_DEVICE_IN_ALL_CODEC_BACKEND;
    /*
     * This function is to make sure that all the active capture usecases
     * are always routed to the same input sound device.
     * For example, if audio-record and voice-call usecases are currently
     * active on speaker(rx) and speaker-mic (tx) and out_set_parameters(earpiece)
     * is received for voice call then we have to make sure that audio-record
     * usecase is also switched to earpiece i.e. voice-dmic-ef,
     * because of the limitation that two devices cannot be enabled
     * at the same time if they share the same backend.
     */
    for (i = 0; i < AUDIO_USECASE_MAX; i++)
        switch_device[i] = false;

    list_for_each(node, &adev->usecase_list) {
        usecase = node_to_item(node, struct audio_usecase, list);
        /*
         * TODO: Enhance below condition to handle BT sco/USB multi recording
         */
        if (usecase->type != PCM_PLAYBACK &&
                usecase != uc_info &&
                (usecase->in_snd_device != snd_device || force_routing) &&
                ((uc_info->devices & backend_check_cond) &&
                 (((usecase->devices & ~AUDIO_DEVICE_BIT_IN) & AUDIO_DEVICE_IN_ALL_CODEC_BACKEND) ||
                  (usecase->type == VOIP_CALL))) &&
                ((uc_info->type == VOICE_CALL &&
                  usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL) ||
                 platform_check_backends_match(snd_device,\
                                              usecase->in_snd_device)) &&
                (usecase->id != USECASE_AUDIO_SPKR_CALIB_TX)) {
            ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
                  __func__, use_case_table[usecase->id],
                  platform_get_snd_device_name(usecase->in_snd_device));
            disable_audio_route(adev, usecase);
            switch_device[usecase->id] = true;
            num_uc_to_switch++;
        }
    }

    if (num_uc_to_switch) {
        /* All streams have been de-routed. Disable the device */

        /* Make sure the previous devices to be disabled first and then enable the
           selected devices */
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            if (switch_device[usecase->id]) {
                disable_snd_device(adev, usecase->in_snd_device);
            }
        }

        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            if (switch_device[usecase->id]) {
                enable_snd_device(adev, snd_device);
            }
        }

        /* Re-route all the usecases on the shared backend other than the
           specified usecase to new snd devices */
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            /* Update the in_snd_device only before enabling the audio route */
            if (switch_device[usecase->id] ) {
                usecase->in_snd_device = snd_device;
                if (usecase->type != VOICE_CALL) {
                    /* Update voc calibration before enabling VoIP route */
                    if (usecase->type == VOIP_CALL)
                        status = platform_switch_voice_call_device_post(adev->platform,
                                                                        platform_get_output_snd_device(adev->platform, uc_info->stream.out),
                                                                        usecase->in_snd_device);
                    enable_audio_route(adev, usecase);
                }
            }
        }
    }
}

static void reset_hdmi_sink_caps(struct stream_out *out) {
    int i = 0;

    for (i = 0; i<= MAX_SUPPORTED_CHANNEL_MASKS; i++) {
        out->supported_channel_masks[i] = 0;
    }
    for (i = 0; i<= MAX_SUPPORTED_FORMATS; i++) {
        out->supported_formats[i] = 0;
    }
    for (i = 0; i<= MAX_SUPPORTED_SAMPLE_RATES; i++) {
        out->supported_sample_rates[i] = 0;
    }
}

/* must be called with hw device mutex locked */
static int read_hdmi_sink_caps(struct stream_out *out)
{
    int ret = 0, i = 0, j = 0;
    int channels = platform_edid_get_max_channels(out->dev->platform);

    reset_hdmi_sink_caps(out);

    /* Cache ext disp type */
    if (platform_get_ext_disp_type(adev->platform) <= 0) {
        ALOGE("%s: Failed to query disp type, ret:%d", __func__, ret);
        return -EINVAL;
    }

    switch (channels) {
    case 8:
        ALOGV("%s: HDMI supports 7.1 channels", __func__);
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_7POINT1;
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_6POINT1;
    case 6:
        ALOGV("%s: HDMI supports 5.1 channels", __func__);
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_5POINT1;
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_PENTA;
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_QUAD;
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_SURROUND;
        out->supported_channel_masks[i++] = AUDIO_CHANNEL_OUT_2POINT1;
        break;
    default:
        ALOGE("invalid/nonstandard channal count[%d]",channels);
        ret = -ENOSYS;
        break;
    }

    // check channel format caps
    i = 0;
    if (platform_is_edid_supported_format(out->dev->platform, AUDIO_FORMAT_AC3)) {
        ALOGV(":%s HDMI supports AC3/EAC3 formats", __func__);
        out->supported_formats[i++] = AUDIO_FORMAT_AC3;
        //Adding EAC3/EAC3_JOC formats if AC3 is supported by the sink.
        //EAC3/EAC3_JOC will be converted to AC3 for decoding if needed
        out->supported_formats[i++] = AUDIO_FORMAT_E_AC3;
        out->supported_formats[i++] = AUDIO_FORMAT_E_AC3_JOC;
    }

    if (platform_is_edid_supported_format(out->dev->platform, AUDIO_FORMAT_DOLBY_TRUEHD)) {
        ALOGV(":%s HDMI supports TRUE HD format", __func__);
        out->supported_formats[i++] = AUDIO_FORMAT_DOLBY_TRUEHD;
    }

    if (platform_is_edid_supported_format(out->dev->platform, AUDIO_FORMAT_DTS)) {
        ALOGV(":%s HDMI supports DTS format", __func__);
        out->supported_formats[i++] = AUDIO_FORMAT_DTS;
    }

    if (platform_is_edid_supported_format(out->dev->platform, AUDIO_FORMAT_DTS_HD)) {
        ALOGV(":%s HDMI supports DTS HD format", __func__);
        out->supported_formats[i++] = AUDIO_FORMAT_DTS_HD;
    }

    if (platform_is_edid_supported_format(out->dev->platform, AUDIO_FORMAT_IEC61937)) {
        ALOGV(":%s HDMI supports IEC61937 format", __func__);
        out->supported_formats[i++] = AUDIO_FORMAT_IEC61937;
    }


    // check sample rate caps
    i = 0;
    for (j = 0; j < MAX_SUPPORTED_SAMPLE_RATES; j++) {
        if (platform_is_edid_supported_sample_rate(out->dev->platform, out_hdmi_sample_rates[j])) {
            ALOGV(":%s HDMI supports sample rate:%d", __func__, out_hdmi_sample_rates[j]);
            out->supported_sample_rates[i++] = out_hdmi_sample_rates[j];
        }
    }

    return ret;
}

static inline ssize_t read_usb_sup_sample_rates(bool is_playback __unused,
                                         uint32_t *supported_sample_rates __unused,
                                         uint32_t max_rates __unused)
{
    ssize_t count = audio_extn_usb_get_sup_sample_rates(is_playback,
                                                        supported_sample_rates,
                                                        max_rates);
    ssize_t i = 0;

    for (i=0; i<count; i++) {
        ALOGV("%s %s %d", __func__, is_playback ? "P" : "C",
              supported_sample_rates[i]);
    }
    return count;
}

static inline int read_usb_sup_channel_masks(bool is_playback,
                                      audio_channel_mask_t *supported_channel_masks,
                                      uint32_t max_masks)
{
    int channels = audio_extn_usb_get_max_channels(is_playback);
    int channel_count;
    uint32_t num_masks = 0;
    if (channels > MAX_HIFI_CHANNEL_COUNT)
        channels = MAX_HIFI_CHANNEL_COUNT;

    if (is_playback) {
        // start from 2 channels as framework currently doesn't support mono.
        if (channels >= FCC_2) {
            supported_channel_masks[num_masks++] = audio_channel_out_mask_from_count(FCC_2);
        }
        for (channel_count = FCC_2;
                channel_count <= channels && num_masks < max_masks;
                ++channel_count) {
            supported_channel_masks[num_masks++] =
                    audio_channel_mask_for_index_assignment_from_count(channel_count);
        }
    } else {
        // For capture we report all supported channel masks from 1 channel up.
        channel_count = MIN_CHANNEL_COUNT;
        // audio_channel_in_mask_from_count() does the right conversion to either positional or
        // indexed mask
        for ( ; channel_count <= channels && num_masks < max_masks; channel_count++) {
            audio_channel_mask_t mask = AUDIO_CHANNEL_NONE;
            if (channel_count <= FCC_2) {
                mask = audio_channel_in_mask_from_count(channel_count);
                supported_channel_masks[num_masks++] = mask;
            }
            const audio_channel_mask_t index_mask =
                    audio_channel_mask_for_index_assignment_from_count(channel_count);
            if (mask != index_mask && num_masks < max_masks) { // ensure index mask added.
                supported_channel_masks[num_masks++] = index_mask;
            }
        }
    }

    for (size_t i = 0; i < num_masks; ++i) {
        ALOGV("%s: %s supported ch %d supported_channel_masks[%zu] %08x num_masks %d", __func__,
              is_playback ? "P" : "C", channels, i, supported_channel_masks[i], num_masks);
    }
    return num_masks;
}

static inline int read_usb_sup_formats(bool is_playback __unused,
                                audio_format_t *supported_formats,
                                uint32_t max_formats __unused)
{
    int bitwidth = audio_extn_usb_get_max_bit_width(is_playback);
    switch (bitwidth) {
        case 24:
            // XXX : usb.c returns 24 for s24 and s24_le?
            supported_formats[0] = AUDIO_FORMAT_PCM_24_BIT_PACKED;
            break;
        case 32:
            supported_formats[0] = AUDIO_FORMAT_PCM_32_BIT;
            break;
        case 16:
        default :
            supported_formats[0] = AUDIO_FORMAT_PCM_16_BIT;
            break;
    }
    ALOGV("%s: %s supported format %d", __func__,
          is_playback ? "P" : "C", bitwidth);
    return 1;
}

static inline int read_usb_sup_params_and_compare(bool is_playback,
                                           audio_format_t *format,
                                           audio_format_t *supported_formats,
                                           uint32_t max_formats,
                                           audio_channel_mask_t *mask,
                                           audio_channel_mask_t *supported_channel_masks,
                                           uint32_t max_masks,
                                           uint32_t *rate,
                                           uint32_t *supported_sample_rates,
                                           uint32_t max_rates) {
    int ret = 0;
    int num_formats;
    int num_masks;
    int num_rates;
    int i;

    num_formats = read_usb_sup_formats(is_playback, supported_formats,
                                       max_formats);
    num_masks = read_usb_sup_channel_masks(is_playback, supported_channel_masks,
                                           max_masks);

    num_rates = read_usb_sup_sample_rates(is_playback,
                                          supported_sample_rates, max_rates);

#define LUT(table, len, what, dflt)                  \
    for (i=0; i<len && (table[i] != what); i++);    \
    if (i==len) { ret |= (what == dflt ? 0 : -1); what=table[0]; }

    LUT(supported_formats, num_formats, *format, AUDIO_FORMAT_DEFAULT);
    LUT(supported_channel_masks, num_masks, *mask, AUDIO_CHANNEL_NONE);
    LUT(supported_sample_rates, num_rates, *rate, 0);

#undef LUT
    return ret < 0 ? -EINVAL : 0; // HACK TBD
}

audio_usecase_t get_usecase_id_from_usecase_type(const struct audio_device *adev,
                                                 usecase_type_t type)
{
    struct audio_usecase *usecase;
    struct listnode *node;

    list_for_each(node, &adev->usecase_list) {
        usecase = node_to_item(node, struct audio_usecase, list);
        if (usecase->type == type) {
            ALOGV("%s: usecase id %d", __func__, usecase->id);
            return usecase->id;
        }
    }
    return USECASE_INVALID;
}

struct audio_usecase *get_usecase_from_list(const struct audio_device *adev,
                                            audio_usecase_t uc_id)
{
    struct audio_usecase *usecase;
    struct listnode *node;

    list_for_each(node, &adev->usecase_list) {
        usecase = node_to_item(node, struct audio_usecase, list);
        if (usecase->id == uc_id)
            return usecase;
    }
    return NULL;
}

/*
 * is a true native playback active
 */
bool audio_is_true_native_stream_active(struct audio_device *adev)
{
    bool active = false;
    int i = 0;
    struct listnode *node;

    if (NATIVE_AUDIO_MODE_TRUE_44_1 != platform_get_native_support()) {
        ALOGV("%s:napb: not in true mode or non hdphones device",
               __func__);
        active = false;
        goto exit;
    }

    list_for_each(node, &adev->usecase_list) {
        struct audio_usecase *uc;
        uc = node_to_item(node, struct audio_usecase, list);
        struct stream_out *curr_out =
            (struct stream_out*) uc->stream.out;

        if (curr_out && PCM_PLAYBACK == uc->type) {
            ALOGD("%s:napb: (%d) (%s)id (%d) sr %d bw "
                  "(%d) device %s", __func__, i++, use_case_table[uc->id],
                  uc->id, curr_out->sample_rate,
                  curr_out->bit_width,
                  platform_get_snd_device_name(uc->out_snd_device));

            if (is_offload_usecase(uc->id) &&
                (curr_out->sample_rate == OUTPUT_SAMPLING_RATE_44100)) {
                active = true;
                ALOGD("%s:napb:native stream detected", __func__);
            }
        }
    }
exit:
    return active;
}

uint32_t adev_get_dsp_bit_width_enforce_mode()
{
    if (adev == NULL) {
        ALOGE("%s: adev is null. Disable DSP bit width enforce mode.\n", __func__);
        return 0;
    }
    return adev->dsp_bit_width_enforce_mode;
}

static uint32_t adev_init_dsp_bit_width_enforce_mode(struct mixer *mixer)
{
    char value[PROPERTY_VALUE_MAX];
    int trial;
    uint32_t dsp_bit_width_enforce_mode = 0;

    if (!mixer) {
        ALOGE("%s: adev mixer is null. cannot update DSP bitwidth.\n",
                __func__);
        return 0;
    }

    if (property_get("persist.vendor.audio_hal.dsp_bit_width_enforce_mode",
                        value, NULL) > 0) {
        trial = atoi(value);
        switch (trial) {
        case 16:
            dsp_bit_width_enforce_mode = 16;
            break;
        case 24:
            dsp_bit_width_enforce_mode = 24;
            break;
        case 32:
            dsp_bit_width_enforce_mode = 32;
            break;
       default:
            dsp_bit_width_enforce_mode = 0;
            ALOGD("%s Dynamic DSP bitwidth config is disabled.", __func__);
            break;
        }
    }

    return dsp_bit_width_enforce_mode;
}

static void audio_enable_asm_bit_width_enforce_mode(struct mixer *mixer,
                                                uint32_t enforce_mode,
                                                bool enable)
{
    struct mixer_ctl *ctl = NULL;
    const char *mixer_ctl_name = "ASM Bit Width";
    uint32_t asm_bit_width_mode = 0;

    if (enforce_mode == 0) {
        ALOGD("%s: DSP bitwidth feature is disabled.", __func__);
        return;
    }

    ctl = mixer_get_ctl_by_name(mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: Could not get ctl for mixer cmd - %s",
                __func__, mixer_ctl_name);
        return;
    }

    if (enable)
        asm_bit_width_mode = enforce_mode;
    else
        asm_bit_width_mode = 0;

    ALOGV("%s DSP bit width feature status is %d width=%d",
        __func__, enable, asm_bit_width_mode);
    if (mixer_ctl_set_value(ctl, 0, asm_bit_width_mode) < 0)
        ALOGE("%s: Could not set ASM biwidth %d", __func__,
                asm_bit_width_mode);

    return;
}

/*
 * if native DSD playback active
 */
bool audio_is_dsd_native_stream_active(struct audio_device *adev)
{
    bool active = false;
    struct listnode *node = NULL;
    struct audio_usecase *uc = NULL;
    struct stream_out *curr_out = NULL;

    list_for_each(node, &adev->usecase_list) {
        uc = node_to_item(node, struct audio_usecase, list);
        curr_out = (struct stream_out*) uc->stream.out;

        if (curr_out && PCM_PLAYBACK == uc->type &&
               (DSD_NATIVE_BACKEND == platform_get_backend_index(uc->out_snd_device))) {
            active = true;
            ALOGV("%s:DSD playback is active", __func__);
            break;
        }
    }
    return active;
}

static bool force_device_switch(struct audio_usecase *usecase)
{
    bool ret = false;
    bool is_it_true_mode = false;

    if (usecase->type == PCM_CAPTURE ||
        usecase->type == TRANSCODE_LOOPBACK_RX ||
        usecase->type == TRANSCODE_LOOPBACK_TX) {
        return false;
    }

    if(usecase->stream.out == NULL) {
        ALOGE("%s: stream.out is NULL", __func__);
        return false;
    }

    if (is_offload_usecase(usecase->id) &&
        (usecase->stream.out->sample_rate == OUTPUT_SAMPLING_RATE_44100) &&
        (usecase->stream.out->devices == AUDIO_DEVICE_OUT_WIRED_HEADSET ||
         usecase->stream.out->devices == AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) {
        is_it_true_mode = (NATIVE_AUDIO_MODE_TRUE_44_1 == platform_get_native_support()? true : false);
         if ((is_it_true_mode && !adev->native_playback_enabled) ||
             (!is_it_true_mode && adev->native_playback_enabled)){
            ret = true;
            ALOGD("napb: time to toggle native mode");
        }
    }

    // Force all a2dp output devices to reconfigure for proper AFE encode format
    //Also handle a case where in earlier a2dp start failed as A2DP stream was
    //in suspended state, hence try to trigger a retry when we again get a routing request.
    if((usecase->stream.out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
        audio_extn_a2dp_is_force_device_switch()) {
         ALOGD("Force a2dp device switch to update new encoder config");
         ret = true;
    }

    if (usecase->stream.out->stream_config_changed) {
         ALOGD("Force stream_config_changed to update iec61937 transmission config");
         return true;
    }
    return ret;
}

static void stream_app_type_cfg_init(struct stream_app_type_cfg *cfg)
{
    cfg->gain[0] = cfg->gain[1] = APP_TYPE_GAIN_DEFAULT;
}

bool is_btsco_device(snd_device_t out_snd_device, snd_device_t in_snd_device)
{
   bool ret=false;
   if ((out_snd_device == SND_DEVICE_OUT_BT_SCO ||
        out_snd_device == SND_DEVICE_OUT_BT_SCO_WB) ||
        in_snd_device == SND_DEVICE_IN_BT_SCO_MIC_WB_NREC ||
        in_snd_device == SND_DEVICE_IN_BT_SCO_MIC_WB ||
        in_snd_device == SND_DEVICE_IN_BT_SCO_MIC_NREC ||
        in_snd_device == SND_DEVICE_IN_BT_SCO_MIC)
        ret = true;

   return ret;
}

bool is_a2dp_device(snd_device_t out_snd_device)
{
   bool ret=false;
   if (out_snd_device == SND_DEVICE_OUT_BT_A2DP)
        ret = true;

   return ret;
}

bool is_bt_soc_on(struct audio_device *adev)
{
    struct mixer_ctl *ctl;
    char *mixer_ctl_name = "BT SOC status";
    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    bool bt_soc_status = true;
    if (!ctl) {
        ALOGE("%s: Could not get ctl for mixer cmd - %s",
              __func__, mixer_ctl_name);
        /*This is to ensure we dont break targets which dont have the kernel change*/
        return true;
    }
    bt_soc_status = mixer_ctl_get_value(ctl, 0);
    ALOGD("BT SOC status: %d",bt_soc_status);
    return bt_soc_status;
}

static int configure_btsco_sample_rate(snd_device_t snd_device)
{
    struct mixer_ctl *ctl = NULL;
    struct mixer_ctl *ctl_sr_rx = NULL, *ctl_sr_tx = NULL, *ctl_sr = NULL;
    char *rate_str = NULL;
    bool is_rx_dev = true;

    if (is_btsco_device(snd_device, snd_device)) {
        ctl_sr_tx = mixer_get_ctl_by_name(adev->mixer, "BT SampleRate TX");
        ctl_sr_rx = mixer_get_ctl_by_name(adev->mixer, "BT SampleRate RX");
        if (!ctl_sr_tx || !ctl_sr_rx) {
            ctl_sr = mixer_get_ctl_by_name(adev->mixer, "BT SampleRate");
            if (!ctl_sr)
                return -ENOSYS;
        }

        switch (snd_device) {
        case SND_DEVICE_OUT_BT_SCO:
            rate_str = "KHZ_8";
            break;
        case SND_DEVICE_IN_BT_SCO_MIC_NREC:
        case SND_DEVICE_IN_BT_SCO_MIC:
            rate_str = "KHZ_8";
            is_rx_dev = false;
            break;
        case SND_DEVICE_OUT_BT_SCO_WB:
            rate_str = "KHZ_16";
            break;
        case SND_DEVICE_IN_BT_SCO_MIC_WB_NREC:
        case SND_DEVICE_IN_BT_SCO_MIC_WB:
            rate_str = "KHZ_16";
            is_rx_dev = false;
            break;
        default:
            return 0;
        }

        ctl = (ctl_sr == NULL) ? (is_rx_dev ? ctl_sr_rx : ctl_sr_tx) : ctl_sr;
        if (mixer_ctl_set_enum_by_string(ctl, rate_str) != 0)
            return -ENOSYS;
    }
    return 0;
}

int out_standby_l(struct audio_stream *stream);

struct stream_in *adev_get_active_input(const struct audio_device *adev)
{
    struct listnode *node;
    struct stream_in *last_active_in = NULL;

    /* Get last added active input.
     * TODO: We may use a priority mechanism to pick highest priority active source */
    list_for_each(node, &adev->usecase_list)
    {
        struct audio_usecase *usecase = node_to_item(node, struct audio_usecase, list);
        if (usecase->type == PCM_CAPTURE && usecase->stream.in != NULL)
            last_active_in =  usecase->stream.in;
    }

    return last_active_in;
}

struct stream_in *get_voice_communication_input(const struct audio_device *adev)
{
    struct listnode *node;

    /* First check active inputs with voice communication source and then
     * any input if audio mode is in communication */
    list_for_each(node, &adev->usecase_list)
    {
        struct audio_usecase *usecase = node_to_item(node, struct audio_usecase, list);
        if (usecase->type == PCM_CAPTURE && usecase->stream.in != NULL &&
            usecase->stream.in->source == AUDIO_SOURCE_VOICE_COMMUNICATION)
            return usecase->stream.in;
    }
    if (adev->mode == AUDIO_MODE_IN_COMMUNICATION)
        return adev_get_active_input(adev);

    return NULL;
}

/*
 * Aligned with policy.h
 */
static inline int source_priority(int inputSource)
{
    switch (inputSource) {
    case AUDIO_SOURCE_VOICE_COMMUNICATION:
        return 9;
    case AUDIO_SOURCE_CAMCORDER:
        return 8;
    case AUDIO_SOURCE_VOICE_PERFORMANCE:
        return 7;
    case AUDIO_SOURCE_UNPROCESSED:
        return 6;
    case AUDIO_SOURCE_MIC:
        return 5;
    case AUDIO_SOURCE_ECHO_REFERENCE:
        return 4;
    case AUDIO_SOURCE_FM_TUNER:
        return 3;
    case AUDIO_SOURCE_VOICE_RECOGNITION:
        return 2;
    case AUDIO_SOURCE_HOTWORD:
        return 1;
    default:
        break;
    }
    return 0;
}

static struct stream_in *get_priority_input(struct audio_device *adev)
{
    struct listnode *node;
    struct audio_usecase *usecase;
    int last_priority = 0, priority;
    struct stream_in *priority_in = NULL;
    struct stream_in *in;

    list_for_each(node, &adev->usecase_list) {
        usecase = node_to_item(node, struct audio_usecase, list);
        if (usecase->type == PCM_CAPTURE) {
            in = usecase->stream.in;
            if (!in)
                continue;
            priority = source_priority(in->source);

            if (priority > last_priority) {
                last_priority = priority;
                priority_in = in;
            }
        }
    }
    return priority_in;
}

int select_devices(struct audio_device *adev, audio_usecase_t uc_id)
{
    snd_device_t out_snd_device = SND_DEVICE_NONE;
    snd_device_t in_snd_device = SND_DEVICE_NONE;
    struct audio_usecase *usecase = NULL;
    struct audio_usecase *vc_usecase = NULL;
    struct audio_usecase *voip_usecase = NULL;
    struct audio_usecase *hfp_usecase = NULL;
    struct stream_out stream_out;
    audio_usecase_t hfp_ucid;
    int status = 0;

    ALOGD("%s for use case (%s)", __func__, use_case_table[uc_id]);

    usecase = get_usecase_from_list(adev, uc_id);
    if (usecase == NULL) {
        ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
        return -EINVAL;
    }

    if ((usecase->type == VOICE_CALL) ||
        (usecase->type == VOIP_CALL)  ||
        (usecase->type == PCM_HFP_CALL)) {
        if(usecase->stream.out == NULL) {
            ALOGE("%s: stream.out is NULL", __func__);
            return -EINVAL;
        }
        out_snd_device = platform_get_output_snd_device(adev->platform,
                                                        usecase->stream.out);
        in_snd_device = platform_get_input_snd_device(adev->platform,
                                                      NULL,
                                                      usecase->stream.out->devices);
        usecase->devices = usecase->stream.out->devices;
    } else if (usecase->type == TRANSCODE_LOOPBACK_RX) {
        if (usecase->stream.inout == NULL) {
            ALOGE("%s: stream.inout is NULL", __func__);
            return -EINVAL;
        }
        stream_out.devices = usecase->stream.inout->out_config.devices;
        stream_out.sample_rate = usecase->stream.inout->out_config.sample_rate;
        stream_out.format = usecase->stream.inout->out_config.format;
        stream_out.channel_mask = usecase->stream.inout->out_config.channel_mask;
        out_snd_device = platform_get_output_snd_device(adev->platform,
                                                        &stream_out);
        usecase->devices = out_snd_device;
    } else if (usecase->type == TRANSCODE_LOOPBACK_TX ) {
        if (usecase->stream.inout == NULL) {
            ALOGE("%s: stream.inout is NULL", __func__);
            return -EINVAL;
        }
        in_snd_device = platform_get_input_snd_device(adev->platform, NULL, AUDIO_DEVICE_NONE);
        usecase->devices = in_snd_device;
    } else {
        /*
         * If the voice call is active, use the sound devices of voice call usecase
         * so that it would not result any device switch. All the usecases will
         * be switched to new device when select_devices() is called for voice call
         * usecase. This is to avoid switching devices for voice call when
         * check_usecases_codec_backend() is called below.
         * choose voice call device only if the use case device is
         * also using the codec backend
         */
        if (voice_is_in_call(adev) && adev->mode != AUDIO_MODE_NORMAL) {
            vc_usecase = get_usecase_from_list(adev,
                                               get_usecase_id_from_usecase_type(adev, VOICE_CALL));
            if ((vc_usecase) && (((vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) &&
                                 (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND)) ||
                                 ((vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) &&
                                 (usecase->devices & AUDIO_DEVICE_IN_ALL_CODEC_BACKEND)) ||
                                 (vc_usecase->devices == AUDIO_DEVICE_OUT_HEARING_AID) ||
                                 (usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL))) {
                in_snd_device = vc_usecase->in_snd_device;
                out_snd_device = vc_usecase->out_snd_device;
            }
        } else if (voice_extn_compress_voip_is_active(adev)) {
            bool out_snd_device_backend_match = true;
            voip_usecase = get_usecase_from_list(adev, USECASE_COMPRESS_VOIP_CALL);
            if ((voip_usecase != NULL) &&
                (usecase->type == PCM_PLAYBACK) &&
                (usecase->stream.out != NULL)) {
                out_snd_device_backend_match = platform_check_backends_match(
                                                   voip_usecase->out_snd_device,
                                                   platform_get_output_snd_device(
                                                       adev->platform,
                                                       usecase->stream.out));
            }
            if ((voip_usecase) && ((voip_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) &&
                ((usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
                  ((usecase->devices & ~AUDIO_DEVICE_BIT_IN) & AUDIO_DEVICE_IN_ALL_CODEC_BACKEND)) &&
                out_snd_device_backend_match &&
                 (voip_usecase->stream.out != adev->primary_output))) {
                    in_snd_device = voip_usecase->in_snd_device;
                    out_snd_device = voip_usecase->out_snd_device;
            }
        } else if (audio_extn_hfp_is_active(adev)) {
            hfp_ucid = audio_extn_hfp_get_usecase();
            hfp_usecase = get_usecase_from_list(adev, hfp_ucid);
            if ((hfp_usecase) && (hfp_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND)) {
                   in_snd_device = hfp_usecase->in_snd_device;
                   out_snd_device = hfp_usecase->out_snd_device;
            }
        }
        if (usecase->type == PCM_PLAYBACK) {
            if (usecase->stream.out == NULL) {
                ALOGE("%s: stream.out is NULL", __func__);
                return -EINVAL;
            }
            usecase->devices = usecase->stream.out->devices;
            in_snd_device = SND_DEVICE_NONE;
            if (out_snd_device == SND_DEVICE_NONE) {
                struct stream_out *voip_out = adev->primary_output;
                struct stream_in *voip_in = get_voice_communication_input(adev);
                out_snd_device = platform_get_output_snd_device(adev->platform,
                                                                usecase->stream.out);
                voip_usecase = get_usecase_from_list(adev, USECASE_AUDIO_PLAYBACK_VOIP);

                if (voip_usecase)
                    voip_out = voip_usecase->stream.out;

                if (usecase->stream.out == voip_out && voip_in != NULL)
                    select_devices(adev, voip_in->usecase);
            }
        } else if (usecase->type == PCM_CAPTURE) {
            if (usecase->stream.in == NULL) {
                ALOGE("%s: stream.in is NULL", __func__);
                return -EINVAL;
            }
            usecase->devices = usecase->stream.in->device;
            out_snd_device = SND_DEVICE_NONE;
            if (in_snd_device == SND_DEVICE_NONE) {
                audio_devices_t out_device = AUDIO_DEVICE_NONE;
                struct stream_in *voip_in = get_voice_communication_input(adev);
                struct stream_in *priority_in = NULL;

                if (voip_in != NULL) {
                    struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
                                                             USECASE_AUDIO_PLAYBACK_VOIP);

                    usecase->stream.in->enable_ec_port = false;

                    if (usecase->id == USECASE_AUDIO_RECORD_AFE_PROXY) {
                        out_device = AUDIO_DEVICE_OUT_TELEPHONY_TX;
                    } else if (voip_usecase) {
                        out_device = voip_usecase->stream.out->devices;
                    } else if (adev->primary_output &&
                                  !adev->primary_output->standby) {
                        out_device = adev->primary_output->devices;
                    } else {
                        /* forcing speaker o/p device to get matching i/p pair
                           in case o/p is not routed from same primary HAL */
                        out_device = AUDIO_DEVICE_OUT_SPEAKER;
                    }
                    priority_in = voip_in;
                } else {
                    /* get the input with the highest priority source*/
                    priority_in = get_priority_input(adev);

                    if (!priority_in)
                        priority_in = usecase->stream.in;
                }

                in_snd_device = platform_get_input_snd_device(adev->platform,
                                                              priority_in,
                                                              out_device);
            }
        }
    }

    if (out_snd_device == usecase->out_snd_device &&
        in_snd_device == usecase->in_snd_device) {

        if (!force_device_switch(usecase))
            return 0;
    }

    if ((is_btsco_device(out_snd_device,in_snd_device) && !adev->bt_sco_on) ||
         (is_a2dp_device(out_snd_device) && !audio_extn_a2dp_source_is_ready())) {
          ALOGD("SCO/A2DP is selected but they are not connected/ready hence dont route");
          return 0;
    }

    if (out_snd_device != SND_DEVICE_NONE &&
            out_snd_device != adev->last_logged_snd_device[uc_id][0]) {
        ALOGD("%s: changing use case %s output device from(%d: %s, acdb %d) to (%d: %s, acdb %d)",
              __func__,
              use_case_table[uc_id],
              adev->last_logged_snd_device[uc_id][0],
              platform_get_snd_device_name(adev->last_logged_snd_device[uc_id][0]),
              adev->last_logged_snd_device[uc_id][0] != SND_DEVICE_NONE ?
                      platform_get_snd_device_acdb_id(adev->last_logged_snd_device[uc_id][0]) :
                      -1,
              out_snd_device,
              platform_get_snd_device_name(out_snd_device),
              platform_get_snd_device_acdb_id(out_snd_device));
        adev->last_logged_snd_device[uc_id][0] = out_snd_device;
    }
    if (in_snd_device != SND_DEVICE_NONE &&
            in_snd_device != adev->last_logged_snd_device[uc_id][1]) {
        ALOGD("%s: changing use case %s input device from(%d: %s, acdb %d) to (%d: %s, acdb %d)",
              __func__,
              use_case_table[uc_id],
              adev->last_logged_snd_device[uc_id][1],
              platform_get_snd_device_name(adev->last_logged_snd_device[uc_id][1]),
              adev->last_logged_snd_device[uc_id][1] != SND_DEVICE_NONE ?
                      platform_get_snd_device_acdb_id(adev->last_logged_snd_device[uc_id][1]) :
                      -1,
              in_snd_device,
              platform_get_snd_device_name(in_snd_device),
              platform_get_snd_device_acdb_id(in_snd_device));
        adev->last_logged_snd_device[uc_id][1] = in_snd_device;
    }


    /*
     * Limitation: While in call, to do a device switch we need to disable
     * and enable both RX and TX devices though one of them is same as current
     * device.
     */
    if ((usecase->type == VOICE_CALL) &&
        (usecase->in_snd_device != SND_DEVICE_NONE) &&
        (usecase->out_snd_device != SND_DEVICE_NONE)) {
        status = platform_switch_voice_call_device_pre(adev->platform);
    }

    if (((usecase->type == VOICE_CALL) ||
         (usecase->type == VOIP_CALL)) &&
        (usecase->out_snd_device != SND_DEVICE_NONE)) {
        /* Disable sidetone only if voice/voip call already exists */
        if (voice_is_call_state_active(adev) ||
            voice_extn_compress_voip_is_started(adev))
            voice_set_sidetone(adev, usecase->out_snd_device, false);

        /* Disable aanc only if voice call exists */
        if (voice_is_call_state_active(adev))
            voice_check_and_update_aanc_path(adev, usecase->out_snd_device, false);
    }

    if ((out_snd_device == SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP ||
         out_snd_device == SND_DEVICE_OUT_SPEAKER_SAFE_AND_BT_A2DP) &&
        (!audio_extn_a2dp_source_is_ready())) {
        ALOGW("%s: A2DP profile is not ready, routing to speaker only", __func__);
        if (out_snd_device == SND_DEVICE_OUT_SPEAKER_SAFE_AND_BT_A2DP)
            out_snd_device = SND_DEVICE_OUT_SPEAKER_SAFE;
        else
            out_snd_device = SND_DEVICE_OUT_SPEAKER;
    }

    /* Disable current sound devices */
    if (usecase->out_snd_device != SND_DEVICE_NONE) {
        disable_audio_route(adev, usecase);
        disable_snd_device(adev, usecase->out_snd_device);
    }

    if (usecase->in_snd_device != SND_DEVICE_NONE) {
        disable_audio_route(adev, usecase);
        disable_snd_device(adev, usecase->in_snd_device);
    }

    /* Applicable only on the targets that has external modem.
     * New device information should be sent to modem before enabling
     * the devices to reduce in-call device switch time.
     */
    if ((usecase->type == VOICE_CALL) &&
        (usecase->in_snd_device != SND_DEVICE_NONE) &&
        (usecase->out_snd_device != SND_DEVICE_NONE)) {
        status = platform_switch_voice_call_enable_device_config(adev->platform,
                                                                 out_snd_device,
                                                                 in_snd_device);
    }

    /* Enable new sound devices */
    if (out_snd_device != SND_DEVICE_NONE) {
        check_usecases_codec_backend(adev, usecase, out_snd_device);
        if (platform_check_codec_asrc_support(adev->platform))
            check_and_set_asrc_mode(adev, usecase, out_snd_device);
        enable_snd_device(adev, out_snd_device);
    }

    if (in_snd_device != SND_DEVICE_NONE) {
        check_usecases_capture_codec_backend(adev, usecase, in_snd_device);
        enable_snd_device(adev, in_snd_device);
    }

    if (usecase->type == VOICE_CALL || usecase->type == VOIP_CALL) {
        status = platform_switch_voice_call_device_post(adev->platform,
                                                        out_snd_device,
                                                        in_snd_device);
        enable_audio_route_for_voice_usecases(adev, usecase);
    }

    usecase->in_snd_device = in_snd_device;
    usecase->out_snd_device = out_snd_device;

    audio_extn_utils_update_stream_app_type_cfg_for_usecase(adev,
                                                            usecase);
    if (usecase->type == PCM_PLAYBACK) {
        if ((24 == usecase->stream.out->bit_width) &&
                (usecase->stream.out->devices & AUDIO_DEVICE_OUT_SPEAKER)) {
            usecase->stream.out->app_type_cfg.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
        } else if ((out_snd_device == SND_DEVICE_OUT_HDMI ||
                    out_snd_device == SND_DEVICE_OUT_USB_HEADSET ||
                    out_snd_device == SND_DEVICE_OUT_DISPLAY_PORT) &&
                   (usecase->stream.out->sample_rate >= OUTPUT_SAMPLING_RATE_44100)) {
            /*
             * To best utlize DSP, check if the stream sample rate is supported/multiple of
             * configured device sample rate, if not update the COPP rate to be equal to the
             * device sample rate, else open COPP at stream sample rate
             */
            platform_check_and_update_copp_sample_rate(adev->platform, out_snd_device,
                    usecase->stream.out->sample_rate,
                    &usecase->stream.out->app_type_cfg.sample_rate);
        } else if (((out_snd_device != SND_DEVICE_OUT_HEADPHONES_44_1 &&
                     !audio_is_true_native_stream_active(adev)) &&
                    usecase->stream.out->sample_rate == OUTPUT_SAMPLING_RATE_44100) ||
                    (usecase->stream.out->sample_rate < OUTPUT_SAMPLING_RATE_44100)) {
            usecase->stream.out->app_type_cfg.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
        }
    }
    enable_audio_route(adev, usecase);

    audio_extn_qdsp_set_device(usecase);

    /* If input stream is already running then effect needs to be
       applied on the new input device that's being enabled here.  */
    if (in_snd_device != SND_DEVICE_NONE)
        check_and_enable_effect(adev);

    if (usecase->type == VOICE_CALL || usecase->type == VOIP_CALL) {
        /* Enable aanc only if voice call exists */
        if (voice_is_call_state_active(adev))
            voice_check_and_update_aanc_path(adev, out_snd_device, true);

        /* Enable sidetone only if other voice/voip call already exists */
        if (voice_is_call_state_active(adev) ||
            voice_extn_compress_voip_is_started(adev))
            voice_set_sidetone(adev, out_snd_device, true);
    }

    /* Applicable only on the targets that has external modem.
     * Enable device command should be sent to modem only after
     * enabling voice call mixer controls
     */
    if (usecase->type == VOICE_CALL)
        status = platform_switch_voice_call_usecase_route_post(adev->platform,
                                                               out_snd_device,
                                                               in_snd_device);

    if (is_btsco_device(out_snd_device, in_snd_device) || is_a2dp_device(out_snd_device)) {
         struct stream_in *in = adev_get_active_input(adev);
         if (usecase->type == VOIP_CALL) {
             if (in != NULL && !in->standby) {
                 if (is_bt_soc_on(adev) == false){
                      ALOGD("BT SCO MIC disconnected while in connection");
                      if (in->pcm != NULL)
                          pcm_stop(in->pcm);
                 }
             }
             if ((usecase->stream.out != NULL) && (usecase->stream.out != adev->primary_output)
                  && usecase->stream.out->started) {
                  if (is_bt_soc_on(adev) == false) {
                      ALOGD("BT SCO/A2DP disconnected while in connection");
                      out_standby_l(&usecase->stream.out->stream.common);
                  }
             }
         } else if ((usecase->stream.out != NULL) &&
              !(usecase->stream.out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
              (usecase->type != TRANSCODE_LOOPBACK_TX) &&
              (usecase->type != TRANSCODE_LOOPBACK_RX) &&
              usecase->stream.out->started) {
              if (is_bt_soc_on(adev) == false) {
                  ALOGD("BT SCO/A2dp disconnected while in connection");
                  out_standby_l(&usecase->stream.out->stream.common);
              }
         }
    }

    if (usecase->type != PCM_CAPTURE && usecase == voip_usecase) {
        struct stream_out *voip_out = voip_usecase->stream.out;
        audio_extn_utils_send_app_type_gain(adev,
                                            voip_out->app_type_cfg.app_type,
                                            &voip_out->app_type_cfg.gain[0]);
    }

    ALOGD("%s: done",__func__);

    return status;
}

static int stop_input_stream(struct stream_in *in)
{
    int ret = 0;
    struct audio_usecase *uc_info;

    if (in == NULL) {
        ALOGE("%s: stream_in ptr is NULL", __func__);
        return -EINVAL;
    }

    struct audio_device *adev = in->dev;
    struct stream_in *priority_in = NULL;

    ALOGV("%s: enter: usecase(%d: %s)", __func__,
          in->usecase, use_case_table[in->usecase]);
    uc_info = get_usecase_from_list(adev, in->usecase);
    if (uc_info == NULL) {
        ALOGE("%s: Could not find the usecase (%d) in the list",
              __func__, in->usecase);
        return -EINVAL;
    }

    priority_in = get_priority_input(adev);

    if (audio_extn_ext_hw_plugin_usecase_stop(adev->ext_hw_plugin, uc_info))
        ALOGE("%s: failed to stop ext hw plugin", __func__);

    /* Close in-call recording streams */
    voice_check_and_stop_incall_rec_usecase(adev, in);

    /* 1. Disable stream specific mixer controls */
    disable_audio_route(adev, uc_info);

    /* 2. Disable the tx device */
    disable_snd_device(adev, uc_info->in_snd_device);

    if (is_loopback_input_device(in->device))
        audio_extn_keep_alive_stop(KEEP_ALIVE_OUT_PRIMARY);

    list_remove(&uc_info->list);
    free(uc_info);

    if (priority_in == in) {
        priority_in = get_priority_input(adev);
        if (priority_in)
            select_devices(adev, priority_in->usecase);
    }

    enable_gcov();
    ALOGV("%s: exit: status(%d)", __func__, ret);
    return ret;
}

int start_input_stream(struct stream_in *in)
{
    /* 1. Enable output device and stream routing controls */
    int ret = 0;
    struct audio_usecase *uc_info;

    if (in == NULL) {
        ALOGE("%s: stream_in ptr is NULL", __func__);
        return -EINVAL;
    }

    struct audio_device *adev = in->dev;
    struct pcm_config config = in->config;
    int usecase = platform_update_usecase_from_source(in->source,in->usecase);

    if (get_usecase_from_list(adev, usecase) == NULL)
        in->usecase = usecase;
    ALOGD("%s: enter: stream(%p)usecase(%d: %s)",
          __func__, &in->stream, in->usecase, use_case_table[in->usecase]);

    if (CARD_STATUS_OFFLINE == in->card_status||
        CARD_STATUS_OFFLINE == adev->card_status) {
        ALOGW("in->card_status or adev->card_status offline, try again");
        ret = -EIO;
        goto error_config;
    }

    if (audio_is_bluetooth_sco_device(in->device)) {
        if (!adev->bt_sco_on) {
            ALOGE("%s: SCO profile is not ready, return error", __func__);
            ret = -EIO;
            goto error_config;
        }
    }

    /* Check if source matches incall recording usecase criteria */
    ret = voice_check_and_set_incall_rec_usecase(adev, in);
    if (ret)
        goto error_config;
    else
        ALOGV("%s: usecase(%d)", __func__, in->usecase);

    if (get_usecase_from_list(adev, in->usecase) != NULL) {
        ALOGE("%s: use case assigned already in use, stream(%p)usecase(%d: %s)",
            __func__, &in->stream, in->usecase, use_case_table[in->usecase]);
        return -EINVAL;
    }

    in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
    if (in->pcm_device_id < 0) {
        ALOGE("%s: Could not find PCM device id for the usecase(%d)",
              __func__, in->usecase);
        ret = -EINVAL;
        goto error_config;
    }

    uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));

    if (!uc_info) {
        ret = -ENOMEM;
        goto error_config;
    }

    uc_info->id = in->usecase;
    uc_info->type = PCM_CAPTURE;
    uc_info->stream.in = in;
    uc_info->devices = in->device;
    uc_info->in_snd_device = SND_DEVICE_NONE;
    uc_info->out_snd_device = SND_DEVICE_NONE;

    list_add_tail(&adev->usecase_list, &uc_info->list);
    audio_streaming_hint_start();
    audio_extn_perf_lock_acquire(&adev->perf_lock_handle, 0,
                                 adev->perf_lock_opts,
                                 adev->perf_lock_opts_size);
    select_devices(adev, in->usecase);

    if (audio_extn_ext_hw_plugin_usecase_start(adev->ext_hw_plugin, uc_info))
        ALOGE("%s: failed to start ext hw plugin", __func__);

    android_atomic_acquire_cas(true, false, &(in->capture_stopped));

    if (audio_extn_cin_attached_usecase(in->usecase)) {
       ret = audio_extn_cin_open_input_stream(in);
       if (ret)
           goto error_open;
       else
           goto done_open;
    }

    if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
        if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
            ALOGE("%s: pcm stream not ready", __func__);
            goto error_open;
        }
        ret = pcm_start(in->pcm);
        if (ret < 0) {
            ALOGE("%s: MMAP pcm_start failed ret %d", __func__, ret);
            goto error_open;
        }
    } else {
        unsigned int flags = PCM_IN | PCM_MONOTONIC;
        unsigned int pcm_open_retry_count = 0;

        if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY) {
            flags |= PCM_MMAP | PCM_NOIRQ;
            pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
        } else if (in->realtime) {
            flags |= PCM_MMAP | PCM_NOIRQ;
        }

        if (audio_extn_ffv_get_stream() == in) {
           ALOGD("%s: ffv stream, update pcm config", __func__);
           audio_extn_ffv_update_pcm_config(&config);
        }
        ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
              __func__, adev->snd_card, in->pcm_device_id, in->config.channels);

        while (1) {
            ATRACE_BEGIN("pcm_in_open");
            in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
                               flags, &config);
            ATRACE_END();
            if (errno == ENETRESET && !pcm_is_ready(in->pcm)) {
                ALOGE("%s: pcm_open failed errno:%d\n", __func__, errno);
                adev->card_status = CARD_STATUS_OFFLINE;
                in->card_status = CARD_STATUS_OFFLINE;
                ret = -EIO;
                goto error_open;
            }

            if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
                ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
                if (in->pcm != NULL) {
                    pcm_close(in->pcm);
                    in->pcm = NULL;
                }
                if (pcm_open_retry_count-- == 0) {
                    ret = -EIO;
                    goto error_open;
                }
                usleep(PROXY_OPEN_WAIT_TIME * 1000);
                continue;
            }
            break;
        }

        ALOGV("%s: pcm_prepare", __func__);
        ATRACE_BEGIN("pcm_in_prepare");
        ret = pcm_prepare(in->pcm);
        ATRACE_END();
        if (ret < 0) {
            ALOGE("%s: pcm_prepare returned %d", __func__, ret);
            pcm_close(in->pcm);
            in->pcm = NULL;
            goto error_open;
        }
        register_in_stream(in);
        if (in->realtime) {
            ATRACE_BEGIN("pcm_in_start");
            ret = pcm_start(in->pcm);
            ATRACE_END();
            if (ret < 0) {
                ALOGE("%s: RT pcm_start failed ret %d", __func__, ret);
                pcm_close(in->pcm);
                in->pcm = NULL;
                goto error_open;
            }
        }
    }

    check_and_enable_effect(adev);
    audio_extn_audiozoom_set_microphone_direction(in, in->zoom);
    audio_extn_audiozoom_set_microphone_field_dimension(in, in->direction);

    if (is_loopback_input_device(in->device))
        audio_extn_keep_alive_start(KEEP_ALIVE_OUT_PRIMARY);

done_open:
    audio_streaming_hint_end();
    audio_extn_perf_lock_release(&adev->perf_lock_handle);
    ALOGD("%s: exit", __func__);
    enable_gcov();
    return ret;

error_open:
    audio_streaming_hint_end();
    audio_extn_perf_lock_release(&adev->perf_lock_handle);
    stop_input_stream(in);

error_config:
    /*
     * sleep 50ms to allow sufficient time for kernel
     * drivers to recover incases like SSR.
     */
    usleep(50000);
    ALOGD("%s: exit: status(%d)", __func__, ret);
    enable_gcov();
    return ret;
}

void lock_input_stream(struct stream_in *in)
{
    pthread_mutex_lock(&in->pre_lock);
    pthread_mutex_lock(&in->lock);
    pthread_mutex_unlock(&in->pre_lock);
}

void lock_output_stream(struct stream_out *out)
{
    pthread_mutex_lock(&out->pre_lock);
    pthread_mutex_lock(&out->lock);
    pthread_mutex_unlock(&out->pre_lock);
}

/* must be called with out->lock locked */
static int send_offload_cmd_l(struct stream_out* out, int command)
{
    struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));

    if (!cmd) {
        ALOGE("failed to allocate mem for command 0x%x", command);
        return -ENOMEM;
    }

    ALOGVV("%s %d", __func__, command);

    cmd->cmd = command;
    list_add_tail(&out->offload_cmd_list, &cmd->node);
    pthread_cond_signal(&out->offload_cond);
    return 0;
}

/* must be called iwth out->lock locked */
static void stop_compressed_output_l(struct stream_out *out)
{
    out->offload_state = OFFLOAD_STATE_IDLE;
    out->playback_started = 0;
    out->send_new_metadata = 1;
    if (out->compr != NULL) {
        compress_stop(out->compr);
        while (out->offload_thread_blocked) {
            pthread_cond_wait(&out->cond, &out->lock);
        }
    }
}

bool is_interactive_usecase(audio_usecase_t uc_id)
{
    unsigned int i;
    for (i = 0; i < sizeof(interactive_usecases)/sizeof(interactive_usecases[0]); i++) {
        if (uc_id == interactive_usecases[i])
            return true;
    }
    return false;
}

static audio_usecase_t get_interactive_usecase(struct audio_device *adev)
{
    audio_usecase_t ret_uc = USECASE_INVALID;
    unsigned int intract_uc_index;
    unsigned int num_usecase = sizeof(interactive_usecases)/sizeof(interactive_usecases[0]);

    ALOGV("%s: num_usecase: %d", __func__, num_usecase);
    for (intract_uc_index = 0; intract_uc_index < num_usecase; intract_uc_index++) {
        if (!(adev->interactive_usecase_state & (0x1 << intract_uc_index))) {
            adev->interactive_usecase_state |= 0x1 << intract_uc_index;
            ret_uc = interactive_usecases[intract_uc_index];
            break;
        }
    }

    ALOGV("%s: Interactive usecase is %d", __func__, ret_uc);
    return ret_uc;
}

static void free_interactive_usecase(struct audio_device *adev,
                                 audio_usecase_t uc_id)
{
    unsigned int interact_uc_index;
    unsigned int num_usecase = sizeof(interactive_usecases)/sizeof(interactive_usecases[0]);

    for (interact_uc_index = 0; interact_uc_index < num_usecase; interact_uc_index++) {
        if (interactive_usecases[interact_uc_index] == uc_id) {
            adev->interactive_usecase_state &= ~(0x1 << interact_uc_index);
            break;
        }
    }
    ALOGV("%s: free Interactive usecase %d", __func__, uc_id);
}

bool is_offload_usecase(audio_usecase_t uc_id)
{
    unsigned int i;
    for (i = 0; i < sizeof(offload_usecases)/sizeof(offload_usecases[0]); i++) {
        if (uc_id == offload_usecases[i])
            return true;
    }
    return false;
}

static audio_usecase_t get_offload_usecase(struct audio_device *adev, bool is_compress)
{
    audio_usecase_t ret_uc = USECASE_INVALID;
    unsigned int offload_uc_index;
    unsigned int num_usecase = sizeof(offload_usecases)/sizeof(offload_usecases[0]);
    if (!adev->multi_offload_enable) {
        if (!is_compress)
            ret_uc = USECASE_AUDIO_PLAYBACK_OFFLOAD2;
        else
            ret_uc = USECASE_AUDIO_PLAYBACK_OFFLOAD;

        pthread_mutex_lock(&adev->lock);
        if (get_usecase_from_list(adev, ret_uc) != NULL)
           ret_uc = USECASE_INVALID;
        pthread_mutex_unlock(&adev->lock);

        return ret_uc;
    }

    ALOGV("%s: num_usecase: %d", __func__, num_usecase);
    for (offload_uc_index = 0; offload_uc_index < num_usecase; offload_uc_index++) {
        if (!(adev->offload_usecases_state & (0x1 << offload_uc_index))) {
            adev->offload_usecases_state |= 0x1 << offload_uc_index;
            ret_uc = offload_usecases[offload_uc_index];
            break;
        }
    }

    ALOGV("%s: offload usecase is %d", __func__, ret_uc);
    return ret_uc;
}

static void free_offload_usecase(struct audio_device *adev,
                                 audio_usecase_t uc_id)
{
    unsigned int offload_uc_index;
    unsigned int num_usecase = sizeof(offload_usecases)/sizeof(offload_usecases[0]);

    if (!adev->multi_offload_enable)
        return;

    for (offload_uc_index = 0; offload_uc_index < num_usecase; offload_uc_index++) {
        if (offload_usecases[offload_uc_index] == uc_id) {
            adev->offload_usecases_state &= ~(0x1 << offload_uc_index);
            break;
        }
    }
    ALOGV("%s: free offload usecase %d", __func__, uc_id);
}

static void *offload_thread_loop(void *context)
{
    struct stream_out *out = (struct stream_out *) context;
    struct listnode *item;
    int ret = 0;

    setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
    //set_sched_policy(0, SP_FOREGROUND);
    prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);

    ALOGV("%s", __func__);
    lock_output_stream(out);
    out->offload_state = OFFLOAD_STATE_IDLE;
    out->playback_started = 0;
    for (;;) {
        struct offload_cmd *cmd = NULL;
        stream_callback_event_t event;
        bool send_callback = false;

        ALOGVV("%s offload_cmd_list %d out->offload_state %d",
              __func__, list_empty(&out->offload_cmd_list),
              out->offload_state);
        if (list_empty(&out->offload_cmd_list)) {
            ALOGV("%s SLEEPING", __func__);
            pthread_cond_wait(&out->offload_cond, &out->lock);
            ALOGV("%s RUNNING", __func__);
            continue;
        }

        item = list_head(&out->offload_cmd_list);
        cmd = node_to_item(item, struct offload_cmd, node);
        list_remove(item);

        ALOGVV("%s STATE %d CMD %d out->compr %p",
               __func__, out->offload_state, cmd->cmd, out->compr);

        if (cmd->cmd == OFFLOAD_CMD_EXIT) {
            free(cmd);
            break;
        }

        // allow OFFLOAD_CMD_ERROR reporting during standby
        // this is needed to handle failures during compress_open
        // Note however that on a pause timeout, the stream is closed
        // and no offload usecase will be active. Therefore this
        // special case is needed for compress_open failures alone
        if (cmd->cmd != OFFLOAD_CMD_ERROR &&
            out->compr == NULL) {
            ALOGE("%s: Compress handle is NULL", __func__);
            free(cmd);
            pthread_cond_signal(&out->cond);
            continue;
        }
        out->offload_thread_blocked = true;
        pthread_mutex_unlock(&out->lock);
        send_callback = false;
        switch(cmd->cmd) {
        case OFFLOAD_CMD_WAIT_FOR_BUFFER:
            ALOGD("copl(%p):calling compress_wait", out);
            compress_wait(out->compr, -1);
            ALOGD("copl(%p):out of compress_wait", out);
            send_callback = true;
            event = STREAM_CBK_EVENT_WRITE_READY;
            break;
        case OFFLOAD_CMD_PARTIAL_DRAIN:
            ret = compress_next_track(out->compr);
            if(ret == 0) {
                ALOGD("copl(%p):calling compress_partial_drain", out);
                ret = compress_partial_drain(out->compr);
                ALOGD("copl(%p):out of compress_partial_drain", out);
                if (ret < 0)
                    ret = -errno;
            }
            else if (ret == -ETIMEDOUT)
                ret = compress_drain(out->compr);
            else
                ALOGE("%s: Next track returned error %d",__func__, ret);
            if (-ENETRESET != ret && !(-EINTR == ret &&
                        CARD_STATUS_OFFLINE == out->card_status)) {
                send_callback = true;
                pthread_mutex_lock(&out->lock);
                out->send_new_metadata = 1;
                out->send_next_track_params = true;
                pthread_mutex_unlock(&out->lock);
                event = STREAM_CBK_EVENT_DRAIN_READY;
                ALOGV("copl(%p):send drain callback, ret %d", out, ret);
            } else
                ALOGI("%s: Block drain ready event during SSR", __func__);
            break;
        case OFFLOAD_CMD_DRAIN:
            ALOGD("copl(%p):calling compress_drain", out);
            ret = compress_drain(out->compr);
            ALOGD("copl(%p):out of compress_drain", out);
            // EINTR check avoids drain interruption due to SSR
            if (-ENETRESET != ret && !(-EINTR == ret &&
                        CARD_STATUS_OFFLINE == out->card_status)) {
                send_callback = true;
                event = STREAM_CBK_EVENT_DRAIN_READY;
            } else
                ALOGI("%s: Block drain ready event during SSR", __func__);
            break;
        case OFFLOAD_CMD_ERROR:
            ALOGD("copl(%p): sending error callback to AF", out);
            send_callback = true;
            event = STREAM_CBK_EVENT_ERROR;
            break;
        default:
            ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
            break;
        }
        lock_output_stream(out);
        out->offload_thread_blocked = false;
        pthread_cond_signal(&out->cond);
        if (send_callback && out->client_callback) {
            ALOGVV("%s: sending client_callback event %d", __func__, event);
            out->client_callback(event, NULL, out->client_cookie);
        }
        free(cmd);
    }

    pthread_cond_signal(&out->cond);
    while (!list_empty(&out->offload_cmd_list)) {
        item = list_head(&out->offload_cmd_list);
        list_remove(item);
        free(node_to_item(item, struct offload_cmd, node));
    }
    pthread_mutex_unlock(&out->lock);

    return NULL;
}

static int create_offload_callback_thread(struct stream_out *out)
{
    pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
    list_init(&out->offload_cmd_list);
    pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
                    offload_thread_loop, out);
    return 0;
}

static int destroy_offload_callback_thread(struct stream_out *out)
{
    lock_output_stream(out);
    stop_compressed_output_l(out);
    send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);

    pthread_mutex_unlock(&out->lock);
    pthread_join(out->offload_thread, (void **) NULL);
    pthread_cond_destroy(&out->offload_cond);

    return 0;
}

static int stop_output_stream(struct stream_out *out)
{
    int ret = 0;
    struct audio_usecase *uc_info;
    struct audio_device *adev = out->dev;
    bool has_voip_usecase =
        get_usecase_from_list(adev, USECASE_AUDIO_PLAYBACK_VOIP) != NULL;

    ALOGV("%s: enter: usecase(%d: %s)", __func__,
          out->usecase, use_case_table[out->usecase]);
    uc_info = get_usecase_from_list(adev, out->usecase);
    if (uc_info == NULL) {
        ALOGE("%s: Could not find the usecase (%d) in the list",
              __func__, out->usecase);
        return -EINVAL;
    }

    if (audio_extn_ext_hw_plugin_usecase_stop(adev->ext_hw_plugin, uc_info))
        ALOGE("%s: failed to stop ext hw plugin", __func__);

    if (is_offload_usecase(out->usecase) &&
        !(audio_extn_passthru_is_passthrough_stream(out))) {
        if (adev->visualizer_stop_output != NULL)
            adev->visualizer_stop_output(out->handle, out->pcm_device_id);

        audio_extn_dts_remove_state_notifier_node(out->usecase);

        if (adev->offload_effects_stop_output != NULL)
            adev->offload_effects_stop_output(out->handle, out->pcm_device_id);
    } else if (out->usecase == USECASE_AUDIO_PLAYBACK_ULL ||
               out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
        audio_low_latency_hint_end();
    }

    if (out->usecase == USECASE_INCALL_MUSIC_UPLINK ||
        out->usecase == USECASE_INCALL_MUSIC_UPLINK2) {
        voice_set_device_mute_flag(adev, false);
    }

    /* 1. Get and set stream specific mixer controls */
    disable_audio_route(adev, uc_info);

    /* 2. Disable the rx device */
    disable_snd_device(adev, uc_info->out_snd_device);

    audio_extn_extspk_update(adev->extspk);

    if (is_offload_usecase(out->usecase)) {
        audio_enable_asm_bit_width_enforce_mode(adev->mixer,
                                                adev->dsp_bit_width_enforce_mode,
                                                false);
    }
    if (audio_is_usb_out_device(out->devices & AUDIO_DEVICE_OUT_ALL_USB)) {
        ret = audio_extn_usb_check_and_set_svc_int(uc_info,
                                                   false);

        if (ret != 0)
            check_usecases_codec_backend(adev, uc_info, uc_info->out_snd_device);
            /* default service interval was successfully updated,
            reopen USB backend with new service interval */
        ret = 0;
    }

    list_remove(&uc_info->list);
    out->started = 0;
    if (is_offload_usecase(out->usecase) &&
        (audio_extn_passthru_is_passthrough_stream(out))) {
        ALOGV("Disable passthrough , reset mixer to pcm");
        /* NO_PASSTHROUGH */
        out->compr_config.codec->compr_passthr = 0;
        audio_extn_passthru_on_stop(out);
        audio_extn_dolby_set_dap_bypass(adev, DAP_STATE_ON);
    }

    /* Must be called after removing the usecase from list */
    if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
        audio_extn_keep_alive_start(KEEP_ALIVE_OUT_HDMI);

    if (out->ip_hdlr_handle) {
        ret = audio_extn_ip_hdlr_intf_close(out->ip_hdlr_handle, true, out);
        if (ret < 0)
            ALOGE("%s: audio_extn_ip_hdlr_intf_close failed %d",__func__, ret);
    }

    /* 1) media + voip output routing to handset must route media back to
          speaker when voip stops.
       2) trigger voip input to reroute when voip output changes to
          hearing aid. */
    if (has_voip_usecase ||
            out->devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
        struct listnode *node;
        struct audio_usecase *usecase;
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            if ((usecase->type == PCM_CAPTURE &&
                     usecase->id != USECASE_AUDIO_RECORD_VOIP)
                || usecase == uc_info)
                continue;

            ALOGD("%s: select_devices at usecase(%d: %s) after removing the usecase(%d: %s)",
                __func__, usecase->id, use_case_table[usecase->id],
                out->usecase, use_case_table[out->usecase]);
            select_devices(adev, usecase->id);
        }
    }

    free(uc_info);
    ALOGV("%s: exit: status(%d)", __func__, ret);
    return ret;
}

struct pcm* pcm_open_prepare_helper(unsigned int snd_card, unsigned int pcm_device_id,
                                   unsigned int flags, unsigned int pcm_open_retry_count,
                                   struct pcm_config *config)
{
    struct pcm* pcm = NULL;

    while (1) {
        pcm = pcm_open(snd_card, pcm_device_id, flags, config);
        if (pcm == NULL || !pcm_is_ready(pcm)) {
            ALOGE("%s: %s", __func__, pcm_get_error(pcm));
            if (pcm != NULL) {
                pcm_close(pcm);
                pcm = NULL;
            }
            if (pcm_open_retry_count-- == 0)
                return NULL;

            usleep(PROXY_OPEN_WAIT_TIME * 1000);
            continue;
        }
        break;
    }

    if (pcm_is_ready(pcm)) {
        int ret = pcm_prepare(pcm);
        if (ret < 0) {
            ALOGE("%s: pcm_prepare returned %d", __func__, ret);
            pcm_close(pcm);
            pcm = NULL;
        }
    }

    return pcm;
}

int start_output_stream(struct stream_out *out)
{
    int ret = 0;
    struct audio_usecase *uc_info;
    struct audio_device *adev = out->dev;
    char mixer_ctl_name[128];
    struct mixer_ctl *ctl = NULL;
    char* perf_mode[] = {"ULL", "ULL_PP", "LL"};
    bool a2dp_combo = false;
    bool is_haptic_usecase = (out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS) ? true: false;

    ATRACE_BEGIN("start_output_stream");
    if ((out->usecase < 0) || (out->usecase >= AUDIO_USECASE_MAX)) {
        ret = -EINVAL;
        goto error_config;
    }

    ALOGD("%s: enter: stream(%p)usecase(%d: %s) devices(%#x) is_haptic_usecase(%d)",
          __func__, &out->stream, out->usecase, use_case_table[out->usecase],
          out->devices, is_haptic_usecase);

    if (CARD_STATUS_OFFLINE == out->card_status ||
        CARD_STATUS_OFFLINE == adev->card_status) {
        ALOGW("out->card_status or adev->card_status offline, try again");
        ret = -EIO;
        goto error_config;
    }

    //Update incall music usecase to reflect correct voice session
    if (out->flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) {
        ret = voice_extn_check_and_set_incall_music_usecase(adev, out);
        if (ret != 0) {
            ALOGE("%s: Incall music delivery usecase cannot be set error:%d",
                __func__, ret);
            goto error_config;
        }
    }

    if (out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) {
        if (!audio_extn_a2dp_source_is_ready()) {
            if (out->devices &
                (AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
                a2dp_combo = true;
            } else {
                if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
                    ALOGE("%s: A2DP profile is not ready, return error", __func__);
                    ret = -EAGAIN;
                    goto error_config;
                }
            }
        }
    }
    if (out->devices & AUDIO_DEVICE_OUT_ALL_SCO) {
        if (!adev->bt_sco_on) {
            if (out->devices & AUDIO_DEVICE_OUT_SPEAKER) {
                //combo usecase just by pass a2dp
                ALOGW("%s: SCO is not connected, route it to speaker", __func__);
                out->devices = AUDIO_DEVICE_OUT_SPEAKER;
            } else {
                ALOGE("%s: SCO profile is not ready, return error", __func__);
                ret = -EAGAIN;
                goto error_config;
            }
        }
    }

    out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
    if (out->pcm_device_id < 0) {
        ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
              __func__, out->pcm_device_id, out->usecase);
        ret = -EINVAL;
        goto error_open;
    }

    if (is_haptic_usecase) {
        adev->haptic_pcm_device_id = platform_get_haptics_pcm_device_id();
        if (adev->haptic_pcm_device_id < 0) {
            ALOGE("%s: Invalid Haptics pcm device id(%d) for the usecase(%d)",
                  __func__, adev->haptic_pcm_device_id, out->usecase);
            ret = -EINVAL;
            goto error_config;
        }
    }

    uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));

    if (!uc_info) {
        ret = -ENOMEM;
        goto error_config;
    }

    uc_info->id = out->usecase;
    uc_info->type = PCM_PLAYBACK;
    uc_info->stream.out = out;
    uc_info->devices = out->devices;
    uc_info->in_snd_device = SND_DEVICE_NONE;
    uc_info->out_snd_device = SND_DEVICE_NONE;

    /* This must be called before adding this usecase to the list */
    if (audio_is_usb_out_device(out->devices & AUDIO_DEVICE_OUT_ALL_USB)) {
       audio_extn_usb_check_and_set_svc_int(uc_info, true);
       /* USB backend is not reopened immediately.
       This is eventually done as part of select_devices */
    }

    list_add_tail(&adev->usecase_list, &uc_info->list);

    audio_streaming_hint_start();
    audio_extn_perf_lock_acquire(&adev->perf_lock_handle, 0,
                                 adev->perf_lock_opts,
                                 adev->perf_lock_opts_size);

    if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
        audio_extn_keep_alive_stop(KEEP_ALIVE_OUT_HDMI);
        if (audio_extn_passthru_is_enabled() &&
            audio_extn_passthru_is_passthrough_stream(out)) {
            audio_extn_passthru_on_start(out);
        }
    }

    if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
        (!audio_extn_a2dp_source_is_ready())) {
        if (!a2dp_combo) {
            check_a2dp_restore_l(adev, out, false);
        } else {
            audio_devices_t dev = out->devices;
            if (dev & AUDIO_DEVICE_OUT_SPEAKER_SAFE)
                out->devices = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
            else
                out->devices = AUDIO_DEVICE_OUT_SPEAKER;
            select_devices(adev, out->usecase);
            out->devices = dev;
        }
    } else {
         select_devices(adev, out->usecase);
    }

    if (out->usecase == USECASE_INCALL_MUSIC_UPLINK ||
        out->usecase == USECASE_INCALL_MUSIC_UPLINK2) {
        voice_set_device_mute_flag(adev, true);
    }

    if (audio_extn_ext_hw_plugin_usecase_start(adev->ext_hw_plugin, uc_info))
        ALOGE("%s: failed to start ext hw plugin", __func__);

    ALOGV("%s: Opening PCM device card_id(%d) device_id(%d) format(%#x)",
          __func__, adev->snd_card, out->pcm_device_id, out->config.format);

    if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
        ALOGD("%s: Starting MMAP stream", __func__);
        if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
            ALOGE("%s: pcm stream not ready", __func__);
            goto error_open;
        }
        ret = pcm_start(out->pcm);
        if (ret < 0) {
            ALOGE("%s: MMAP pcm_start failed ret %d", __func__, ret);
            goto error_open;
        }
        out_set_mmap_volume(&out->stream, out->volume_l, out->volume_r);
    } else if (!is_offload_usecase(out->usecase)) {
        unsigned int flags = PCM_OUT;
        unsigned int pcm_open_retry_count = 0;
        if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY) {
            flags |= PCM_MMAP | PCM_NOIRQ;
            pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
        } else if (out->realtime) {
            flags |= PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC;
        } else
            flags |= PCM_MONOTONIC;

        if ((adev->vr_audio_mode_enabled) &&
            (out->flags & AUDIO_OUTPUT_FLAG_RAW)) {
            snprintf(mixer_ctl_name, sizeof(mixer_ctl_name),
                    "PCM_Dev %d Topology", out->pcm_device_id);
            ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
            if (!ctl) {
                ALOGI("%s: Could not get ctl for mixer cmd might be ULL - %s",
                      __func__, mixer_ctl_name);
            } else {
                //if success use ULLPP
                ALOGI("%s: mixer ctrl %s succeeded setting up ULL for %d",
                    __func__, mixer_ctl_name, out->pcm_device_id);
                //There is a still a possibility that some sessions
                // that request for FAST|RAW when 3D audio is active
                //can go through ULLPP. Ideally we expects apps to
                //listen to audio focus and stop concurrent playback
                //Also, we will look for mode flag (voice_in_communication)
                //before enabling the realtime flag.
                mixer_ctl_set_enum_by_string(ctl, perf_mode[1]);
            }
        }

        if (out->realtime)
            platform_set_stream_channel_map(adev->platform, out->channel_mask,
                   out->pcm_device_id, &out->channel_map_param.channel_map[0]);

        out->pcm = pcm_open_prepare_helper(adev->snd_card, out->pcm_device_id,
                                       flags, pcm_open_retry_count,
                                       &(out->config));
        if (out->pcm == NULL) {
           ret = -EIO;
           goto error_open;
        }

        if (is_haptic_usecase) {
            adev->haptic_pcm = pcm_open_prepare_helper(adev->snd_card,
                                   adev->haptic_pcm_device_id,
                                   flags, pcm_open_retry_count,
                                   &(adev->haptics_config));
            // failure to open haptics pcm shouldnt stop audio,
            // so do not close audio pcm in case of error

            if (property_get_bool("vendor.audio.enable_haptic_audio_sync", false)) {
                ALOGD("%s: enable haptic audio synchronization", __func__);
                platform_set_qtime(adev->platform, out->pcm_device_id, adev->haptic_pcm_device_id);
            }
        }

        if (!out->realtime)
            platform_set_stream_channel_map(adev->platform, out->channel_mask,
                   out->pcm_device_id, &out->channel_map_param.channel_map[0]);

        // apply volume for voip playback after path is set up
        if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP)
            out_set_voip_volume(&out->stream, out->volume_l, out->volume_r);
        else if ((out->usecase == USECASE_AUDIO_PLAYBACK_LOW_LATENCY || out->usecase == USECASE_AUDIO_PLAYBACK_DEEP_BUFFER ||
                  out->usecase == USECASE_AUDIO_PLAYBACK_ULL) && (out->apply_volume)) {
                 out_set_pcm_volume(&out->stream, out->volume_l, out->volume_r);
                 out->apply_volume = false;
        } else if (audio_extn_auto_hal_is_bus_device_usecase(out->usecase)) {
            out_set_pcm_volume(&out->stream, out->volume_l, out->volume_r);
        }
    } else {
        platform_set_stream_channel_map(adev->platform, out->channel_mask,
                   out->pcm_device_id, &out->channel_map_param.channel_map[0]);
        audio_enable_asm_bit_width_enforce_mode(adev->mixer,
                                                adev->dsp_bit_width_enforce_mode,
                                                true);
        out->pcm = NULL;
        ATRACE_BEGIN("compress_open");
        out->compr = compress_open(adev->snd_card,
                                   out->pcm_device_id,
                                   COMPRESS_IN, &out->compr_config);
        ATRACE_END();
        if (errno == ENETRESET && !is_compress_ready(out->compr)) {
                ALOGE("%s: compress_open failed errno:%d\n", __func__, errno);
                adev->card_status = CARD_STATUS_OFFLINE;
                out->card_status = CARD_STATUS_OFFLINE;
                ret = -EIO;
                goto error_open;
        }

        if (out->compr && !is_compress_ready(out->compr)) {
            ALOGE("%s: failed /w error %s", __func__, compress_get_error(out->compr));
            compress_close(out->compr);
            out->compr = NULL;
            ret = -EIO;
            goto error_open;
        }
        /* compress_open sends params of the track, so reset the flag here */
        out->is_compr_metadata_avail = false;

        if (out->client_callback)
            compress_nonblock(out->compr, out->non_blocking);

        /* Since small bufs uses blocking writes, a write will be blocked
           for the default max poll time (20s) in the event of an SSR.
           Reduce the poll time to observe and deal with SSR faster.
        */
        if (!out->non_blocking) {
            compress_set_max_poll_wait(out->compr, 1000);
        }

        audio_extn_utils_compress_set_render_mode(out);
        audio_extn_utils_compress_set_clk_rec_mode(uc_info);

        audio_extn_dts_create_state_notifier_node(out->usecase);
        audio_extn_dts_notify_playback_state(out->usecase, 0, out->sample_rate,
                                             popcount(out->channel_mask),
                                             out->playback_started);

#ifdef DS1_DOLBY_DDP_ENABLED
        if (audio_extn_utils_is_dolby_format(out->format))
            audio_extn_dolby_send_ddp_endp_params(adev);
#endif
        if (!(audio_extn_passthru_is_passthrough_stream(out)) &&
                (out->sample_rate != 176400 && out->sample_rate <= 192000)) {
            if (adev->visualizer_start_output != NULL)
                adev->visualizer_start_output(out->handle, out->pcm_device_id);
            if (adev->offload_effects_start_output != NULL)
                adev->offload_effects_start_output(out->handle, out->pcm_device_id, adev->mixer);
            audio_extn_check_and_set_dts_hpx_state(adev);
        }

        if (out->devices & AUDIO_DEVICE_OUT_BUS) {
            /* Update cached volume from media to offload/direct stream */
            struct listnode *node = NULL;
            list_for_each(node, &adev->active_outputs_list) {
                streams_output_ctxt_t *out_ctxt = node_to_item(node,
                                                    streams_output_ctxt_t,
                                                    list);
                if (out_ctxt->output->usecase == USECASE_AUDIO_PLAYBACK_MEDIA) {
                    out->volume_l = out_ctxt->output->volume_l;
                    out->volume_r = out_ctxt->output->volume_r;
                }
            }
            out_set_compr_volume(&out->stream,
                                 out->volume_l, out->volume_r);
        }
    }

    if (ret == 0) {
        register_out_stream(out);
        if (out->realtime) {
            if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
                ALOGE("%s: pcm stream not ready", __func__);
                goto error_open;
            }
            ATRACE_BEGIN("pcm_start");
            ret = pcm_start(out->pcm);
            ATRACE_END();
            if (ret < 0)
                goto error_open;
        }
    }
    audio_streaming_hint_end();
    audio_extn_perf_lock_release(&adev->perf_lock_handle);
    ALOGD("%s: exit", __func__);

    if (out->usecase == USECASE_AUDIO_PLAYBACK_ULL ||
        out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
        audio_low_latency_hint_start();
    }

    if (out->ip_hdlr_handle) {
        ret = audio_extn_ip_hdlr_intf_open(out->ip_hdlr_handle, true, out, out->usecase);
        if (ret < 0)
            ALOGE("%s: audio_extn_ip_hdlr_intf_open failed %d",__func__, ret);
    }

    // consider a scenario where on pause lower layers are tear down.
    // so on resume, swap mixer control need to be sent only when
    // backend is active, hence rather than sending from enable device
    // sending it from start of streamtream

    platform_set_swap_channels(adev, true);

    ATRACE_END();
    enable_gcov();
    return ret;
error_open:
    if (adev->haptic_pcm) {
        pcm_close(adev->haptic_pcm);
        adev->haptic_pcm = NULL;
    }
    audio_streaming_hint_end();
    audio_extn_perf_lock_release(&adev->perf_lock_handle);
    stop_output_stream(out);
error_config:
    /*
     * sleep 50ms to allow sufficient time for kernel
     * drivers to recover incases like SSR.
     */
    usleep(50000);
    ATRACE_END();
    enable_gcov();
    return ret;
}

static int check_input_parameters(uint32_t sample_rate,
                                  audio_format_t format,
                                  int channel_count,
                                  bool is_usb_hifi)
{
    int ret = 0;

    if (((format != AUDIO_FORMAT_PCM_16_BIT) && (format != AUDIO_FORMAT_PCM_8_24_BIT) &&
        (format != AUDIO_FORMAT_PCM_24_BIT_PACKED) && (format != AUDIO_FORMAT_PCM_32_BIT) &&
        (format != AUDIO_FORMAT_PCM_FLOAT)) &&
        !voice_extn_compress_voip_is_format_supported(format) &&
        !audio_extn_compr_cap_format_supported(format) &&
        !audio_extn_cin_format_supported(format))
            ret = -EINVAL;

    int max_channel_count = is_usb_hifi ? MAX_HIFI_CHANNEL_COUNT : MAX_CHANNEL_COUNT;
    if ((channel_count < MIN_CHANNEL_COUNT) || (channel_count > max_channel_count)) {
        ALOGE("%s: unsupported channel count (%d) passed  Min / Max (%d / %d)", __func__,
               channel_count, MIN_CHANNEL_COUNT, max_channel_count);
        return -EINVAL;
    }

    switch (channel_count) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 6:
    case 8:
    case 10:
    case 12:
    case 14:
        break;
    default:
        ret = -EINVAL;
    }

    switch (sample_rate) {
    case 8000:
    case 11025:
    case 12000:
    case 16000:
    case 22050:
    case 24000:
    case 32000:
    case 44100:
    case 48000:
    case 88200:
    case 96000:
    case 176400:
    case 192000:
        break;
    default:
        ret = -EINVAL;
    }

    return ret;
}


/** Add a value in a list if not already present.
 * @return true if value was successfully inserted or already present,
 *         false if the list is full and does not contain the value.
 */
static bool register_uint(uint32_t value, uint32_t* list, size_t list_length) {
    for (size_t i = 0; i < list_length; i++) {
        if (list[i] == value) return true; // value is already present
        if (list[i] == 0) { // no values in this slot
            list[i] = value;
            return true; // value inserted
        }
    }
    return false; // could not insert value
}

/** Add channel_mask in supported_channel_masks if not already present.
 * @return true if channel_mask was successfully inserted or already present,
 *         false if supported_channel_masks is full and does not contain channel_mask.
 */
static void register_channel_mask(audio_channel_mask_t channel_mask,
            audio_channel_mask_t supported_channel_masks[static MAX_SUPPORTED_CHANNEL_MASKS]) {
    ALOGE_IF(!register_uint(channel_mask, supported_channel_masks, MAX_SUPPORTED_CHANNEL_MASKS),
        "%s: stream can not declare supporting its channel_mask %x", __func__, channel_mask);
}

/** Add format in supported_formats if not already present.
 * @return true if format was successfully inserted or already present,
 *         false if supported_formats is full and does not contain format.
 */
static void register_format(audio_format_t format,
            audio_format_t supported_formats[static MAX_SUPPORTED_FORMATS]) {
    ALOGE_IF(!register_uint(format, supported_formats, MAX_SUPPORTED_FORMATS),
             "%s: stream can not declare supporting its format %x", __func__, format);
}
/** Add sample_rate in supported_sample_rates if not already present.
 * @return true if sample_rate was successfully inserted or already present,
 *         false if supported_sample_rates is full and does not contain sample_rate.
 */
static void register_sample_rate(uint32_t sample_rate,
            uint32_t supported_sample_rates[static MAX_SUPPORTED_SAMPLE_RATES]) {
    ALOGE_IF(!register_uint(sample_rate, supported_sample_rates, MAX_SUPPORTED_SAMPLE_RATES),
             "%s: stream can not declare supporting its sample rate %x", __func__, sample_rate);
}

static inline uint32_t lcm(uint32_t num1, uint32_t num2)
{
    uint32_t high = num1, low = num2, temp = 0;

    if (!num1 || !num2)
        return 0;

    if (num1 < num2) {
         high = num2;
         low = num1;
    }

    while (low != 0) {
        temp = low;
        low = high % low;
        high = temp;
    }
    return (num1 * num2)/high;
}

static inline uint32_t nearest_multiple(uint32_t num, uint32_t multiplier)
{
    uint32_t remainder = 0;

    if (!multiplier)
        return num;

    remainder = num % multiplier;
    if (remainder)
        num += (multiplier - remainder);

    return num;
}

static size_t get_stream_buffer_size(size_t duration_ms,
                                     uint32_t sample_rate,
                                     audio_format_t format,
                                     int channel_count,
                                     bool is_low_latency)
{
    size_t size = 0;
    uint32_t bytes_per_period_sample = 0;

    size = (sample_rate * duration_ms) / 1000;
    if (is_low_latency)
        size = configured_low_latency_capture_period_size;

    bytes_per_period_sample = audio_bytes_per_sample(format) * channel_count;
    size *= audio_bytes_per_sample(format) * channel_count;

    /* make sure the size is multiple of 32 bytes and additionally multiple of
     * the frame_size (required for 24bit samples and non-power-of-2 channel counts)
     * At 48 kHz mono 16-bit PCM:
     *  5.000 ms = 240 frames = 15*16*1*2 = 480, a whole multiple of 32 (15)
     *  3.333 ms = 160 frames = 10*16*1*2 = 320, a whole multiple of 32 (10)
     * Also, make sure the size is multiple of bytes per period sample
     */
    size = nearest_multiple(size, lcm(32, bytes_per_period_sample));

    return size;
}

static size_t get_input_buffer_size(uint32_t sample_rate,
                                    audio_format_t format,
                                    int channel_count,
                                    bool is_low_latency)
{
    /* Don't know if USB HIFI in this context so use true to be conservative */
    if (check_input_parameters(sample_rate, format, channel_count,
                               true /*is_usb_hifi */) != 0)
        return 0;

    return get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
                                  sample_rate,
                                  format,
                                  channel_count,
                                  is_low_latency);
}

size_t get_output_period_size(uint32_t sample_rate,
                            audio_format_t format,
                            int channel_count,
                            int duration /*in millisecs*/)
{
    size_t size = 0;
    uint32_t bytes_per_sample = audio_bytes_per_sample(format);

    if ((duration == 0) || (sample_rate == 0) ||
        (bytes_per_sample == 0) || (channel_count == 0)) {
        ALOGW("Invalid config duration %d sr %d bps %d ch %d", duration, sample_rate,
               bytes_per_sample, channel_count);
        return -EINVAL;
    }

    size = (sample_rate *
            duration *
            bytes_per_sample *
            channel_count) / 1000;
    /*
     * To have same PCM samples for all channels, the buffer size requires to
     * be multiple of (number of channels * bytes per sample)
     * For writes to succeed, the buffer must be written at address which is multiple of 32
     */
    size = ALIGN(size, (bytes_per_sample * channel_count * 32));

    return (size/(channel_count * bytes_per_sample));
}

static uint64_t get_actual_pcm_frames_rendered(struct stream_out *out, struct timespec *timestamp)
{
    uint64_t actual_frames_rendered = 0;
    size_t kernel_buffer_size = out->compr_config.fragment_size * out->compr_config.fragments;

    /* This adjustment accounts for buffering after app processor.
     * It is based on estimated DSP latency per use case, rather than exact.
     */
    int64_t platform_latency =  platform_render_latency(out->usecase) *
                                out->sample_rate / 1000000LL;

    pthread_mutex_lock(&out->position_query_lock);
    /* not querying actual state of buffering in kernel as it would involve an ioctl call
     * which then needs protection, this causes delay in TS query for pcm_offload usecase
     * hence only estimate.
     */
    int64_t signed_frames = out->written - kernel_buffer_size;

    signed_frames = signed_frames / (audio_bytes_per_sample(out->format) * popcount(out->channel_mask)) - platform_latency;

    if (signed_frames > 0) {
        actual_frames_rendered = signed_frames;
        if (timestamp != NULL )
            *timestamp = out->writeAt;
    } else if (timestamp != NULL) {
        clock_gettime(CLOCK_MONOTONIC, timestamp);
    }
    pthread_mutex_unlock(&out->position_query_lock);

    ALOGVV("%s signed frames %lld out_written %lld kernel_buffer_size %d"
            "bytes/sample %zu channel count %d", __func__,(long long int)signed_frames,
             (long long int)out->written, (int)kernel_buffer_size,
             audio_bytes_per_sample(out->compr_config.codec->format),
             popcount(out->channel_mask));

    return actual_frames_rendered;
}

static uint32_t out_get_sample_rate(const struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;

    return out->sample_rate;
}

static int out_set_sample_rate(struct audio_stream *stream __unused,
                               uint32_t rate __unused)
{
    return -ENOSYS;
}

static size_t out_get_buffer_size(const struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;

    if (is_interactive_usecase(out->usecase)) {
        return out->config.period_size * out->config.period_count;
    } else if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
        if (out->flags & AUDIO_OUTPUT_FLAG_TIMESTAMP)
            return out->compr_config.fragment_size - sizeof(struct snd_codec_metadata);
        else
            return out->compr_config.fragment_size;
    } else if(out->usecase == USECASE_COMPRESS_VOIP_CALL)
        return voice_extn_compress_voip_out_get_buffer_size(out);
    else if (is_offload_usecase(out->usecase) &&
             out->flags == AUDIO_OUTPUT_FLAG_DIRECT)
        return out->hal_fragment_size;

    return out->config.period_size * out->af_period_multiplier *
                audio_stream_out_frame_size((const struct audio_stream_out *)stream);
}

static uint32_t out_get_channels(const struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;

    return out->channel_mask;
}

static audio_format_t out_get_format(const struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;

    return out->format;
}

static int out_set_format(struct audio_stream *stream __unused,
                          audio_format_t format __unused)
{
    return -ENOSYS;
}

static int out_standby(struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    bool do_stop = true;

    ALOGD("%s: enter: stream (%p) usecase(%d: %s)", __func__,
          stream, out->usecase, use_case_table[out->usecase]);

    lock_output_stream(out);
    if (!out->standby) {
        if (adev->adm_deregister_stream)
            adev->adm_deregister_stream(adev->adm_data, out->handle);

        if (is_offload_usecase(out->usecase))
            stop_compressed_output_l(out);

        pthread_mutex_lock(&adev->lock);
        out->standby = true;
        if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
            voice_extn_compress_voip_close_output_stream(stream);
            out->started = 0;
            pthread_mutex_unlock(&adev->lock);
            pthread_mutex_unlock(&out->lock);
            ALOGD("VOIP output entered standby");
            return 0;
        } else if (!is_offload_usecase(out->usecase)) {
            if (out->pcm) {
                pcm_close(out->pcm);
                out->pcm = NULL;
            }
            if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
                do_stop = out->playback_started;
                out->playback_started = false;
            }
        } else {
            ALOGD("copl(%p):standby", out);
            out->send_next_track_params = false;
            out->is_compr_metadata_avail = false;
            out->gapless_mdata.encoder_delay = 0;
            out->gapless_mdata.encoder_padding = 0;
            if (out->compr != NULL) {
                compress_close(out->compr);
                out->compr = NULL;
            }
        }
        if (do_stop) {
            stop_output_stream(out);
        }
        // if fm is active route on selected device in UI
        audio_extn_fm_route_on_selected_device(adev, out->devices);
        pthread_mutex_unlock(&adev->lock);
    }
    pthread_mutex_unlock(&out->lock);
    ALOGD("%s: exit", __func__);
    return 0;
}

static int out_on_error(struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    int status = 0;

    lock_output_stream(out);
    // always send CMD_ERROR for offload streams, this
    // is needed e.g. when SSR happens within compress_open
    // since the stream is active, offload_callback_thread is also active.
    if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
        stop_compressed_output_l(out);
    }
    pthread_mutex_unlock(&out->lock);

    status = out_standby(&out->stream.common);

    lock_output_stream(out);
    if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
        send_offload_cmd_l(out, OFFLOAD_CMD_ERROR);
    }

    if (is_offload_usecase(out->usecase) && out->card_status == CARD_STATUS_OFFLINE) {
        ALOGD("Setting previous card status if offline");
        out->prev_card_status_offline = true;
    }

    pthread_mutex_unlock(&out->lock);

    return status;
}

/*
 *standby implementation without locks, assumes that the callee already
 *has taken adev and out lock.
 */
int out_standby_l(struct audio_stream *stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;

    ALOGD("%s: enter: stream (%p) usecase(%d: %s)", __func__,
          stream, out->usecase, use_case_table[out->usecase]);

    if (!out->standby) {
        ATRACE_BEGIN("out_standby_l");
        if (adev->adm_deregister_stream)
            adev->adm_deregister_stream(adev->adm_data, out->handle);

        if (is_offload_usecase(out->usecase))
            stop_compressed_output_l(out);

        out->standby = true;
        if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
            voice_extn_compress_voip_close_output_stream(stream);
            out->started = 0;
            ALOGD("VOIP output entered standby");
            ATRACE_END();
            return 0;
        } else if (!is_offload_usecase(out->usecase)) {
            if (out->pcm) {
                pcm_close(out->pcm);
                out->pcm = NULL;
            }
            if (out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS) {
                if (adev->haptic_pcm) {
                    pcm_close(adev->haptic_pcm);
                    adev->haptic_pcm = NULL;
                }

                if (adev->haptic_buffer != NULL) {
                    free(adev->haptic_buffer);
                    adev->haptic_buffer = NULL;
                    adev->haptic_buffer_size = 0;
                }
                adev->haptic_pcm_device_id = 0;
            }
        } else {
            ALOGD("copl(%p):standby", out);
            out->send_next_track_params = false;
            out->is_compr_metadata_avail = false;
            out->gapless_mdata.encoder_delay = 0;
            out->gapless_mdata.encoder_padding = 0;
            if (out->compr != NULL) {
                compress_close(out->compr);
                out->compr = NULL;
            }
        }
        stop_output_stream(out);
        ATRACE_END();
    }
    ALOGD("%s: exit", __func__);
    return 0;
}

static int out_dump(const struct audio_stream *stream, int fd)
{
    struct stream_out *out = (struct stream_out *)stream;

    // We try to get the lock for consistency,
    // but it isn't necessary for these variables.
    // If we're not in standby, we may be blocked on a write.
    const bool locked = (pthread_mutex_trylock(&out->lock) == 0);
    dprintf(fd, "      Standby: %s\n", out->standby ? "yes" : "no");
    dprintf(fd, "      Frames written: %lld\n", (long long)out->written);

    if (locked) {
        pthread_mutex_unlock(&out->lock);
    }

    // dump error info
    (void)error_log_dump(
            out->error_log, fd, "      " /* prefix */, 0 /* lines */, 0 /* limit_ns */);

    return 0;
}

static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
{
    int ret = 0;
    char value[32];

    if (!out || !parms) {
        ALOGE("%s: return invalid ",__func__);
        return -EINVAL;
    }

    ret = audio_extn_parse_compress_metadata(out, parms);

    ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
    if (ret >= 0) {
        out->gapless_mdata.encoder_delay = atoi(value); //whats a good limit check?
    }
    ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
    if (ret >= 0) {
        out->gapless_mdata.encoder_padding = atoi(value);
    }

    ALOGV("%s new encoder delay %u and padding %u", __func__,
          out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);

    return 0;
}

static bool output_drives_call(struct audio_device *adev, struct stream_out *out)
{
    return out == adev->primary_output || out == adev->voice_tx_output;
}

// note: this call is safe only if the stream_cb is
// removed first in close_output_stream (as is done now).
static void out_snd_mon_cb(void * stream, struct str_parms * parms)
{
    if (!stream || !parms)
        return;

    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;

    card_status_t status;
    int card;
    if (parse_snd_card_status(parms, &card, &status) < 0)
        return;

    pthread_mutex_lock(&adev->lock);
    bool valid_cb = (card == adev->snd_card);
    pthread_mutex_unlock(&adev->lock);

    if (!valid_cb)
        return;

    lock_output_stream(out);
    if (out->card_status != status)
        out->card_status = status;
    pthread_mutex_unlock(&out->lock);

    ALOGI("out_snd_mon_cb for card %d usecase %s, status %s", card,
          use_case_table[out->usecase],
          status == CARD_STATUS_OFFLINE ? "offline" : "online");

    if (status == CARD_STATUS_OFFLINE) {
        out_on_error(stream);
        if (voice_is_call_state_active(adev) &&
            out == adev->primary_output) {
            ALOGD("%s: SSR/PDR occurred, end all calls\n", __func__);
            pthread_mutex_lock(&adev->lock);
            voice_stop_call(adev);
            adev->mode = AUDIO_MODE_NORMAL;
            pthread_mutex_unlock(&adev->lock);
        }
    }
    return;
}

static int get_alive_usb_card(struct str_parms* parms) {
    int card;
    if ((str_parms_get_int(parms, "card", &card) >= 0) &&
        !audio_extn_usb_alive(card)) {
        return card;
    }
    return -ENODEV;
}

static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    struct str_parms *parms;
    char value[32];
    int ret = 0, val = 0, err;
    bool bypass_a2dp = false;
    bool reconfig = false;
    unsigned long service_interval = 0;

    ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s",
          __func__, out->usecase, use_case_table[out->usecase], kvpairs);
    parms = str_parms_create_str(kvpairs);
    if (!parms)
        goto error;
    err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
    if (err >= 0) {
        val = atoi(value);
        lock_output_stream(out);
        pthread_mutex_lock(&adev->lock);

        /*
         * When HDMI cable is unplugged the music playback is paused and
         * the policy manager sends routing=0. But the audioflinger continues
         * to write data until standby time (3sec). As the HDMI core is
         * turned off, the write gets blocked.
         * Avoid this by routing audio to speaker until standby.
         */
        if ((out->devices == AUDIO_DEVICE_OUT_AUX_DIGITAL) &&
                (val == AUDIO_DEVICE_NONE) &&
                !audio_extn_passthru_is_passthrough_stream(out) &&
                (platform_get_edid_info(adev->platform) != 0) /* HDMI disconnected */) {
            val = AUDIO_DEVICE_OUT_SPEAKER;
        }
        /*
         * When A2DP is disconnected the
         * music playback is paused and the policy manager sends routing=0
         * But the audioflinger continues to write data until standby time
         * (3sec). As BT is turned off, the write gets blocked.
         * Avoid this by routing audio to speaker until standby.
         */
        if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
                (val == AUDIO_DEVICE_NONE) &&
                !audio_extn_a2dp_source_is_ready() &&
                !adev->bt_sco_on) {
                val = AUDIO_DEVICE_OUT_SPEAKER;
        }
        /*
        * When USB headset is disconnected the music platback paused
        * and the policy manager send routing=0. But if the USB is connected
        * back before the standby time, AFE is not closed and opened
        * when USB is connected back. So routing to speker will guarantee
        * AFE reconfiguration and AFE will be opend once USB is connected again
        */
        if ((out->devices & AUDIO_DEVICE_OUT_ALL_USB) &&
                (val == AUDIO_DEVICE_NONE) &&
                 !audio_extn_usb_connected(parms)) {
                 val = AUDIO_DEVICE_OUT_SPEAKER;
         }
        /* To avoid a2dp to sco overlapping / BT device improper state
         * check with BT lib about a2dp streaming support before routing
         */
        if (val & AUDIO_DEVICE_OUT_ALL_A2DP) {
            if (!audio_extn_a2dp_source_is_ready()) {
                if (val &
                    (AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
                    //combo usecase just by pass a2dp
                    ALOGW("%s: A2DP profile is not ready,routing to speaker only", __func__);
                    bypass_a2dp = true;
                } else {
                    ALOGE("%s: A2DP profile is not ready,ignoring routing request", __func__);
                    /* update device to a2dp and don't route as BT returned error
                     * However it is still possible a2dp routing called because
                     * of current active device disconnection (like wired headset)
                     */
                    out->devices = val;
                    pthread_mutex_unlock(&out->lock);
                    pthread_mutex_unlock(&adev->lock);
                    goto error;
                }
            }
        }

        audio_devices_t new_dev = val;

        // Workaround: If routing to an non existing usb device, fail gracefully
        // The routing request will otherwise block during 10 second
        int card;
        if (audio_is_usb_out_device(new_dev) &&
            (card = get_alive_usb_card(parms)) >= 0) {

            ALOGW("out_set_parameters() ignoring rerouting to non existing USB card %d", card);
            pthread_mutex_unlock(&adev->lock);
            pthread_mutex_unlock(&out->lock);
            ret = -ENOSYS;
            goto routing_fail;
        }

        /*
         * select_devices() call below switches all the usecases on the same
         * backend to the new device. Refer to check_usecases_codec_backend() in
         * the select_devices(). But how do we undo this?
         *
         * For example, music playback is active on headset (deep-buffer usecase)
         * and if we go to ringtones and select a ringtone, low-latency usecase
         * will be started on headset+speaker. As we can't enable headset+speaker
         * and headset devices at the same time, select_devices() switches the music
         * playback to headset+speaker while starting low-lateny usecase for ringtone.
         * So when the ringtone playback is completed, how do we undo the same?
         *
         * We are relying on the out_set_parameters() call on deep-buffer output,
         * once the ringtone playback is ended.
         * NOTE: We should not check if the current devices are same as new devices.
         *       Because select_devices() must be called to switch back the music
         *       playback to headset.
         */
        if (val != 0) {
            audio_devices_t new_dev = val;
            bool same_dev = out->devices == new_dev;
            out->devices = new_dev;

            if (output_drives_call(adev, out)) {
                if (!voice_is_call_state_active(adev)) {
                    if (adev->mode == AUDIO_MODE_IN_CALL) {
                        adev->current_call_output = out;
                        if (audio_is_usb_out_device(out->devices & AUDIO_DEVICE_OUT_ALL_USB)) {
                            service_interval = audio_extn_usb_find_service_interval(true, true /*playback*/);
                            audio_extn_usb_set_service_interval(true /*playback*/,
                                                                service_interval,
                                                                &reconfig);
                            ALOGD("%s, svc_int(%ld),reconfig(%d)",__func__,service_interval, reconfig);
                         }
                         ret = voice_start_call(adev);
                    }
                } else {
                    adev->current_call_output = out;
                    voice_update_devices_for_all_voice_usecases(adev);
                }
            }

            if (!out->standby) {
                if (!same_dev) {
                    ALOGV("update routing change");
                    audio_extn_perf_lock_acquire(&adev->perf_lock_handle, 0,
                                                 adev->perf_lock_opts,
                                                 adev->perf_lock_opts_size);
                    if (adev->adm_on_routing_change)
                        adev->adm_on_routing_change(adev->adm_data,
                                                    out->handle);
                }
                if (!bypass_a2dp) {
                    select_devices(adev, out->usecase);
                } else {
                    if (new_dev & AUDIO_DEVICE_OUT_SPEAKER_SAFE)
                        out->devices = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
                    else
                        out->devices = AUDIO_DEVICE_OUT_SPEAKER;
                    select_devices(adev, out->usecase);
                    out->devices = new_dev;
                }

                if (!same_dev) {
                    // on device switch force swap, lower functions will make sure
                    // to check if swap is allowed or not.
                    platform_set_swap_channels(adev, true);
                    audio_extn_perf_lock_release(&adev->perf_lock_handle);
                }
                if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
                    out->a2dp_compress_mute &&
                    (!(out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) || audio_extn_a2dp_source_is_ready())) {
                    pthread_mutex_lock(&out->compr_mute_lock);
                    out->a2dp_compress_mute = false;
                    out_set_compr_volume(&out->stream, out->volume_l, out->volume_r);
                    pthread_mutex_unlock(&out->compr_mute_lock);
                } else if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP) {
                    out_set_voip_volume(&out->stream, out->volume_l, out->volume_r);
                }
            }
        }

        pthread_mutex_unlock(&adev->lock);
        pthread_mutex_unlock(&out->lock);

        /*handles device and call state changes*/
        audio_extn_extspk_update(adev->extspk);
    }
    routing_fail:

    if (out == adev->primary_output) {
        pthread_mutex_lock(&adev->lock);
        audio_extn_set_parameters(adev, parms);
        pthread_mutex_unlock(&adev->lock);
    }
    if (is_offload_usecase(out->usecase)) {
        lock_output_stream(out);
        parse_compress_metadata(out, parms);

        audio_extn_dts_create_state_notifier_node(out->usecase);
        audio_extn_dts_notify_playback_state(out->usecase, 0, out->sample_rate,
                                                 popcount(out->channel_mask),
                                                 out->playback_started);

        pthread_mutex_unlock(&out->lock);
    }

    err = str_parms_get_str(parms, AUDIO_PARAMETER_DUAL_MONO, value,
                            sizeof(value));
    if (err >= 0) {
        if (!strncmp("true", value, sizeof("true")) || atoi(value))
            audio_extn_send_dual_mono_mixing_coefficients(out);
    }

    err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_PROFILE, value, sizeof(value));
    if (err >= 0) {
        strlcpy(out->profile, value, sizeof(out->profile));
        ALOGV("updating stream profile with value '%s'", out->profile);
        lock_output_stream(out);
        audio_extn_utils_update_stream_output_app_type_cfg(adev->platform,
                                                          &adev->streams_output_cfg_list,
                                                          out->devices, out->flags, out->hal_op_format,
                                                          out->sample_rate, out->bit_width,
                                                          out->channel_mask, out->profile,
                                                          &out->app_type_cfg);
        pthread_mutex_unlock(&out->lock);
    }

    //suspend, resume handling block
    //remove QOS only if vendor.audio.hal.dynamic.qos.config.supported is set to true
    // and vendor.audio.hal.output.suspend.supported is set to true
    if (out->hal_output_suspend_supported && out->dynamic_pm_qos_config_supported) {
        //check suspend parameter only for low latency and if the property
        //is enabled
        if (str_parms_get_str(parms, "suspend_playback", value, sizeof(value)) >= 0) {
            ALOGI("%s: got suspend_playback %s", __func__, value);
            lock_output_stream(out);
            if (!strncmp(value, "false", 5)) {
                //suspend_playback=false is supposed to set QOS value back to 75%
                //the mixer control sent with value Enable will achieve that
                ret = audio_route_apply_and_update_path(adev->audio_route, out->pm_qos_mixer_path);
            } else if (!strncmp (value, "true", 4)) {
                //suspend_playback=true is supposed to remove QOS value
                //resetting the mixer control will set the default value
                //for the mixer control which is Disable and this removes the QOS vote
                ret = audio_route_reset_and_update_path(adev->audio_route, out->pm_qos_mixer_path);
            } else {
                ALOGE("%s: Wrong value sent for suspend_playback, expected true/false,"
                       " got %s", __func__, value);
                ret = -1;
            }

            if (ret != 0) {
                ALOGE("%s: %s mixer ctl failed with %d, ignore suspend/resume setparams",
                        __func__, out->pm_qos_mixer_path, ret);
            }

            pthread_mutex_unlock(&out->lock);
        }
    }
    //end suspend, resume handling block
    str_parms_destroy(parms);
error:
    ALOGV("%s: exit: code(%d)", __func__, ret);
    return ret;
}

static int in_set_microphone_direction(const struct audio_stream_in *stream,
                                           audio_microphone_direction_t dir) {
    struct stream_in *in = (struct stream_in *)stream;

    ALOGVV("%s: standby %d source %d dir %d", __func__, in->standby, in->source, dir);

    in->direction = dir;

    if (in->standby)
        return 0;

    return audio_extn_audiozoom_set_microphone_direction(in, dir);
}

static int in_set_microphone_field_dimension(const struct audio_stream_in *stream, float zoom) {
    struct stream_in *in = (struct stream_in *)stream;

    ALOGVV("%s: standby %d source %d zoom %f", __func__, in->standby, in->source, zoom);

    if (zoom > 1.0 || zoom < -1.0)
        return -EINVAL;

    in->zoom = zoom;

    if (in->standby)
        return 0;

    return audio_extn_audiozoom_set_microphone_field_dimension(in, zoom);
}


static bool stream_get_parameter_channels(struct str_parms *query,
                                          struct str_parms *reply,
                                          audio_channel_mask_t *supported_channel_masks) {
    int ret = -1;
    char value[512];
    bool first = true;
    size_t i, j;

    if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
        ret = 0;
        value[0] = '\0';
        i = 0;
        while (supported_channel_masks[i] != 0) {
            for (j = 0; j < ARRAY_SIZE(channels_name_to_enum_table); j++) {
                if (channels_name_to_enum_table[j].value == supported_channel_masks[i]) {
                    if (!first)
                        strlcat(value, "|", sizeof(value));

                    strlcat(value, channels_name_to_enum_table[j].name, sizeof(value));
                    first = false;
                    break;
                }
            }
            i++;
        }
        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
    }
    return ret == 0;
}

static bool stream_get_parameter_formats(struct str_parms *query,
                                         struct str_parms *reply,
                                         audio_format_t *supported_formats) {
    int ret = -1;
    char value[256];
    size_t i, j;
    bool first = true;

    if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
        ret = 0;
        value[0] = '\0';
        i = 0;
        while (supported_formats[i] != 0) {
            for (j = 0; j < ARRAY_SIZE(formats_name_to_enum_table); j++) {
                if (formats_name_to_enum_table[j].value == supported_formats[i]) {
                    if (!first) {
                        strlcat(value, "|", sizeof(value));
                    }
                    strlcat(value, formats_name_to_enum_table[j].name, sizeof(value));
                    first = false;
                    break;
                }
            }
            i++;
        }
        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_FORMATS, value);
    }
    return ret == 0;
}

static bool stream_get_parameter_rates(struct str_parms *query,
                                       struct str_parms *reply,
                                       uint32_t *supported_sample_rates) {

    int i;
    char value[256];
    int ret = -1;
    if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
        ret = 0;
        value[0] = '\0';
        i=0;
        int cursor = 0;
        while (supported_sample_rates[i]) {
            int avail = sizeof(value) - cursor;
            ret = snprintf(value + cursor, avail, "%s%d",
                           cursor > 0 ? "|" : "",
                           supported_sample_rates[i]);
            if (ret < 0 || ret >= avail) {
                // if cursor is at the last element of the array
                //    overwrite with \0 is duplicate work as
                //    snprintf already put a \0 in place.
                // else
                //    we had space to write the '|' at value[cursor]
                //    (which will be overwritten) or no space to fill
                //    the first element (=> cursor == 0)
                value[cursor] = '\0';
                break;
            }
            cursor += ret;
            ++i;
        }
        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES,
                          value);
    }
    return ret >= 0;
}

static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct str_parms *query = str_parms_create_str(keys);
    char *str = (char*) NULL;
    char value[256];
    struct str_parms *reply = str_parms_create();
    size_t i, j;
    int ret;
    bool first = true;

    if (!query || !reply) {
        if (reply) {
            str_parms_destroy(reply);
        }
        if (query) {
            str_parms_destroy(query);
        }
        ALOGE("out_get_parameters: failed to allocate mem for query or reply");
        return NULL;
    }

    ALOGV("%s: %s enter: keys - %s", __func__, use_case_table[out->usecase], keys);
    ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value, sizeof(value));
    if (ret >= 0) {
        value[0] = '\0';
        i = 0;
        while (out->supported_channel_masks[i] != 0) {
            for (j = 0; j < ARRAY_SIZE(channels_name_to_enum_table); j++) {
                if (channels_name_to_enum_table[j].value == out->supported_channel_masks[i]) {
                    if (!first) {
                        strlcat(value, "|", sizeof(value));
                    }
                    strlcat(value, channels_name_to_enum_table[j].name, sizeof(value));
                    first = false;
                    break;
                }
            }
            i++;
        }
        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
        str = str_parms_to_str(reply);
    } else {
        voice_extn_out_get_parameters(out, query, reply);
        str = str_parms_to_str(reply);
    }


    ret = str_parms_get_str(query, "is_direct_pcm_track", value, sizeof(value));
    if (ret >= 0) {
        value[0] = '\0';
        if (out->flags & AUDIO_OUTPUT_FLAG_DIRECT &&
            !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
            ALOGV("in direct_pcm");
            strlcat(value, "true", sizeof(value));
        } else {
            ALOGV("not in direct_pcm");
            strlcat(value, "false", sizeof(value));
        }
        str_parms_add_str(reply, "is_direct_pcm_track", value);
        if (str)
            free(str);
        str = str_parms_to_str(reply);
    }

    ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS, value, sizeof(value));
    if (ret >= 0) {
        value[0] = '\0';
        i = 0;
        first = true;
        while (out->supported_formats[i] != 0) {
            for (j = 0; j < ARRAY_SIZE(formats_name_to_enum_table); j++) {
                if (formats_name_to_enum_table[j].value == out->supported_formats[i]) {
                    if (!first) {
                        strlcat(value, "|", sizeof(value));
                    }
                    strlcat(value, formats_name_to_enum_table[j].name, sizeof(value));
                    first = false;
                    break;
                }
            }
            i++;
        }
        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_FORMATS, value);
        if (str)
            free(str);
        str = str_parms_to_str(reply);
    }

    ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES, value, sizeof(value));
    if (ret >= 0) {
        value[0] = '\0';
        i = 0;
        first = true;
        while (out->supported_sample_rates[i] != 0) {
            for (j = 0; j < ARRAY_SIZE(out_sample_rates_name_to_enum_table); j++) {
                if (out_sample_rates_name_to_enum_table[j].value == out->supported_sample_rates[i]) {
                    if (!first) {
                        strlcat(value, "|", sizeof(value));
                    }
                    strlcat(value, out_sample_rates_name_to_enum_table[j].name, sizeof(value));
                    first = false;
                    break;
                }
            }
            i++;
        }
        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES, value);
        if (str)
            free(str);
        str = str_parms_to_str(reply);
    }

    if (str_parms_get_str(query, "supports_hw_suspend", value, sizeof(value)) >= 0) {
        //only low latency track supports suspend_resume
        str_parms_add_int(reply, "supports_hw_suspend",
                (out->hal_output_suspend_supported));
        if (str)
            free(str);
        str = str_parms_to_str(reply);
    }


    str_parms_destroy(query);
    str_parms_destroy(reply);
    ALOGV("%s: exit: returns - %s", __func__, str);
    return str;
}

static uint32_t out_get_latency(const struct audio_stream_out *stream)
{
    uint32_t period_ms;
    struct stream_out *out = (struct stream_out *)stream;
    uint32_t latency = 0;

    if (is_offload_usecase(out->usecase)) {
        lock_output_stream(out);
        latency = audio_extn_utils_compress_get_dsp_latency(out);
        pthread_mutex_unlock(&out->lock);
    } else if ((out->realtime) ||
            (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP)) {
        // since the buffer won't be filled up faster than realtime,
        // return a smaller number
        if (out->config.rate)
            period_ms = (out->af_period_multiplier * out->config.period_size *
                         1000) / (out->config.rate);
        else
            period_ms = 0;
        latency = period_ms + platform_render_latency(out->usecase)/1000;
    } else {
        latency = (out->config.period_count * out->config.period_size * 1000) /
           (out->config.rate);
    }

    if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices)
        latency += audio_extn_a2dp_get_encoder_latency();

    ALOGV("%s: Latency %d", __func__, latency);
    return latency;
}

static float AmpToDb(float amplification)
{
    float db = DSD_VOLUME_MIN_DB;
    if (amplification > 0) {
        db = 20 * log10(amplification);
        if(db < DSD_VOLUME_MIN_DB)
            return DSD_VOLUME_MIN_DB;
    }
    return db;
}

static int out_set_mmap_volume(struct audio_stream_out *stream, float left,
                          float right)
{
    struct stream_out *out = (struct stream_out *)stream;
    long volume = 0;
    char mixer_ctl_name[128] = "";
    struct audio_device *adev = out->dev;
    struct mixer_ctl *ctl = NULL;
    int pcm_device_id = platform_get_pcm_device_id(out->usecase,
                                               PCM_PLAYBACK);

    snprintf(mixer_ctl_name, sizeof(mixer_ctl_name),
             "Playback %d Volume", pcm_device_id);
    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: Could not get ctl for mixer cmd - %s",
              __func__, mixer_ctl_name);
        return -EINVAL;
    }
    if (left != right)
        ALOGW("%s: Left and right channel volume mismatch:%f,%f",
                 __func__, left, right);
    volume = (long)(left * (MMAP_PLAYBACK_VOLUME_MAX*1.0));
    if (mixer_ctl_set_value(ctl, 0, volume) < 0){
        ALOGE("%s:ctl for mixer cmd - %s, volume %ld returned error",
           __func__, mixer_ctl_name, volume);
        return -EINVAL;
    }
    return 0;
}

static int out_set_compr_volume(struct audio_stream_out *stream, float left,
                          float right)
{
    struct stream_out *out = (struct stream_out *)stream;
    long volume[2];
    char mixer_ctl_name[128];
    struct audio_device *adev = out->dev;
    struct mixer_ctl *ctl;
    int pcm_device_id = platform_get_pcm_device_id(out->usecase,
                                               PCM_PLAYBACK);

    snprintf(mixer_ctl_name, sizeof(mixer_ctl_name),
             "Compress Playback %d Volume", pcm_device_id);
    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: Could not get ctl for mixer cmd - %s",
              __func__, mixer_ctl_name);
        return -EINVAL;
    }
    ALOGE("%s:ctl for mixer cmd - %s, left %f, right %f",
           __func__, mixer_ctl_name, left, right);
    volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
    volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
    mixer_ctl_set_array(ctl, volume, sizeof(volume)/sizeof(volume[0]));

    return 0;
}

static int out_set_voip_volume(struct audio_stream_out *stream, float left,
                          float right)
{
    struct stream_out *out = (struct stream_out *)stream;
    char mixer_ctl_name[] = "App Type Gain";
    struct audio_device *adev = out->dev;
    struct mixer_ctl *ctl;
    long set_values[4];

    if (!is_valid_volume(left, right)) {
        ALOGE("%s: Invalid stream volume for left=%f, right=%f",
                   __func__, left, right);
        return -EINVAL;
    }

    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: Could not get ctl for mixer cmd - %s",
               __func__, mixer_ctl_name);
        return -EINVAL;
    }

    set_values[0] = 0; //0: Rx Session 1:Tx Session
    set_values[1] = out->app_type_cfg.app_type;
    set_values[2] = (long)(left * VOIP_PLAYBACK_VOLUME_MAX);
    set_values[3] = (long)(right * VOIP_PLAYBACK_VOLUME_MAX);

    mixer_ctl_set_array(ctl, set_values, ARRAY_SIZE(set_values));
    return 0;
}

static int out_set_pcm_volume(struct audio_stream_out *stream, float left,
                              float right)
{
    struct stream_out *out = (struct stream_out *)stream;
    /* Volume control for pcm playback */
    if (left != right) {
        return -EINVAL;
    } else {
        char mixer_ctl_name[128];
        struct audio_device *adev = out->dev;
        struct mixer_ctl *ctl;
        int pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
        snprintf(mixer_ctl_name, sizeof(mixer_ctl_name), "Playback %d Volume", pcm_device_id);
        ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
        if (!ctl) {
            ALOGE("%s : Could not get ctl for mixer cmd - %s", __func__, mixer_ctl_name);
            return -EINVAL;
        }

        int volume = (int) (left * PCM_PLAYBACK_VOLUME_MAX);
        int ret = mixer_ctl_set_value(ctl, 0, volume);
        if (ret < 0) {
            ALOGE("%s: Could not set ctl, error:%d ", __func__, ret);
            return -EINVAL;
        }

        ALOGV("%s : Pcm set volume value %d left %f", __func__, volume, left);

        return 0;
    }
}

static int out_set_volume(struct audio_stream_out *stream, float left,
                          float right)
{
    struct stream_out *out = (struct stream_out *)stream;
    int volume[2];
    int ret = 0;

    ALOGD("%s: called with left_vol=%f, right_vol=%f", __func__, left, right);
    if (out->usecase == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
        /* only take left channel into account: the API is for stereo anyway */
        out->muted = (left == 0.0f);
        return 0;
    } else if (is_offload_usecase(out->usecase)) {
        if (audio_extn_passthru_is_passthrough_stream(out)) {
            /*
             * Set mute or umute on HDMI passthrough stream.
             * Only take left channel into account.
             * Mute is 0 and unmute 1
             */
            audio_extn_passthru_set_volume(out, (left == 0.0f));
        } else if (out->format == AUDIO_FORMAT_DSD){
            char mixer_ctl_name[128] =  "DSD Volume";
            struct audio_device *adev = out->dev;
            struct mixer_ctl *ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);

            if (!ctl) {
                ALOGE("%s: Could not get ctl for mixer cmd - %s",
                      __func__, mixer_ctl_name);
                return -EINVAL;
            }
            volume[0] = (long)(AmpToDb(left));
            volume[1] = (long)(AmpToDb(right));
            mixer_ctl_set_array(ctl, volume, sizeof(volume)/sizeof(volume[0]));
            return 0;
        } else if ((out->devices & AUDIO_DEVICE_OUT_BUS) &&
                (audio_extn_auto_hal_get_snd_device_for_car_audio_stream(out) ==
                    SND_DEVICE_OUT_BUS_MEDIA)) {
            ALOGD("%s: Overriding offload set volume for media bus stream", __func__);
            struct listnode *node = NULL;
            list_for_each(node, &adev->active_outputs_list) {
                streams_output_ctxt_t *out_ctxt = node_to_item(node,
                                                    streams_output_ctxt_t,
                                                    list);
                if (out_ctxt->output->usecase == USECASE_AUDIO_PLAYBACK_MEDIA) {
                    out->volume_l = out_ctxt->output->volume_l;
                    out->volume_r = out_ctxt->output->volume_r;
                }
            }
            if (!out->a2dp_compress_mute) {
                ret = out_set_compr_volume(&out->stream, out->volume_l, out->volume_r);
            }
            return ret;
        } else {
            pthread_mutex_lock(&out->compr_mute_lock);
            ALOGV("%s: compress mute %d", __func__, out->a2dp_compress_mute);
            if (!out->a2dp_compress_mute)
                ret = out_set_compr_volume(stream, left, right);
            out->volume_l = left;
            out->volume_r = right;
            pthread_mutex_unlock(&out->compr_mute_lock);
            return ret;
        }
    } else if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP) {
        out->app_type_cfg.gain[0] = (int)(left * VOIP_PLAYBACK_VOLUME_MAX);
        out->app_type_cfg.gain[1] = (int)(right * VOIP_PLAYBACK_VOLUME_MAX);
        if (!out->standby) {
            audio_extn_utils_send_app_type_gain(out->dev,
                                                out->app_type_cfg.app_type,
                                                &out->app_type_cfg.gain[0]);
            ret = out_set_voip_volume(stream, left, right);
        }
        out->volume_l = left;
        out->volume_r = right;
        return ret;
    } else if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
        ALOGV("%s: MMAP set volume called", __func__);
        if (!out->standby)
            ret = out_set_mmap_volume(stream, left, right);
        out->volume_l = left;
        out->volume_r = right;
        return ret;
    } else if (out->usecase == USECASE_AUDIO_PLAYBACK_LOW_LATENCY ||
               out->usecase == USECASE_AUDIO_PLAYBACK_DEEP_BUFFER ||
               out->usecase == USECASE_AUDIO_PLAYBACK_ULL) {
        /* Volume control for pcm playback */
        if (!out->standby)
            ret = out_set_pcm_volume(stream, left, right);
        else
            out->apply_volume = true;

        out->volume_l = left;
        out->volume_r = right;
        return ret;
    } else if (audio_extn_auto_hal_is_bus_device_usecase(out->usecase)) {
        ALOGV("%s: bus device set volume called", __func__);
        if (!out->standby)
            ret = out_set_pcm_volume(stream, left, right);
        out->volume_l = left;
        out->volume_r = right;
        return ret;
    }

    return -ENOSYS;
}

static void update_frames_written(struct stream_out *out, size_t bytes)
{
    size_t bpf = 0;

    if (is_offload_usecase(out->usecase) && !out->non_blocking &&
        !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))
        bpf = 1;
    else if (!is_offload_usecase(out->usecase))
        bpf = audio_bytes_per_sample(out->format) *
             audio_channel_count_from_out_mask(out->channel_mask);

    pthread_mutex_lock(&out->position_query_lock);
    if (bpf != 0) {
        out->written += bytes / bpf;
        clock_gettime(CLOCK_MONOTONIC, &out->writeAt);
    }
    pthread_mutex_unlock(&out->position_query_lock);
}

int split_and_write_audio_haptic_data(struct stream_out *out,
                 const void *buffer, size_t bytes_to_write)
{
    struct audio_device *adev = out->dev;

    int ret = 0;
    size_t channel_count = audio_channel_count_from_out_mask(out->channel_mask);
    size_t bytes_per_sample = audio_bytes_per_sample(out->format);
    size_t frame_size = channel_count * bytes_per_sample;
    size_t frame_count = bytes_to_write / frame_size;

    bool force_haptic_path =
         property_get_bool("vendor.audio.test_haptic", false);

    // extract Haptics data from Audio buffer
    bool   alloc_haptic_buffer = false;
    int    haptic_channel_count = adev->haptics_config.channels;
    size_t haptic_frame_size = bytes_per_sample * haptic_channel_count;
    size_t audio_frame_size = frame_size - haptic_frame_size;
    size_t total_haptic_buffer_size = frame_count * haptic_frame_size;

    if (adev->haptic_buffer == NULL) {
        alloc_haptic_buffer = true;
    } else if (adev->haptic_buffer_size < total_haptic_buffer_size) {
        free(adev->haptic_buffer);
        adev->haptic_buffer_size = 0;
        alloc_haptic_buffer = true;
    }

    if (alloc_haptic_buffer) {
        adev->haptic_buffer = (uint8_t *)calloc(1, total_haptic_buffer_size);
        if(adev->haptic_buffer == NULL) {
            ALOGE("%s: failed to allocate mem for dev->haptic_buffer", __func__);
            return -ENOMEM;
        }
        adev->haptic_buffer_size = total_haptic_buffer_size;
    }

    size_t src_index = 0, aud_index = 0, hap_index = 0;
    uint8_t *audio_buffer = (uint8_t *)buffer;
    uint8_t *haptic_buffer  = adev->haptic_buffer;

    // This is required for testing only. This works for stereo data only.
    // One channel is fed to audio stream and other to haptic stream for testing.
    if (force_haptic_path)
       audio_frame_size = haptic_frame_size = bytes_per_sample;

    for (size_t i = 0; i < frame_count; i++) {
        memcpy(audio_buffer + aud_index, audio_buffer + src_index,
               audio_frame_size);
        aud_index += audio_frame_size;
        src_index += audio_frame_size;

        if (adev->haptic_pcm)
            memcpy(haptic_buffer + hap_index, audio_buffer + src_index,
                   haptic_frame_size);
        hap_index += haptic_frame_size;
        src_index += haptic_frame_size;

        // This is required for testing only.
        // Discard haptic channel data.
        if (force_haptic_path)
            src_index += haptic_frame_size;
    }

    // write to audio pipeline
    ret = pcm_write(out->pcm, (void *)audio_buffer,
                    frame_count * audio_frame_size);

    // write to haptics pipeline
    if (adev->haptic_pcm)
        ret = pcm_write(adev->haptic_pcm, (void *)adev->haptic_buffer,
                        frame_count * haptic_frame_size);

    return ret;
}

#ifdef NO_AUDIO_OUT
static ssize_t out_write_for_no_output(struct audio_stream_out *stream,
                                       const void *buffer __unused, size_t bytes)
{
    struct stream_out *out = (struct stream_out *)stream;

    /* No Output device supported other than BT for playback.
     * Sleep for the amount of buffer duration
     */
    lock_output_stream(out);
    usleep(bytes * 1000000 / audio_stream_out_frame_size(
            (const struct audio_stream_out *)&out->stream) /
            out_get_sample_rate(&out->stream.common));
    pthread_mutex_unlock(&out->lock);
    return bytes;
}
#endif

static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
                         size_t bytes)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    ssize_t ret = 0;
    int channels = 0;
    const size_t frame_size = audio_stream_out_frame_size(stream);
    const size_t frames = (frame_size != 0) ? bytes / frame_size : bytes;
    struct audio_usecase *usecase = NULL;

    ATRACE_BEGIN("out_write");
    lock_output_stream(out);

    if (CARD_STATUS_OFFLINE == out->card_status) {

        if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
            /*during SSR for compress usecase we should return error to flinger*/
            ALOGD(" copl %s: sound card is not active/SSR state", __func__);
            pthread_mutex_unlock(&out->lock);
            ATRACE_END();
            return -ENETRESET;
        } else {
            ALOGD(" %s: sound card is not active/SSR state", __func__);
            ret= -EIO;
            goto exit;
        }
    }

    if (audio_extn_passthru_should_drop_data(out)) {
        ALOGV(" %s : Drop data as compress passthrough session is going on", __func__);
        ret = -EIO;
        goto exit;
    }

    if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
        ret = -EINVAL;
        goto exit;
    }

    if ((out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) &&
         !out->is_iec61937_info_available) {

        if (!audio_extn_passthru_is_passthrough_stream(out)) {
            out->is_iec61937_info_available = true;
        } else if (audio_extn_passthru_is_enabled()) {
            audio_extn_passthru_update_stream_configuration(adev, out, buffer, bytes);
            out->is_iec61937_info_available = true;

            if((out->format == AUDIO_FORMAT_DTS) ||
               (out->format == AUDIO_FORMAT_DTS_HD)) {
                ret = audio_extn_passthru_update_dts_stream_configuration(out,
                                                                buffer, bytes);
                if (ret) {
                    if (ret != -ENOSYS) {
                        out->is_iec61937_info_available = false;
                        ALOGD("iec61937 transmission info not yet updated retry");
                    }
                } else if (!out->standby) {
                    /* if stream has started and after that there is
                     * stream config change (iec transmission config)
                     * then trigger select_device to update backend configuration.
                     */
                    out->stream_config_changed = true;
                    pthread_mutex_lock(&adev->lock);
                    select_devices(adev, out->usecase);
                    if (!audio_extn_passthru_is_supported_backend_edid_cfg(adev, out)) {
                        pthread_mutex_unlock(&adev->lock);
                        ret = -EINVAL;
                        goto exit;
                    }
                    pthread_mutex_unlock(&adev->lock);
                    out->stream_config_changed = false;
                    out->is_iec61937_info_available = true;
                }
            }

            if ((channels < (int)audio_channel_count_from_out_mask(out->channel_mask)) &&
                (out->compr_config.codec->compr_passthr == PASSTHROUGH) &&
                (out->is_iec61937_info_available == true)) {
                    ALOGE("%s: ERROR: Unsupported channel config in passthrough mode", __func__);
                    ret = -EINVAL;
                    goto exit;
            }
        }
    }

    if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
        (audio_extn_a2dp_source_is_suspended())) {
        if (!(out->devices &
            (AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_SPEAKER_SAFE))) {
            if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
                ret = -EIO;
                goto exit;
            }
        }
    }

    if (out->standby) {
        out->standby = false;
        pthread_mutex_lock(&adev->lock);
        if (out->usecase == USECASE_COMPRESS_VOIP_CALL)
            ret = voice_extn_compress_voip_start_output_stream(out);
        else
            ret = start_output_stream(out);
        pthread_mutex_unlock(&adev->lock);
        /* ToDo: If use case is compress offload should return 0 */
        if (ret != 0) {
            out->standby = true;
            goto exit;
        }
        out->started = 1;
        if (last_known_cal_step != -1) {
            ALOGD("%s: retry previous failed cal level set", __func__);
            audio_hw_send_gain_dep_calibration(last_known_cal_step);
            last_known_cal_step = -1;
        }

        if ((out->is_iec61937_info_available == true) &&
            (audio_extn_passthru_is_passthrough_stream(out))&&
            (!audio_extn_passthru_is_supported_backend_edid_cfg(adev, out))) {
            ret = -EINVAL;
            goto exit;
        }
        if (out->set_dual_mono)
            audio_extn_send_dual_mono_mixing_coefficients(out);
    }

    if (adev->is_channel_status_set == false && (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)){
        audio_utils_set_hdmi_channel_status(out, (void *)buffer, bytes);
        adev->is_channel_status_set = true;
    }

    if ((adev->use_old_pspd_mix_ctrl == true) &&
        (out->pspd_coeff_sent == false)) {
        /*
         * Need to resend pspd coefficients after stream started for
         * older kernel version as it does not save the coefficients
         * and also stream has to be started for coeff to apply.
         */
        usecase = get_usecase_from_list(adev, out->usecase);
        if (usecase != NULL) {
            audio_extn_set_custom_mtmx_params_v2(adev, usecase, true);
            out->pspd_coeff_sent = true;
        }
    }

    if (is_offload_usecase(out->usecase)) {
        ALOGVV("copl(%p): writing buffer (%zu bytes) to compress device", out, bytes);
        if (out->send_new_metadata) {
            ALOGD("copl(%p):send new gapless metadata", out);
            compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
            out->send_new_metadata = 0;
            if (out->send_next_track_params && out->is_compr_metadata_avail) {
                ALOGD("copl(%p):send next track params in gapless", out);
                // compress_set_next_track_param(out->compr, &(out->compr_config.codec->options));
                out->send_next_track_params = false;
                out->is_compr_metadata_avail = false;
            }
        }
        if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
                      (out->convert_buffer) != NULL) {

            if ((bytes > out->hal_fragment_size)) {
                ALOGW("Error written bytes %zu > %d (fragment_size)",
                       bytes, out->hal_fragment_size);
                pthread_mutex_unlock(&out->lock);
                ATRACE_END();
                return -EINVAL;
            } else {
                audio_format_t dst_format = out->hal_op_format;
                audio_format_t src_format = out->hal_ip_format;

                /* prevent division-by-zero */
                uint32_t bitwidth_src = format_to_bitwidth_table[src_format];
                uint32_t bitwidth_dst = format_to_bitwidth_table[dst_format];
                if ((bitwidth_src == 0) || (bitwidth_dst == 0)) {
                    ALOGE("%s: Error bitwidth == 0", __func__);
                    pthread_mutex_unlock(&out->lock);
                    ATRACE_END();
                    return -EINVAL;
                }

                uint32_t frames = bytes / format_to_bitwidth_table[src_format];
                uint32_t bytes_to_write = frames * format_to_bitwidth_table[dst_format];

                memcpy_by_audio_format(out->convert_buffer,
                                       dst_format,
                                       buffer,
                                       src_format,
                                       frames);

                ret = compress_write(out->compr, out->convert_buffer,
                                     bytes_to_write);

                /*Convert written bytes in audio flinger format*/
                if (ret > 0)
                    ret = ((ret * format_to_bitwidth_table[out->format]) /
                           format_to_bitwidth_table[dst_format]);
            }
        } else
            ret = compress_write(out->compr, buffer, bytes);

        if ((ret < 0 || ret == (ssize_t)bytes) && !out->non_blocking)
            update_frames_written(out, bytes);

        if (ret < 0)
            ret = -errno;
        ALOGVV("%s: writing buffer (%zu bytes) to compress device returned %d", __func__, bytes, (int)ret);
        /*msg to cb thread only if non blocking write is enabled*/
        if (ret >= 0 && ret < (ssize_t)bytes && out->non_blocking) {
            ALOGD("No space available in compress driver, post msg to cb thread");
            send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
        } else if (-ENETRESET == ret) {
            ALOGE("copl %s: received sound card offline state on compress write", __func__);
            out->card_status = CARD_STATUS_OFFLINE;
            pthread_mutex_unlock(&out->lock);
            out_on_error(&out->stream.common);
            ATRACE_END();
            return ret;
        }

        /* Call compr start only when non-zero bytes of data is there to be rendered */
        if (!out->playback_started && ret > 0) {
            int status = compress_start(out->compr);
            if (status < 0) {
                ret = status;
                ALOGE("%s: compr start failed with err %d", __func__, errno);
                goto exit;
            }
            audio_extn_dts_eagle_fade(adev, true, out);
            out->playback_started = 1;
            out->offload_state = OFFLOAD_STATE_PLAYING;

            audio_extn_dts_notify_playback_state(out->usecase, 0, out->sample_rate,
                                                     popcount(out->channel_mask),
                                                     out->playback_started);
        }
        pthread_mutex_unlock(&out->lock);
        ATRACE_END();
        return ret;
    } else {
        if (out->pcm) {
            size_t bytes_to_write = bytes;
            if (out->muted)
                memset((void *)buffer, 0, bytes);
            ALOGV("%s: frames=%zu, frame_size=%zu, bytes_to_write=%zu",
                     __func__, frames, frame_size, bytes_to_write);

            if (out->usecase == USECASE_INCALL_MUSIC_UPLINK ||
                out->usecase == USECASE_INCALL_MUSIC_UPLINK2 ||
                (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP &&
                 !audio_extn_utils_is_vendor_enhanced_fwk())) {
                size_t channel_count = audio_channel_count_from_out_mask(out->channel_mask);
                int16_t *src = (int16_t *)buffer;
                int16_t *dst = (int16_t *)buffer;

                LOG_ALWAYS_FATAL_IF(out->config.channels != 1 || channel_count != 2 ||
                                    out->format != AUDIO_FORMAT_PCM_16_BIT,
                                    "out_write called for %s use case with wrong properties",
                                    use_case_table[out->usecase]);

                /*
                 * FIXME: this can be removed once audio flinger mixer supports
                 * mono output
                 */

                /*
                 * Code below goes over each frame in the buffer and adds both
                 * L and R samples and then divides by 2 to convert to mono
                 */
                for (size_t i = 0; i < frames ; i++, dst++, src += 2) {
                    *dst = (int16_t)(((int32_t)src[0] + (int32_t)src[1]) >> 1);
                }
                bytes_to_write /= 2;
            }

            ALOGVV("%s: writing buffer (%zu bytes) to pcm device", __func__, bytes);

            long ns = 0;

            if (out->config.rate)
                ns = pcm_bytes_to_frames(out->pcm, bytes)*1000000000LL/
                                                     out->config.rate;

            request_out_focus(out, ns);
            bool use_mmap = is_mmap_usecase(out->usecase) || out->realtime;

            if (use_mmap)
                ret = pcm_mmap_write(out->pcm, (void *)buffer, bytes_to_write);
            else if (out->hal_op_format != out->hal_ip_format &&
                       out->convert_buffer != NULL) {

                memcpy_by_audio_format(out->convert_buffer,
                                       out->hal_op_format,
                                       buffer,
                                       out->hal_ip_format,
                                       out->config.period_size * out->config.channels);

                ret = pcm_write(out->pcm, out->convert_buffer,
                                 (out->config.period_size *
                                 out->config.channels *
                                 format_to_bitwidth_table[out->hal_op_format]));
            } else {
                /*
                 * To avoid underrun in DSP when the application is not pumping
                 * data at required rate, check for the no. of bytes and ignore
                 * pcm_write if it is less than actual buffer size.
                 * It is a work around to a change in compress VOIP driver.
                 */
                if ((out->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) &&
                    bytes < (out->config.period_size * out->config.channels *
                    audio_bytes_per_sample(out->format))) {
                    size_t voip_buf_size =
                        out->config.period_size * out->config.channels *
                        audio_bytes_per_sample(out->format);
                    ALOGE("%s:VOIP underrun: bytes received %zu, required:%zu\n",
                            __func__, bytes, voip_buf_size);
                    usleep(((uint64_t)voip_buf_size - bytes) *
                           1000000 / audio_stream_out_frame_size(stream) /
                           out_get_sample_rate(&out->stream.common));
                    ret = 0;
                } else {
                    if (out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS)
                        ret = split_and_write_audio_haptic_data(out, buffer, bytes);
                    else
                        ret = pcm_write(out->pcm, (void *)buffer, bytes_to_write);
                }
            }

            release_out_focus(out);

            if (ret < 0)
                ret = -errno;
            else if (ret > 0)
                ret = -EINVAL;
        }
    }

exit:
    update_frames_written(out, bytes);
    if (-ENETRESET == ret) {
        out->card_status = CARD_STATUS_OFFLINE;
    }
    pthread_mutex_unlock(&out->lock);

    if (ret != 0) {
        if (out->pcm)
            ALOGE("%s: error %d, %s", __func__, (int)ret, pcm_get_error(out->pcm));
        if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
            pthread_mutex_lock(&adev->lock);
            voice_extn_compress_voip_close_output_stream(&out->stream.common);
            out->started = 0;
            pthread_mutex_unlock(&adev->lock);
            out->standby = true;
        }
        out_on_error(&out->stream.common);
        if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
            /* prevent division-by-zero */
            uint32_t stream_size = audio_stream_out_frame_size(stream);
            uint32_t srate = out_get_sample_rate(&out->stream.common);

            if ((stream_size == 0) || (srate == 0)) {
                ALOGE("%s: stream_size= %d, srate = %d", __func__, stream_size, srate);
                ATRACE_END();
                return -EINVAL;
             }
             usleep((uint64_t)bytes * 1000000 / stream_size / srate);
        }
        if (audio_extn_passthru_is_passthrough_stream(out)) {
                //ALOGE("%s: write error, ret = %zd", __func__, ret);
                ATRACE_END();
                return ret;
        }
    }
    ATRACE_END();
    return bytes;
}

static int out_get_render_position(const struct audio_stream_out *stream,
                                   uint32_t *dsp_frames)
{
    struct stream_out *out = (struct stream_out *)stream;

    if (dsp_frames == NULL)
        return -EINVAL;

    *dsp_frames = 0;
    if (is_offload_usecase(out->usecase)) {
        ssize_t ret = 0;

        /* Below piece of code is not guarded against any lock beacuse audioFliner serializes
         * this operation and adev_close_output_stream(where out gets reset).
         */
        if (!out->non_blocking && !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
            *dsp_frames = get_actual_pcm_frames_rendered(out, NULL);
             ALOGVV("dsp_frames %d sampleRate %d",(int)*dsp_frames,out->sample_rate);
             adjust_frames_for_device_delay(out, dsp_frames);
             return 0;
        }

        lock_output_stream(out);
        if (out->compr != NULL && out->non_blocking) {
            ret = compress_get_tstamp(out->compr, (unsigned long *)dsp_frames,
                    &out->sample_rate);
            if (ret < 0)
                ret = -errno;
            ALOGVV("%s rendered frames %d sample_rate %d",
                    __func__, *dsp_frames, out->sample_rate);
        }
        if (-ENETRESET == ret) {
            ALOGE(" ERROR: sound card not active Unable to get time stamp from compress driver");
            out->card_status = CARD_STATUS_OFFLINE;
            ret = -EINVAL;
        } else if(ret < 0) {
            ALOGE(" ERROR: Unable to get time stamp from compress driver");
            ret = -EINVAL;
        } else if (out->card_status == CARD_STATUS_OFFLINE) {
            /*
             * Handle corner case where compress session is closed during SSR
             * and timestamp is queried
             */
            ALOGE(" ERROR: sound card not active, return error");
            ret = -EINVAL;
        } else if (out->prev_card_status_offline) {
            ALOGE("ERROR: previously sound card was offline,return error");
            ret = -EINVAL;
        } else {
            ret = 0;
            adjust_frames_for_device_delay(out, dsp_frames);
        }
        pthread_mutex_unlock(&out->lock);
        return ret;
    } else if (audio_is_linear_pcm(out->format)) {
        *dsp_frames = out->written;
        adjust_frames_for_device_delay(out, dsp_frames);
        return 0;
    } else
        return -EINVAL;
}

static int out_add_audio_effect(const struct audio_stream *stream __unused,
                                effect_handle_t effect __unused)
{
    return 0;
}

static int out_remove_audio_effect(const struct audio_stream *stream __unused,
                                   effect_handle_t effect __unused)
{
    return 0;
}

static int out_get_next_write_timestamp(const struct audio_stream_out *stream __unused,
                                        int64_t *timestamp __unused)
{
    return -ENOSYS;
}

static int out_get_presentation_position(const struct audio_stream_out *stream,
                                   uint64_t *frames, struct timespec *timestamp)
{
    struct stream_out *out = (struct stream_out *)stream;
    int ret = -ENODATA;
    unsigned long dsp_frames;

    /* below piece of code is not guarded against any lock because audioFliner serializes
     * this operation and adev_close_output_stream( where out gets reset).
     */
    if (is_offload_usecase(out->usecase) && !out->non_blocking &&
        !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
        *frames = get_actual_pcm_frames_rendered(out, timestamp);
        ALOGVV("frames %lld playedat %lld",(long long int)*frames,
             timestamp->tv_sec * 1000000LL + timestamp->tv_nsec / 1000);
        return 0;
    }

    lock_output_stream(out);

    if (is_offload_usecase(out->usecase) && out->compr != NULL && out->non_blocking) {
        ret = compress_get_tstamp(out->compr, &dsp_frames,
                 &out->sample_rate);
        // Adjustment accounts for A2dp encoder latency with offload usecases
        // Note: Encoder latency is returned in ms.
        if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices) {
            unsigned long offset =
                        (audio_extn_a2dp_get_encoder_latency() * out->sample_rate / 1000);
            dsp_frames = (dsp_frames > offset) ? (dsp_frames - offset) : 0;
        }
        ALOGVV("%s rendered frames %ld sample_rate %d",
               __func__, dsp_frames, out->sample_rate);
        *frames = dsp_frames;
        if (ret < 0)
            ret = -errno;
        if (-ENETRESET == ret) {
            ALOGE(" ERROR: sound card not active Unable to get time stamp from compress driver");
            out->card_status = CARD_STATUS_OFFLINE;
            ret = -EINVAL;
        } else
            ret = 0;
         /* this is the best we can do */
        clock_gettime(CLOCK_MONOTONIC, timestamp);
    } else {
        if (out->pcm) {
            unsigned int avail;
            if (pcm_get_htimestamp(out->pcm, &avail, timestamp) == 0) {
                size_t kernel_buffer_size = out->config.period_size * out->config.period_count;
                int64_t signed_frames = out->written - kernel_buffer_size + avail;
                // This adjustment accounts for buffering after app processor.
                // It is based on estimated DSP latency per use case, rather than exact.
                signed_frames -=
                        (platform_render_latency(out->usecase) * out->sample_rate / 1000000LL);

                // Adjustment accounts for A2dp encoder latency with non offload usecases
                // Note: Encoder latency is returned in ms, while platform_render_latency in us.
                if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices) {
                    signed_frames -=
                            (audio_extn_a2dp_get_encoder_latency() * out->sample_rate / 1000);
                }

                // It would be unusual for this value to be negative, but check just in case ...
                if (signed_frames >= 0) {
                    *frames = signed_frames;
                    ret = 0;
                }
            }
        } else if (out->card_status == CARD_STATUS_OFFLINE) {
            *frames = out->written;
            clock_gettime(CLOCK_MONOTONIC, timestamp);
            if (is_offload_usecase(out->usecase))
                ret = -EINVAL;
            else
                ret = 0;
        }
    }
    pthread_mutex_unlock(&out->lock);
    return ret;
}

static int out_set_callback(struct audio_stream_out *stream,
            stream_callback_t callback, void *cookie)
{
    struct stream_out *out = (struct stream_out *)stream;
    int ret;

    ALOGV("%s", __func__);
    lock_output_stream(out);
    out->client_callback = callback;
    out->client_cookie = cookie;
    if (out->adsp_hdlr_stream_handle) {
        ret = audio_extn_adsp_hdlr_stream_set_callback(
                                out->adsp_hdlr_stream_handle,
                                callback,
                                cookie);
        if (ret)
            ALOGW("%s:adsp hdlr callback registration failed %d",
                   __func__, ret);
    }
    pthread_mutex_unlock(&out->lock);
    return 0;
}

static int out_pause(struct audio_stream_out* stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    int status = -ENOSYS;
    ALOGV("%s", __func__);
    if (is_offload_usecase(out->usecase)) {
        ALOGD("copl(%p):pause compress driver", out);
        lock_output_stream(out);
        if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
            if (out->card_status != CARD_STATUS_OFFLINE)
                status = compress_pause(out->compr);

            out->offload_state = OFFLOAD_STATE_PAUSED;

            if (audio_extn_passthru_is_active()) {
                ALOGV("offload use case, pause passthru");
                audio_extn_passthru_on_pause(out);
            }

            audio_extn_dts_eagle_fade(adev, false, out);
            audio_extn_dts_notify_playback_state(out->usecase, 0,
                                                 out->sample_rate, popcount(out->channel_mask),
                                                 0);
        }
        pthread_mutex_unlock(&out->lock);
    }
    return status;
}

static int out_resume(struct audio_stream_out* stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    int status = -ENOSYS;
    ALOGV("%s", __func__);
    if (is_offload_usecase(out->usecase)) {
        ALOGD("copl(%p):resume compress driver", out);
        status = 0;
        lock_output_stream(out);
        if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
            if (out->card_status != CARD_STATUS_OFFLINE) {
                status = compress_resume(out->compr);
            }
            if (!status) {
                out->offload_state = OFFLOAD_STATE_PLAYING;
            }
            audio_extn_dts_eagle_fade(adev, true, out);
            audio_extn_dts_notify_playback_state(out->usecase, 0, out->sample_rate,
                                                     popcount(out->channel_mask), 1);
        }
        pthread_mutex_unlock(&out->lock);
    }
    return status;
}

static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
{
    struct stream_out *out = (struct stream_out *)stream;
    int status = -ENOSYS;
    ALOGV("%s", __func__);
    if (is_offload_usecase(out->usecase)) {
        lock_output_stream(out);
        if (type == AUDIO_DRAIN_EARLY_NOTIFY)
            status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
        else
            status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
        pthread_mutex_unlock(&out->lock);
    }
    return status;
}

static int out_flush(struct audio_stream_out* stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    ALOGV("%s", __func__);
    if (is_offload_usecase(out->usecase)) {
        ALOGD("copl(%p):calling compress flush", out);
        lock_output_stream(out);
        if (out->offload_state == OFFLOAD_STATE_PAUSED) {
            stop_compressed_output_l(out);
        } else {
            ALOGW("%s called in invalid state %d", __func__, out->offload_state);
        }
        out->written = 0;
        pthread_mutex_unlock(&out->lock);
        ALOGD("copl(%p):out of compress flush", out);
        return 0;
    }
    return -ENOSYS;
}

static int out_stop(const struct audio_stream_out* stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    int ret = -ENOSYS;

    ALOGV("%s", __func__);
    pthread_mutex_lock(&adev->lock);
    if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP && !out->standby &&
            out->playback_started && out->pcm != NULL) {
        pcm_stop(out->pcm);
        ret = stop_output_stream(out);
        out->playback_started = false;
    }
    pthread_mutex_unlock(&adev->lock);
    return ret;
}

static int out_start(const struct audio_stream_out* stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    int ret = -ENOSYS;

    ALOGV("%s", __func__);
    pthread_mutex_lock(&adev->lock);
    if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP && !out->standby &&
            !out->playback_started && out->pcm != NULL) {
        ret = start_output_stream(out);
        if (ret == 0) {
            out->playback_started = true;
        }
    }
    pthread_mutex_unlock(&adev->lock);
    return ret;
}

/*
 * Modify config->period_count based on min_size_frames
 */
static void adjust_mmap_period_count(struct pcm_config *config, int32_t min_size_frames)
{
    int periodCountRequested = (min_size_frames + config->period_size - 1)
                               / config->period_size;
    int periodCount = MMAP_PERIOD_COUNT_MIN;

    ALOGV("%s original config.period_size = %d config.period_count = %d",
          __func__, config->period_size, config->period_count);

    while (periodCount < periodCountRequested && (periodCount * 2) < MMAP_PERIOD_COUNT_MAX) {
        periodCount *= 2;
    }
    config->period_count = periodCount;

    ALOGV("%s requested config.period_count = %d", __func__, config->period_count);
}

// Read offset for the positional timestamp from a persistent vendor property.
// This is to workaround apparent inaccuracies in the timing information that
// is used by the AAudio timing model. The inaccuracies can cause glitches.
static int64_t get_mmap_out_time_offset() {
    const int32_t kDefaultOffsetMicros = 0;
    int32_t mmap_time_offset_micros = property_get_int32(
        "persist.vendor.audio.out_mmap_delay_micros", kDefaultOffsetMicros);
    ALOGI("mmap_time_offset_micros = %d for output", mmap_time_offset_micros);
    return mmap_time_offset_micros * (int64_t)1000;
}

static int out_create_mmap_buffer(const struct audio_stream_out *stream,
                                  int32_t min_size_frames,
                                  struct audio_mmap_buffer_info *info)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    int ret = 0;
    unsigned int offset1 = 0;
    unsigned int frames1 = 0;
    const char *step = "";
    uint32_t mmap_size;
    uint32_t buffer_size;

    ALOGD("%s", __func__);
    lock_output_stream(out);
    pthread_mutex_lock(&adev->lock);

    if (CARD_STATUS_OFFLINE == out->card_status ||
        CARD_STATUS_OFFLINE == adev->card_status) {
        ALOGW("out->card_status or adev->card_status offline, try again");
        ret = -EIO;
        goto exit;
    }
    if (info == NULL || min_size_frames == 0) {
        ALOGE("%s: info = %p, min_size_frames = %d", __func__, info, min_size_frames);
        ret = -EINVAL;
        goto exit;
    }
    if (out->usecase != USECASE_AUDIO_PLAYBACK_MMAP || !out->standby) {
        ALOGE("%s: usecase = %d, standby = %d", __func__, out->usecase, out->standby);
        ret = -ENOSYS;
        goto exit;
    }
    out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
    if (out->pcm_device_id < 0) {
        ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
              __func__, out->pcm_device_id, out->usecase);
        ret = -EINVAL;
        goto exit;
    }

    adjust_mmap_period_count(&out->config, min_size_frames);

    ALOGD("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
          __func__, adev->snd_card, out->pcm_device_id, out->config.channels);
    out->pcm = pcm_open(adev->snd_card, out->pcm_device_id,
                        (PCM_OUT | PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC), &out->config);
    if (errno == ENETRESET && !pcm_is_ready(out->pcm)) {
        ALOGE("%s: pcm_open failed errno:%d\n", __func__, errno);
        out->card_status = CARD_STATUS_OFFLINE;
        adev->card_status = CARD_STATUS_OFFLINE;
        ret = -EIO;
        goto exit;
    }

    if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
        step = "open";
        ret = -ENODEV;
        goto exit;
    }
    ret = pcm_mmap_begin(out->pcm, &info->shared_memory_address, &offset1, &frames1);
    if (ret < 0)  {
        step = "begin";
        goto exit;
    }
    info->buffer_size_frames = pcm_get_buffer_size(out->pcm);
    buffer_size = pcm_frames_to_bytes(out->pcm, info->buffer_size_frames);
    info->burst_size_frames = out->config.period_size;
    ret = platform_get_mmap_data_fd(adev->platform,
                                    out->pcm_device_id, 0 /*playback*/,
                                    &info->shared_memory_fd,
                                    &mmap_size);
    if (ret < 0) {
        // Fall back to non exclusive mode
        info->shared_memory_fd = pcm_get_poll_fd(out->pcm);
    } else {
        if (mmap_size < buffer_size) {
            step = "mmap";
            goto exit;
        }
        // FIXME: indicate exclusive mode support by returning a negative buffer size
        info->buffer_size_frames *= -1;
    }
    memset(info->shared_memory_address, 0, pcm_frames_to_bytes(out->pcm,
                                                               info->buffer_size_frames));

    ret = pcm_mmap_commit(out->pcm, 0, MMAP_PERIOD_SIZE);
    if (ret < 0) {
        step = "commit";
        goto exit;
    }

    out->mmap_time_offset_nanos = get_mmap_out_time_offset();

    out->standby = false;
    ret = 0;

    ALOGD("%s: got mmap buffer address %p info->buffer_size_frames %d",
          __func__, info->shared_memory_address, info->buffer_size_frames);

exit:
    if (ret != 0) {
        if (out->pcm == NULL) {
            ALOGE("%s: %s - %d", __func__, step, ret);
        } else {
            ALOGE("%s: %s %s", __func__, step, pcm_get_error(out->pcm));
            pcm_close(out->pcm);
            out->pcm = NULL;
        }
    }
    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&out->lock);
    return ret;
}

static int out_get_mmap_position(const struct audio_stream_out *stream,
                                  struct audio_mmap_position *position)
{
    struct stream_out *out = (struct stream_out *)stream;
    ALOGVV("%s", __func__);
    if (position == NULL) {
        return -EINVAL;
    }
    if (out->usecase != USECASE_AUDIO_PLAYBACK_MMAP) {
        ALOGE("%s: called on %s", __func__, use_case_table[out->usecase]);
        return -ENOSYS;
    }
    if (out->pcm == NULL) {
        return -ENOSYS;
    }

    struct timespec ts = { 0, 0 };
    int ret = pcm_mmap_get_hw_ptr(out->pcm, (unsigned int *)&position->position_frames, &ts);
    if (ret < 0) {
        ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
        return ret;
    }
    position->time_nanoseconds = ts.tv_sec*1000000000LL + ts.tv_nsec
            + out->mmap_time_offset_nanos;
    return 0;
}


/** audio_stream_in implementation **/
static uint32_t in_get_sample_rate(const struct audio_stream *stream)
{
    struct stream_in *in = (struct stream_in *)stream;

    return in->config.rate;
}

static int in_set_sample_rate(struct audio_stream *stream __unused,
                              uint32_t rate __unused)
{
    return -ENOSYS;
}

static size_t in_get_buffer_size(const struct audio_stream *stream)
{
    struct stream_in *in = (struct stream_in *)stream;

    if(in->usecase == USECASE_COMPRESS_VOIP_CALL)
        return voice_extn_compress_voip_in_get_buffer_size(in);
    else if(audio_extn_compr_cap_usecase_supported(in->usecase))
        return audio_extn_compr_cap_get_buffer_size(in->config.format);
    else if(audio_extn_cin_attached_usecase(in->usecase))
        return audio_extn_cin_get_buffer_size(in);

    return in->config.period_size * in->af_period_multiplier *
        audio_stream_in_frame_size((const struct audio_stream_in *)stream);
}

static uint32_t in_get_channels(const struct audio_stream *stream)
{
    struct stream_in *in = (struct stream_in *)stream;

    return in->channel_mask;
}

static audio_format_t in_get_format(const struct audio_stream *stream)
{
    struct stream_in *in = (struct stream_in *)stream;

    return in->format;
}

static int in_set_format(struct audio_stream *stream __unused,
                         audio_format_t format __unused)
{
    return -ENOSYS;
}

static int in_standby(struct audio_stream *stream)
{
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;
    int status = 0;
    ALOGD("%s: enter: stream (%p) usecase(%d: %s)", __func__,
          stream, in->usecase, use_case_table[in->usecase]);
    bool do_stop = true;

    lock_input_stream(in);
    if (!in->standby && in->is_st_session) {
        ALOGD("%s: sound trigger pcm stop lab", __func__);
        audio_extn_sound_trigger_stop_lab(in);
        adev->num_va_sessions--;
        in->standby = 1;
    }

    if (!in->standby) {
        if (adev->adm_deregister_stream)
            adev->adm_deregister_stream(adev->adm_data, in->capture_handle);

        pthread_mutex_lock(&adev->lock);
        in->standby = true;
        if (in->usecase == USECASE_COMPRESS_VOIP_CALL) {
            do_stop = false;
            voice_extn_compress_voip_close_input_stream(stream);
            ALOGD("VOIP input entered standby");
        } else if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
            do_stop = in->capture_started;
            in->capture_started = false;
        } else {
            if (audio_extn_cin_attached_usecase(in->usecase))
                audio_extn_cin_close_input_stream(in);
        }

        if (in->pcm) {
            ATRACE_BEGIN("pcm_in_close");
            pcm_close(in->pcm);
            ATRACE_END();
            in->pcm = NULL;
        }

        if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION)
            adev->enable_voicerx = false;

        if (do_stop)
            status = stop_input_stream(in);

        if (in->source == AUDIO_SOURCE_VOICE_RECOGNITION)
            adev->num_va_sessions--;

        pthread_mutex_unlock(&adev->lock);
    }
    pthread_mutex_unlock(&in->lock);
    ALOGV("%s: exit:  status(%d)", __func__, status);
    return status;
}

static int in_dump(const struct audio_stream *stream,
                   int fd)
{
    struct stream_in *in = (struct stream_in *)stream;

    // We try to get the lock for consistency,
    // but it isn't necessary for these variables.
    // If we're not in standby, we may be blocked on a read.
    const bool locked = (pthread_mutex_trylock(&in->lock) == 0);
    dprintf(fd, "      Standby: %s\n", in->standby ? "yes" : "no");
    dprintf(fd, "      Frames read: %lld\n", (long long)in->frames_read);
    dprintf(fd, "      Frames muted: %lld\n", (long long)in->frames_muted);

    if (locked) {
        pthread_mutex_unlock(&in->lock);
    }

    // dump error info
    (void)error_log_dump(
            in->error_log, fd, "      " /* prefix */, 0 /* lines */, 0 /* limit_ns */);

    return 0;
}

static void in_snd_mon_cb(void * stream, struct str_parms * parms)
{
    if (!stream || !parms)
        return;

    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;

    card_status_t status;
    int card;
    if (parse_snd_card_status(parms, &card, &status) < 0)
        return;

    pthread_mutex_lock(&adev->lock);
    bool valid_cb = (card == adev->snd_card);
    pthread_mutex_unlock(&adev->lock);

    if (!valid_cb)
        return;

    lock_input_stream(in);
    if (in->card_status != status)
        in->card_status = status;
    pthread_mutex_unlock(&in->lock);

    ALOGW("in_snd_mon_cb for card %d usecase %s, status %s", card,
          use_case_table[in->usecase],
          status == CARD_STATUS_OFFLINE ? "offline" : "online");

    // a better solution would be to report error back to AF and let
    // it put the stream to standby
    if (status == CARD_STATUS_OFFLINE)
        in_standby(&in->stream.common);

    return;
}

static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
{
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;
    struct str_parms *parms;
    char value[32];
    int ret = 0, val = 0, err;

    ALOGD("%s: enter: kvpairs=%s", __func__, kvpairs);
    parms = str_parms_create_str(kvpairs);

    if (!parms)
        goto error;
    lock_input_stream(in);
    pthread_mutex_lock(&adev->lock);

    err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
    if (err >= 0) {
        val = atoi(value);
        /* no audio source uses val == 0 */
        if ((in->source != val) && (val != 0)) {
            in->source = val;
            if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
                (in->dev->mode == AUDIO_MODE_IN_COMMUNICATION) &&
                (voice_extn_compress_voip_is_format_supported(in->format)) &&
                (in->config.rate == 8000 || in->config.rate == 16000 ||
                 in->config.rate == 32000 || in->config.rate == 48000 ) &&
                (audio_channel_count_from_in_mask(in->channel_mask) == 1)) {
                err = voice_extn_compress_voip_open_input_stream(in);
                if (err != 0) {
                    ALOGE("%s: Compress voip input cannot be opened, error:%d",
                          __func__, err);
                }
            }
        }
    }

    err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
    if (err >= 0) {
        val = atoi(value);
        if (((int)in->device != val) && (val != 0) && audio_is_input_device(val) ) {

            // Workaround: If routing to an non existing usb device, fail gracefully
            // The routing request will otherwise block during 10 second
            int card;
            if (audio_is_usb_in_device(val) &&
                (card = get_alive_usb_card(parms)) >= 0) {

                ALOGW("in_set_parameters() ignoring rerouting to non existing USB card %d", card);
                ret = -ENOSYS;
            } else {

                in->device = val;
                /* If recording is in progress, change the tx device to new device */
                if (!in->standby && !in->is_st_session) {
                    ALOGV("update input routing change");
                    // inform adm before actual routing to prevent glitches.
                    if (adev->adm_on_routing_change) {
                        adev->adm_on_routing_change(adev->adm_data,
                                                    in->capture_handle);
                        ret = select_devices(adev, in->usecase);
                        if (in->usecase == USECASE_AUDIO_RECORD_LOW_LATENCY)
                            adev->adm_routing_changed = true;
                    }
                }
            }
        }
    }

    err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_PROFILE, value, sizeof(value));
    if (err >= 0) {
        strlcpy(in->profile, value, sizeof(in->profile));
        ALOGV("updating stream profile with value '%s'", in->profile);
        audio_extn_utils_update_stream_input_app_type_cfg(adev->platform,
                                                          &adev->streams_input_cfg_list,
                                                          in->device, in->flags, in->format,
                                                          in->sample_rate, in->bit_width,
                                                          in->profile, &in->app_type_cfg);
    }

    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&in->lock);

    str_parms_destroy(parms);
error:
    ALOGV("%s: exit: status(%d)", __func__, ret);
    return ret;
}

static char* in_get_parameters(const struct audio_stream *stream,
                               const char *keys)
{
    struct stream_in *in = (struct stream_in *)stream;
    struct str_parms *query = str_parms_create_str(keys);
    char *str;
    struct str_parms *reply = str_parms_create();

    if (!query || !reply) {
        if (reply) {
            str_parms_destroy(reply);
        }
        if (query) {
            str_parms_destroy(query);
        }
        ALOGE("in_get_parameters: failed to create query or reply");
        return NULL;
    }

    ALOGV("%s: enter: keys - %s %s ", __func__, use_case_table[in->usecase], keys);

    voice_extn_in_get_parameters(in, query, reply);

    stream_get_parameter_channels(query, reply,
                                  &in->supported_channel_masks[0]);
    stream_get_parameter_formats(query, reply,
                                 &in->supported_formats[0]);
    stream_get_parameter_rates(query, reply,
                               &in->supported_sample_rates[0]);
    str = str_parms_to_str(reply);
    str_parms_destroy(query);
    str_parms_destroy(reply);

    ALOGV("%s: exit: returns - %s", __func__, str);
    return str;
}

static int in_set_gain(struct audio_stream_in *stream,
                       float gain)
{
    struct stream_in *in = (struct stream_in *)stream;
    char mixer_ctl_name[128];
    struct mixer_ctl *ctl;
    int ctl_value;

    ALOGV("%s: gain %f", __func__, gain);

    if (stream == NULL)
        return -EINVAL;

    /* in_set_gain() only used to silence MMAP capture for now */
    if (in->usecase != USECASE_AUDIO_RECORD_MMAP)
        return -ENOSYS;

    snprintf(mixer_ctl_name, sizeof(mixer_ctl_name), "Capture %d Volume", in->pcm_device_id);

    ctl = mixer_get_ctl_by_name(in->dev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGW("%s: Could not get ctl for mixer cmd - %s",
              __func__, mixer_ctl_name);
        return -ENOSYS;
    }

    if (gain < RECORD_GAIN_MIN)
        gain  = RECORD_GAIN_MIN;
    else if (gain > RECORD_GAIN_MAX)
         gain = RECORD_GAIN_MAX;
    ctl_value = (int)(RECORD_VOLUME_CTL_MAX * gain);

    mixer_ctl_set_value(ctl, 0, ctl_value);

    return 0;
}

static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
                       size_t bytes)
{
    struct stream_in *in = (struct stream_in *)stream;

    if (in == NULL) {
        ALOGE("%s: stream_in ptr is NULL", __func__);
        return -EINVAL;
    }

    struct audio_device *adev = in->dev;
    int ret = -1;
    size_t bytes_read = 0, frame_size = 0;

    lock_input_stream(in);

    if (in->is_st_session) {
        ALOGVV(" %s: reading on st session bytes=%zu", __func__, bytes);
        /* Read from sound trigger HAL */
        audio_extn_sound_trigger_read(in, buffer, bytes);
        if (in->standby) {
            adev->num_va_sessions++;
            in->standby = 0;
        }
        pthread_mutex_unlock(&in->lock);
        return bytes;
    }

    if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
        ret = -ENOSYS;
        goto exit;
    }

    if (in->usecase == USECASE_AUDIO_RECORD_LOW_LATENCY &&
        !in->standby && adev->adm_routing_changed) {
        ret = -ENOSYS;
        goto exit;
    }

    if (in->standby) {
        pthread_mutex_lock(&adev->lock);
        if (in->usecase == USECASE_COMPRESS_VOIP_CALL)
            ret = voice_extn_compress_voip_start_input_stream(in);
        else
            ret = start_input_stream(in);
        if (!ret && in->source == AUDIO_SOURCE_VOICE_RECOGNITION)
            adev->num_va_sessions++;
        pthread_mutex_unlock(&adev->lock);
        if (ret != 0) {
            goto exit;
        }
        in->standby = 0;
    }

    /* Avoid read if capture_stopped is set */
    if (android_atomic_acquire_load(&(in->capture_stopped)) > 0) {
        ALOGD("%s: force stopped catpure session, ignoring read request", __func__);
        ret = -EINVAL;
        goto exit;
    }

    // what's the duration requested by the client?
    long ns = 0;

    if (in->pcm && in->config.rate)
        ns = pcm_bytes_to_frames(in->pcm, bytes)*1000000000LL/
                                             in->config.rate;

    ret = request_in_focus(in, ns);
    if (ret != 0)
        goto exit;
    bool use_mmap = is_mmap_usecase(in->usecase) || in->realtime;

    if (audio_extn_cin_attached_usecase(in->usecase)) {
        ret = audio_extn_cin_read(in, buffer, bytes, &bytes_read);
    } else if (in->pcm) {
        if (audio_extn_ssr_get_stream() == in) {
            ret = audio_extn_ssr_read(stream, buffer, bytes);
        } else if (audio_extn_compr_cap_usecase_supported(in->usecase)) {
            ret = audio_extn_compr_cap_read(in, buffer, bytes);
        } else if (use_mmap) {
            ret = pcm_mmap_read(in->pcm, buffer, bytes);
        } else if (audio_extn_ffv_get_stream() == in) {
            ret = audio_extn_ffv_read(stream, buffer, bytes);
        } else {
            ret = pcm_read(in->pcm, buffer, bytes);
            /* data from DSP comes in 24_8 format, convert it to 8_24 */
            if (!ret && bytes > 0 && (in->format == AUDIO_FORMAT_PCM_8_24_BIT)) {
                if (audio_extn_utils_convert_format_24_8_to_8_24(buffer, bytes)
                    != bytes) {
                    ret = -EINVAL;
                    goto exit;
                }
            } else if (ret < 0) {
                ret = -errno;
            }
        }
        /* bytes read is always set to bytes for non compress usecases */
        bytes_read = bytes;
    }

    release_in_focus(in);

    /*
     * Instead of writing zeroes here, we could trust the hardware to always
     * provide zeroes when muted. This is also muted with voice recognition
     * usecases so that other clients do not have access to voice recognition
     * data.
     */
    if ((ret == 0 && voice_get_mic_mute(adev) &&
         !voice_is_in_call_rec_stream(in) &&
         in->usecase != USECASE_AUDIO_RECORD_AFE_PROXY) ||
        (adev->num_va_sessions &&
         in->source != AUDIO_SOURCE_VOICE_RECOGNITION &&
         property_get_bool("persist.vendor.audio.va_concurrency_mute_enabled",
            false)))
        memset(buffer, 0, bytes);

exit:
    frame_size = audio_stream_in_frame_size(stream);
    if (frame_size > 0)
        in->frames_read += bytes_read/frame_size;

    if (-ENETRESET == ret)
        in->card_status = CARD_STATUS_OFFLINE;
    pthread_mutex_unlock(&in->lock);

    if (ret != 0) {
        if (in->usecase == USECASE_COMPRESS_VOIP_CALL) {
            pthread_mutex_lock(&adev->lock);
            voice_extn_compress_voip_close_input_stream(&in->stream.common);
            pthread_mutex_unlock(&adev->lock);
            in->standby = true;
        }
        if (!audio_extn_cin_attached_usecase(in->usecase)) {
            bytes_read = bytes;
            memset(buffer, 0, bytes);
        }
        in_standby(&in->stream.common);
        if (in->usecase == USECASE_AUDIO_RECORD_LOW_LATENCY)
            adev->adm_routing_changed = false;
        ALOGV("%s: read failed status %d- sleeping for buffer duration", __func__, ret);
        usleep((uint64_t)bytes * 1000000 / audio_stream_in_frame_size(stream) /
                                   in_get_sample_rate(&in->stream.common));
    }
    return bytes_read;
}

static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream __unused)
{
    return 0;
}

static int in_get_capture_position(const struct audio_stream_in *stream,
                                   int64_t *frames, int64_t *time)
{
    if (stream == NULL || frames == NULL || time == NULL) {
        return -EINVAL;
    }
    struct stream_in *in = (struct stream_in *)stream;
    int ret = -ENOSYS;

    lock_input_stream(in);
    // note: ST sessions do not close the alsa pcm driver synchronously
    // on standby. Therefore, we may return an error even though the
    // pcm stream is still opened.
    if (in->standby) {
        ALOGE_IF(in->pcm != NULL && !in->is_st_session,
                 "%s stream in standby but pcm not NULL for non ST session", __func__);
        goto exit;
    }
    if (in->pcm) {
        struct timespec timestamp;
        unsigned int avail;
        if (pcm_get_htimestamp(in->pcm, &avail, &timestamp) == 0) {
            *frames = in->frames_read + avail;
            *time = timestamp.tv_sec * 1000000000LL + timestamp.tv_nsec;
            ret = 0;
        }
    }
exit:
    pthread_mutex_unlock(&in->lock);
    return ret;
}

static int in_update_effect_list(bool add, effect_handle_t effect,
                            struct listnode *head)
{
    struct listnode *node;
    struct in_effect_list *elist = NULL;
    struct in_effect_list *target = NULL;
    int ret = 0;

    if (!head)
        return ret;

    list_for_each(node, head) {
        elist = node_to_item(node, struct in_effect_list, list);
        if (elist->handle == effect) {
            target = elist;
            break;
        }
    }

    if (add) {
        if (target) {
            ALOGD("effect %p already exist", effect);
            return ret;
        }

        target = (struct in_effect_list *)
                     calloc(1, sizeof(struct in_effect_list));

        if (!target) {
            ALOGE("%s:fail to allocate memory", __func__);
            return -ENOMEM;
        }

        target->handle = effect;
        list_add_tail(head, &target->list);
    } else {
        if (target) {
            list_remove(&target->list);
            free(target);
        }
    }

    return ret;
}

static int add_remove_audio_effect(const struct audio_stream *stream,
                                   effect_handle_t effect,
                                   bool enable)
{
    struct stream_in *in = (struct stream_in *)stream;
    int status = 0;
    effect_descriptor_t desc;

    status = (*effect)->get_descriptor(effect, &desc);
    ALOGV("%s: status %d in->standby %d enable:%d", __func__, status, in->standby, enable);

    if (status != 0)
        return status;

    lock_input_stream(in);
    pthread_mutex_lock(&in->dev->lock);
    if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
            in->source == AUDIO_SOURCE_VOICE_RECOGNITION ||
            adev->mode == AUDIO_MODE_IN_COMMUNICATION) &&
            (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {

        in_update_effect_list(enable, effect, &in->aec_list);
        enable = !list_empty(&in->aec_list);
        if (enable == in->enable_aec)
            goto exit;

        in->enable_aec = enable;
        ALOGD("AEC enable %d", enable);

        if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
            in->dev->mode == AUDIO_MODE_IN_COMMUNICATION) {
            in->dev->enable_voicerx = enable;
            struct audio_usecase *usecase;
            struct listnode *node;
            list_for_each(node, &in->dev->usecase_list) {
                usecase = node_to_item(node, struct audio_usecase, list);
                if (usecase->type == PCM_PLAYBACK)
                    select_devices(in->dev, usecase->id);
            }
        }
        if (!in->standby) {
            if (enable_disable_effect(in->dev, EFFECT_AEC, enable) == ENOSYS)
                select_devices(in->dev, in->usecase);
        }

    }
    if (memcmp(&desc.type, FX_IID_NS, sizeof(effect_uuid_t)) == 0) {

        in_update_effect_list(enable, effect, &in->ns_list);
        enable = !list_empty(&in->ns_list);
        if (enable == in->enable_ns)
            goto exit;

        in->enable_ns = enable;
        ALOGD("NS enable %d", enable);
        if (!in->standby) {
            if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
                in->dev->mode == AUDIO_MODE_IN_COMMUNICATION) {
                if (enable_disable_effect(in->dev, EFFECT_NS, enable) == ENOSYS)
                    select_devices(in->dev, in->usecase);
            } else
                select_devices(in->dev, in->usecase);
        }
    }
exit:
    pthread_mutex_unlock(&in->dev->lock);
    pthread_mutex_unlock(&in->lock);

    return 0;
}

static int in_add_audio_effect(const struct audio_stream *stream,
                               effect_handle_t effect)
{
    ALOGV("%s: effect %p", __func__, effect);
    return add_remove_audio_effect(stream, effect, true);
}

static int in_remove_audio_effect(const struct audio_stream *stream,
                                  effect_handle_t effect)
{
    ALOGV("%s: effect %p", __func__, effect);
    return add_remove_audio_effect(stream, effect, false);
}

streams_input_ctxt_t *in_get_stream(struct audio_device *dev,
                                  audio_io_handle_t input)
{
    struct listnode *node;

    list_for_each(node, &dev->active_inputs_list) {
        streams_input_ctxt_t *in_ctxt = node_to_item(node,
                                                     streams_input_ctxt_t,
                                                     list);
        if (in_ctxt->input->capture_handle == input) {
            return in_ctxt;
        }
    }
    return NULL;
}

streams_output_ctxt_t *out_get_stream(struct audio_device *dev,
                                  audio_io_handle_t output)
{
    struct listnode *node;

    list_for_each(node, &dev->active_outputs_list) {
        streams_output_ctxt_t *out_ctxt = node_to_item(node,
                                                     streams_output_ctxt_t,
                                                     list);
        if (out_ctxt->output->handle == output) {
            return out_ctxt;
        }
    }
    return NULL;
}

static int in_stop(const struct audio_stream_in* stream)
{
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;

    int ret = -ENOSYS;
    ALOGV("%s", __func__);
    pthread_mutex_lock(&adev->lock);
    if (in->usecase == USECASE_AUDIO_RECORD_MMAP && !in->standby &&
            in->capture_started && in->pcm != NULL) {
        pcm_stop(in->pcm);
        ret = stop_input_stream(in);
        in->capture_started = false;
    }
    pthread_mutex_unlock(&adev->lock);
    return ret;
}

static int in_start(const struct audio_stream_in* stream)
{
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;
    int ret = -ENOSYS;

    ALOGV("%s in %p", __func__, in);
    pthread_mutex_lock(&adev->lock);
    if (in->usecase == USECASE_AUDIO_RECORD_MMAP && !in->standby &&
            !in->capture_started && in->pcm != NULL) {
        if (!in->capture_started) {
            ret = start_input_stream(in);
            if (ret == 0) {
                in->capture_started = true;
            }
        }
    }
    pthread_mutex_unlock(&adev->lock);
    return ret;
}

// Read offset for the positional timestamp from a persistent vendor property.
// This is to workaround apparent inaccuracies in the timing information that
// is used by the AAudio timing model. The inaccuracies can cause glitches.
static int64_t in_get_mmap_time_offset() {
    const int32_t kDefaultOffsetMicros = 0;
    int32_t mmap_time_offset_micros = property_get_int32(
            "persist.vendor.audio.in_mmap_delay_micros", kDefaultOffsetMicros);
    ALOGI("mmap_time_offset_micros = %d for input", mmap_time_offset_micros);
    return mmap_time_offset_micros * (int64_t)1000;
}

static int in_create_mmap_buffer(const struct audio_stream_in *stream,
                                  int32_t min_size_frames,
                                  struct audio_mmap_buffer_info *info)
{
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;
    int ret = 0;
    unsigned int offset1 = 0;
    unsigned int frames1 = 0;
    const char *step = "";
    uint32_t mmap_size = 0;
    uint32_t buffer_size = 0;

    pthread_mutex_lock(&adev->lock);
    ALOGV("%s in %p", __func__, in);

    if (CARD_STATUS_OFFLINE == in->card_status||
        CARD_STATUS_OFFLINE == adev->card_status) {
        ALOGW("in->card_status or adev->card_status offline, try again");
        ret = -EIO;
        goto exit;
    }

    if (info == NULL || min_size_frames == 0) {
        ALOGE("%s invalid argument info %p min_size_frames %d", __func__, info, min_size_frames);
        ret = -EINVAL;
        goto exit;
    }
    if (in->usecase != USECASE_AUDIO_RECORD_MMAP || !in->standby) {
        ALOGE("%s: usecase = %d, standby = %d", __func__, in->usecase, in->standby);
        ALOGV("%s in %p", __func__, in);
        ret = -ENOSYS;
        goto exit;
    }
    in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
    if (in->pcm_device_id < 0) {
        ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
              __func__, in->pcm_device_id, in->usecase);
        ret = -EINVAL;
        goto exit;
    }

    adjust_mmap_period_count(&in->config, min_size_frames);

    ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
          __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
    in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
                        (PCM_IN | PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC), &in->config);
    if (errno == ENETRESET && !pcm_is_ready(in->pcm)) {
        ALOGE("%s: pcm_open failed errno:%d\n", __func__, errno);
        in->card_status = CARD_STATUS_OFFLINE;
        adev->card_status = CARD_STATUS_OFFLINE;
        ret = -EIO;
        goto exit;
    }

    if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
        step = "open";
        ret = -ENODEV;
        goto exit;
    }

    ret = pcm_mmap_begin(in->pcm, &info->shared_memory_address, &offset1, &frames1);
    if (ret < 0)  {
        step = "begin";
        goto exit;
    }

    info->buffer_size_frames = pcm_get_buffer_size(in->pcm);
    buffer_size = pcm_frames_to_bytes(in->pcm, info->buffer_size_frames);
    info->burst_size_frames = in->config.period_size;
    ret = platform_get_mmap_data_fd(adev->platform,
                                    in->pcm_device_id, 1 /*capture*/,
                                    &info->shared_memory_fd,
                                    &mmap_size);
    if (ret < 0) {
        // Fall back to non exclusive mode
        info->shared_memory_fd = pcm_get_poll_fd(in->pcm);
    } else {
        if (mmap_size < buffer_size) {
            step = "mmap";
            goto exit;
        }
        // FIXME: indicate exclusive mode support by returning a negative buffer size
        info->buffer_size_frames *= -1;
    }

    memset(info->shared_memory_address, 0, buffer_size);

    ret = pcm_mmap_commit(in->pcm, 0, MMAP_PERIOD_SIZE);
    if (ret < 0) {
        step = "commit";
        goto exit;
    }

    in->mmap_time_offset_nanos = in_get_mmap_time_offset();

    in->standby = false;
    ret = 0;

    ALOGV("%s: got mmap buffer address %p info->buffer_size_frames %d",
          __func__, info->shared_memory_address, info->buffer_size_frames);

exit:
    if (ret != 0) {
        if (in->pcm == NULL) {
            ALOGE("%s: %s - %d", __func__, step, ret);
        } else {
            ALOGE("%s: %s %s", __func__, step, pcm_get_error(in->pcm));
            pcm_close(in->pcm);
            in->pcm = NULL;
        }
    }
    pthread_mutex_unlock(&adev->lock);
    return ret;
}

static int in_get_mmap_position(const struct audio_stream_in *stream,
                                  struct audio_mmap_position *position)
{
    struct stream_in *in = (struct stream_in *)stream;
    ALOGVV("%s", __func__);
    if (position == NULL) {
        return -EINVAL;
    }
    if (in->usecase != USECASE_AUDIO_RECORD_MMAP) {
        return -ENOSYS;
    }
    if (in->pcm == NULL) {
        return -ENOSYS;
    }
    struct timespec ts = { 0, 0 };
    int ret = pcm_mmap_get_hw_ptr(in->pcm, (unsigned int *)&position->position_frames, &ts);
    if (ret < 0) {
        ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
        return ret;
    }
    position->time_nanoseconds = ts.tv_sec*1000000000LL + ts.tv_nsec
            + in->mmap_time_offset_nanos;
    return 0;
}

static int in_get_active_microphones(const struct audio_stream_in *stream,
                                     struct audio_microphone_characteristic_t *mic_array,
                                     size_t *mic_count) {
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;
    ALOGVV("%s", __func__);

    lock_input_stream(in);
    pthread_mutex_lock(&adev->lock);
    int ret = platform_get_active_microphones(adev->platform,
                                              audio_channel_count_from_in_mask(in->channel_mask),
                                              in->usecase, mic_array, mic_count);
    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&in->lock);

    return ret;
}

static int adev_get_microphones(const struct audio_hw_device *dev,
                                struct audio_microphone_characteristic_t *mic_array,
                                size_t *mic_count) {
    struct audio_device *adev = (struct audio_device *)dev;
    ALOGVV("%s", __func__);

    pthread_mutex_lock(&adev->lock);
    int ret = platform_get_microphones(adev->platform, mic_array, mic_count);
    pthread_mutex_unlock(&adev->lock);

    return ret;
}

static void in_update_sink_metadata(struct audio_stream_in *stream,
                                    const struct sink_metadata *sink_metadata) {

    if (stream == NULL
            || sink_metadata == NULL
            || sink_metadata->tracks == NULL) {
        return;
    }

    int error = 0;
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = in->dev;
    audio_devices_t device = AUDIO_DEVICE_NONE;

    if (sink_metadata->track_count != 0)
        device = sink_metadata->tracks->dest_device;

    lock_input_stream(in);
    pthread_mutex_lock(&adev->lock);
    ALOGV("%s: in->usecase: %d, device: %x", __func__, in->usecase, device);

    if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY
            && device != AUDIO_DEVICE_NONE
            && adev->voice_tx_output != NULL) {
        /* Use the rx device from afe-proxy record to route voice call because
           there is no routing if tx device is on primary hal and rx device
           is on other hal during voice call. */
        adev->voice_tx_output->devices = device;

        if (!voice_is_call_state_active(adev)) {
            if (adev->mode == AUDIO_MODE_IN_CALL) {
                adev->current_call_output = adev->voice_tx_output;
                error = voice_start_call(adev);
                if (error != 0)
                    ALOGE("%s: start voice call failed %d", __func__, error);
            }
        } else {
            adev->current_call_output = adev->voice_tx_output;
            voice_update_devices_for_all_voice_usecases(adev);
        }
    }

    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&in->lock);
}

int adev_open_output_stream(struct audio_hw_device *dev,
                            audio_io_handle_t handle,
                            audio_devices_t devices,
                            audio_output_flags_t flags,
                            struct audio_config *config,
                            struct audio_stream_out **stream_out,
                            const char *address)
{
    struct audio_device *adev = (struct audio_device *)dev;
    struct stream_out *out;
    int ret = 0, ip_hdlr_stream = 0, ip_hdlr_dev = 0;
    audio_format_t format;
    struct adsp_hdlr_stream_cfg hdlr_stream_cfg;
    bool is_direct_passthough = false;
    bool is_hdmi = devices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
    bool is_usb_dev = audio_is_usb_out_device(devices) &&
                      (devices != AUDIO_DEVICE_OUT_USB_ACCESSORY);
    bool direct_dev = is_hdmi || is_usb_dev;
    bool use_db_as_primary =
         property_get_bool("vendor.audio.feature.deepbuffer_as_primary.enable",
                            false);
    bool force_haptic_path =
            property_get_bool("vendor.audio.test_haptic", false);
    bool is_voip_rx = flags & AUDIO_OUTPUT_FLAG_VOIP_RX;

    if (is_usb_dev && (!audio_extn_usb_connected(NULL))) {
        is_usb_dev = false;
        devices = AUDIO_DEVICE_OUT_SPEAKER;
        ALOGW("%s: ignore set device to non existing USB card, use output device(%#x)",
              __func__, devices);
    }

    *stream_out = NULL;

    pthread_mutex_lock(&adev->lock);
    if (out_get_stream(adev, handle) != NULL) {
        ALOGW("%s, output stream already opened", __func__);
        ret = -EEXIST;
    }
    pthread_mutex_unlock(&adev->lock);
    if (ret)
        return ret;

    out = (struct stream_out *)calloc(1, sizeof(struct stream_out));

    ALOGD("%s: enter: format(%#x) sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)\
        stream_handle(%p) address(%s)", __func__, config->format, config->sample_rate, config->channel_mask,
        devices, flags, &out->stream, address);


    if (!out) {
        return -ENOMEM;
    }

    pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
    pthread_mutex_init(&out->pre_lock, (const pthread_mutexattr_t *) NULL);
    pthread_mutex_init(&out->compr_mute_lock, (const pthread_mutexattr_t *) NULL);
    pthread_mutex_init(&out->position_query_lock, (const pthread_mutexattr_t *) NULL);
    pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);

    if (devices == AUDIO_DEVICE_NONE)
        devices = AUDIO_DEVICE_OUT_SPEAKER;

    out->flags = flags;
    out->devices = devices;
    out->dev = adev;
    out->hal_op_format = out->hal_ip_format = format = out->format = config->format;
    out->sample_rate = config->sample_rate;
    out->channel_mask = config->channel_mask;
    if (out->channel_mask == AUDIO_CHANNEL_NONE)
        out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
    else
        out->supported_channel_masks[0] = out->channel_mask;
    out->handle = handle;
    out->bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH;
    out->non_blocking = 0;
    out->convert_buffer = NULL;
    out->started = 0;
    out->a2dp_compress_mute = false;
    out->hal_output_suspend_supported = 0;
    out->dynamic_pm_qos_config_supported = 0;
    out->set_dual_mono = false;
    out->prev_card_status_offline = false;
    out->pspd_coeff_sent = false;

    if ((flags & AUDIO_OUTPUT_FLAG_BD) &&
        (property_get_bool("vendor.audio.matrix.limiter.enable", false)))
        platform_set_device_params(out, DEVICE_PARAM_LIMITER_ID, 1);

    if (direct_dev &&
        (audio_is_linear_pcm(out->format) ||
         config->format == AUDIO_FORMAT_DEFAULT) &&
        out->flags == AUDIO_OUTPUT_FLAG_NONE) {
        audio_format_t req_format = config->format;
        audio_channel_mask_t req_channel_mask = config->channel_mask;
        uint32_t req_sample_rate = config->sample_rate;

        pthread_mutex_lock(&adev->lock);
        if (is_hdmi) {
            ALOGV("AUDIO_DEVICE_OUT_AUX_DIGITAL and DIRECT|OFFLOAD, check hdmi caps");
            ret = read_hdmi_sink_caps(out);
            if (config->sample_rate == 0)
                config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
            if (config->channel_mask == AUDIO_CHANNEL_NONE)
                config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
            if (config->format == AUDIO_FORMAT_DEFAULT)
                config->format = AUDIO_FORMAT_PCM_16_BIT;
        } else if (is_usb_dev) {
            ret = read_usb_sup_params_and_compare(true /*is_playback*/,
                                                  &config->format,
                                                  &out->supported_formats[0],
                                                  MAX_SUPPORTED_FORMATS,
                                                  &config->channel_mask,
                                                  &out->supported_channel_masks[0],
                                                  MAX_SUPPORTED_CHANNEL_MASKS,
                                                  &config->sample_rate,
                                                  &out->supported_sample_rates[0],
                                                  MAX_SUPPORTED_SAMPLE_RATES);
            ALOGV("plugged dev USB ret %d", ret);
       }

       pthread_mutex_unlock(&adev->lock);
       if (ret != 0) {
            if (ret == -ENOSYS) {
                /* ignore and go with default */
                ret = 0;
            }
            // For MMAP NO IRQ, allow conversions in ADSP
            else if (is_hdmi || (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0)
                goto error_open;
            else {
                ALOGE("error reading direct dev sink caps");
                goto error_open;
            }

            if (req_sample_rate != 0 && config->sample_rate != req_sample_rate)
                config->sample_rate = req_sample_rate;
            if (req_channel_mask != AUDIO_CHANNEL_NONE && config->channel_mask != req_channel_mask)
                config->channel_mask = req_channel_mask;
            if (req_format != AUDIO_FORMAT_DEFAULT && config->format != req_format)
                config->format = req_format;
        }

        out->sample_rate = config->sample_rate;
        out->channel_mask = config->channel_mask;
        out->format = config->format;
        if (is_hdmi) {
            out->usecase = USECASE_AUDIO_PLAYBACK_HIFI;
            out->config = pcm_config_hdmi_multi;
        } else if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
            out->usecase = USECASE_AUDIO_PLAYBACK_MMAP;
            out->config = pcm_config_mmap_playback;
            out->stream.start = out_start;
            out->stream.stop = out_stop;
            out->stream.create_mmap_buffer = out_create_mmap_buffer;
            out->stream.get_mmap_position = out_get_mmap_position;
        } else {
            out->usecase = USECASE_AUDIO_PLAYBACK_HIFI;
            out->config = pcm_config_hifi;
        }

        out->config.rate = out->sample_rate;
        out->config.channels = audio_channel_count_from_out_mask(out->channel_mask);
        if (is_hdmi) {
            out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels *
                                                         audio_bytes_per_sample(out->format));
        }
        out->config.format = pcm_format_from_audio_format(out->format);
    }

    /* validate bus device address */
    if (out->devices & AUDIO_DEVICE_OUT_BUS) {
        /* extract car audio stream index */
        out->car_audio_stream =
            audio_extn_auto_hal_get_car_audio_stream_from_address(address);
        if (out->car_audio_stream < 0) {
            ALOGE("%s: invalid car audio stream %x",
                __func__, out->car_audio_stream);
            ret = -EINVAL;
            goto error_open;
        }
        /* save car audio stream and address for bus device */
        strlcpy(out->address, address, AUDIO_DEVICE_MAX_ADDRESS_LEN);
        ALOGV("%s: address %s, car_audio_stream %x",
            __func__, out->address, out->car_audio_stream);
    }

    /* Check for VOIP usecase */
    if (is_voip_rx) {
        if (!voice_extn_is_compress_voip_supported()) {
            if (out->sample_rate == 8000 || out->sample_rate == 16000 ||
             out->sample_rate == 32000 || out->sample_rate == 48000) {
                out->channel_mask = audio_extn_utils_is_vendor_enhanced_fwk() ?
                                        AUDIO_CHANNEL_OUT_MONO : AUDIO_CHANNEL_OUT_STEREO;
                out->usecase = USECASE_AUDIO_PLAYBACK_VOIP;
                out->format = AUDIO_FORMAT_PCM_16_BIT;
                out->volume_l = INVALID_OUT_VOLUME;
                out->volume_r = INVALID_OUT_VOLUME;

                out->config = default_pcm_config_voip_copp;
                out->config.rate = out->sample_rate;
                uint32_t channel_count =
                        audio_channel_count_from_out_mask(out->channel_mask);
                uint32_t buffer_size = get_stream_buffer_size(DEFAULT_VOIP_BUF_DURATION_MS,
                                                              out->sample_rate, out->format,
                                                              channel_count, false);
                uint32_t frame_size = audio_bytes_per_sample(out->format) * channel_count;
                if (frame_size != 0)
                    out->config.period_size = buffer_size / frame_size;
                else
                    ALOGW("%s: frame size is 0 for format %#x", __func__, out->format);
            }
        } else {
                if ((out->dev->mode == AUDIO_MODE_IN_COMMUNICATION ||
                    voice_extn_compress_voip_is_active(out->dev)) &&
                       (voice_extn_compress_voip_is_config_supported(config))) {
                    ret = voice_extn_compress_voip_open_output_stream(out);
                    if (ret != 0) {
                        ALOGE("%s: Compress voip output cannot be opened, error:%d",
                              __func__, ret);
                        goto error_open;
                    }
                } else {
                    out->usecase = GET_USECASE_AUDIO_PLAYBACK_PRIMARY(use_db_as_primary);
                    out->config = GET_PCM_CONFIG_AUDIO_PLAYBACK_PRIMARY(use_db_as_primary);
                }
        }
    } else if (audio_is_linear_pcm(out->format) &&
        out->flags == AUDIO_OUTPUT_FLAG_NONE && is_usb_dev) {
        out->channel_mask = config->channel_mask;
        out->sample_rate = config->sample_rate;
        out->format = config->format;
        out->usecase = USECASE_AUDIO_PLAYBACK_HIFI;
        // does this change?
        out->config = is_hdmi ? pcm_config_hdmi_multi : pcm_config_hifi;
        out->config.rate = config->sample_rate;
        out->config.channels = audio_channel_count_from_out_mask(out->channel_mask);
        out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels *
                                                         audio_bytes_per_sample(config->format));
        out->config.format = pcm_format_from_audio_format(out->format);
    } else if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) ||
               (out->flags == AUDIO_OUTPUT_FLAG_DIRECT)) {
        pthread_mutex_lock(&adev->lock);
        bool offline = (adev->card_status == CARD_STATUS_OFFLINE);
        pthread_mutex_unlock(&adev->lock);

        // reject offload during card offline to allow
        // fallback to s/w paths
        if (offline) {
            ret = -ENODEV;
            goto error_open;
        }

        if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
            config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
            ALOGE("%s: Unsupported Offload information", __func__);
            ret = -EINVAL;
            goto error_open;
        }

        if (config->offload_info.format == 0)
            config->offload_info.format = config->format;
        if (config->offload_info.sample_rate == 0)
            config->offload_info.sample_rate = config->sample_rate;

        if (!is_supported_format(config->offload_info.format) &&
                !audio_extn_passthru_is_supported_format(config->offload_info.format)) {
            ALOGE("%s: Unsupported audio format %x " , __func__, config->offload_info.format);
            ret = -EINVAL;
            goto error_open;
        }

        /* TrueHD only supported for 48k multiples (48k, 96k, 192k) */
        if ((config->offload_info.format == AUDIO_FORMAT_DOLBY_TRUEHD) &&
                (audio_extn_passthru_is_passthrough_stream(out)) &&
                !((config->sample_rate == 48000) ||
                  (config->sample_rate == 96000) ||
                  (config->sample_rate == 192000))) {
            ALOGE("%s: Unsupported sample rate %d for audio format %x",
                    __func__, config->sample_rate, config->offload_info.format);
            ret = -EINVAL;
            goto error_open;
        }

        out->compr_config.codec = (struct snd_codec *)
                                    calloc(1, sizeof(struct snd_codec));

        if (!out->compr_config.codec) {
            ret = -ENOMEM;
            goto error_open;
        }

        out->stream.pause = out_pause;
        out->stream.resume = out_resume;
        out->stream.flush = out_flush;
        out->stream.set_callback = out_set_callback;
        if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
            out->stream.drain = out_drain;
            out->usecase = get_offload_usecase(adev, true /* is_compress */);
            ALOGV("Compress Offload usecase .. usecase selected %d", out->usecase);
        } else {
            out->usecase = get_offload_usecase(adev, false /* is_compress */);
            ALOGV("non-offload DIRECT_usecase ... usecase selected %d ", out->usecase);
        }

        if (out->flags & AUDIO_OUTPUT_FLAG_FAST) {
            ALOGD("%s: Setting latency mode to true", __func__);
            out->compr_config.codec->flags |= audio_extn_utils_get_perf_mode_flag();
        }

        if (out->usecase == USECASE_INVALID) {
            if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL &&
                    config->format == 0 && config->sample_rate == 0 &&
                    config->channel_mask == 0) {
                ALOGI("%s dummy open to query sink capability",__func__);
                out->usecase = USECASE_AUDIO_PLAYBACK_OFFLOAD;
            } else {
                ALOGE("%s, Max allowed OFFLOAD usecase reached ... ", __func__);
                ret = -EEXIST;
                goto error_open;
            }
        }

        if (config->offload_info.channel_mask)
            out->channel_mask = config->offload_info.channel_mask;
        else if (config->channel_mask) {
            out->channel_mask = config->channel_mask;
            config->offload_info.channel_mask = config->channel_mask;
        } else {
            ALOGE("out->channel_mask not set for OFFLOAD/DIRECT usecase");
            ret = -EINVAL;
            goto error_open;
        }

        format = out->format = config->offload_info.format;
        out->sample_rate = config->offload_info.sample_rate;

        out->bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH;

        out->compr_config.codec->id = get_snd_codec_id(config->offload_info.format);
        if (audio_extn_utils_is_dolby_format(config->offload_info.format)) {
            audio_extn_dolby_send_ddp_endp_params(adev);
            audio_extn_dolby_set_dmid(adev);
        }

        out->compr_config.codec->sample_rate =
                    config->offload_info.sample_rate;
        out->compr_config.codec->bit_rate =
                    config->offload_info.bit_rate;
        out->compr_config.codec->ch_in =
                audio_channel_count_from_out_mask(out->channel_mask);
        out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
        /* Update bit width only for non passthrough usecases.
         * For passthrough usecases, the output will always be opened @16 bit
         */
        if (!audio_extn_passthru_is_passthrough_stream(out))
            out->bit_width = AUDIO_OUTPUT_BIT_WIDTH;

        if (out->flags & AUDIO_OUTPUT_FLAG_TIMESTAMP)
            out->compr_config.codec->flags |= COMPRESSED_TIMESTAMP_FLAG;
        ALOGVV("%s : out->compr_config.codec->flags -> (%#x) ", __func__, out->compr_config.codec->flags);

        /*TODO: Do we need to change it for passthrough */
        out->compr_config.codec->format = SND_AUDIOSTREAMFORMAT_RAW;

        if ((config->offload_info.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC)
             out->compr_config.codec->format = SND_AUDIOSTREAMFORMAT_RAW;
        else if ((config->offload_info.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC_ADTS)
            out->compr_config.codec->format = SND_AUDIOSTREAMFORMAT_MP4ADTS;
        else if ((config->offload_info.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC_LATM)
            out->compr_config.codec->format = SND_AUDIOSTREAMFORMAT_MP4LATM;

        if ((config->offload_info.format & AUDIO_FORMAT_MAIN_MASK) ==
             AUDIO_FORMAT_PCM) {

            /*Based on platform support, configure appropriate alsa format for corresponding
             *hal input format.
             */
            out->compr_config.codec->format = hal_format_to_alsa(
                                              config->offload_info.format);

            out->hal_op_format = alsa_format_to_hal(
                                                  out->compr_config.codec->format);
            out->hal_ip_format = out->format;

            /*for direct non-compress playback populate bit_width based on selected alsa format as
             *hal input format and alsa format might differ based on platform support.
             */
            out->bit_width = audio_bytes_per_sample(
                             out->hal_op_format) << 3;

            out->compr_config.fragments = DIRECT_PCM_NUM_FRAGMENTS;

            if ((config->offload_info.duration_us >= MIN_OFFLOAD_BUFFER_DURATION_MS * 1000) &&
                   (config->offload_info.duration_us <= MAX_OFFLOAD_BUFFER_DURATION_MS * 1000))
                out->info.duration_us = (int64_t)config->offload_info.duration_us;

            /* Check if alsa session is configured with the same format as HAL input format,
             * if not then derive correct fragment size needed to accomodate the
             * conversion of HAL input format to alsa format.
             */
            audio_extn_utils_update_direct_pcm_fragment_size(out);

            /*if hal input and output fragment size is different this indicates HAL input format is
             *not same as the alsa format
             */
            if (out->hal_fragment_size != out->compr_config.fragment_size) {
                /*Allocate a buffer to convert input data to the alsa configured format.
                 *size of convert buffer is equal to the size required to hold one fragment size
                 *worth of pcm data, this is because flinger does not write more than fragment_size
                 */
                out->convert_buffer = calloc(1,out->compr_config.fragment_size);
                if (out->convert_buffer == NULL){
                    ALOGE("Allocation failed for convert buffer for size %d", out->compr_config.fragment_size);
                    ret = -ENOMEM;
                    goto error_open;
                }
            }
        } else if (audio_extn_passthru_is_passthrough_stream(out)) {
            out->compr_config.fragment_size =
                   audio_extn_passthru_get_buffer_size(&config->offload_info);
            out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
        } else {
            out->compr_config.fragment_size =
                  platform_get_compress_offload_buffer_size(&config->offload_info);
            out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
        }

        if (out->flags & AUDIO_OUTPUT_FLAG_TIMESTAMP) {
            out->compr_config.fragment_size += sizeof(struct snd_codec_metadata);
        }
        if (config->offload_info.format == AUDIO_FORMAT_FLAC)
            out->compr_config.codec->options.flac_dec.sample_size = AUDIO_OUTPUT_BIT_WIDTH;

        if (config->offload_info.format == AUDIO_FORMAT_APTX) {
            audio_extn_send_aptx_dec_bt_addr_to_dsp(out);
        }

        if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
            out->non_blocking = 1;

        if ((flags & AUDIO_OUTPUT_FLAG_TIMESTAMP) &&
            (flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC)) {
            out->render_mode = RENDER_MODE_AUDIO_STC_MASTER;
        } else if(flags & AUDIO_OUTPUT_FLAG_TIMESTAMP) {
            out->render_mode = RENDER_MODE_AUDIO_MASTER;
        } else {
            out->render_mode = RENDER_MODE_AUDIO_NO_TIMESTAMP;
        }

        memset(&out->channel_map_param, 0,
                sizeof(struct audio_out_channel_map_param));

        out->send_new_metadata = 1;
        out->send_next_track_params = false;
        out->is_compr_metadata_avail = false;
        out->offload_state = OFFLOAD_STATE_IDLE;
        out->playback_started = 0;
        out->writeAt.tv_sec = 0;
        out->writeAt.tv_nsec = 0;

        audio_extn_dts_create_state_notifier_node(out->usecase);

        ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
                __func__, config->offload_info.version,
                config->offload_info.bit_rate);

        /* Check if DSD audio format is supported in codec
         * and there is no active native DSD use case
         */

        if ((config->format == AUDIO_FORMAT_DSD) &&
                (!platform_check_codec_dsd_support(adev->platform) ||
                audio_is_dsd_native_stream_active(adev))) {
            ret = -EINVAL;
            goto error_open;
        }

        /* Disable gapless if any of the following is true
         * passthrough playback
         * AV playback
         * non compressed Direct playback
         */
        if (audio_extn_passthru_is_passthrough_stream(out) ||
                (config->format == AUDIO_FORMAT_DSD) ||
                (config->format == AUDIO_FORMAT_IEC61937) ||
                config->offload_info.has_video ||
                !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
            check_and_set_gapless_mode(adev, false);
        } else
            check_and_set_gapless_mode(adev, true);

        if (audio_extn_passthru_is_passthrough_stream(out)) {
            out->flags |= AUDIO_OUTPUT_FLAG_COMPRESS_PASSTHROUGH;
        }
        if (config->format == AUDIO_FORMAT_DSD) {
            out->flags |= AUDIO_OUTPUT_FLAG_COMPRESS_PASSTHROUGH;
            out->compr_config.codec->compr_passthr = PASSTHROUGH_DSD;
        }

        create_offload_callback_thread(out);

    } else if (out->flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) {
          switch (config->sample_rate) {
            case 0:
                out->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
                break;
            case 8000:
            case 16000:
            case 48000:
                out->sample_rate = config->sample_rate;
                break;
            default:
                ALOGE("%s: Unsupported sampling rate %d for Incall Music", __func__,
                      config->sample_rate);
                config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
                ret = -EINVAL;
                goto error_open;
        }
        //FIXME: add support for MONO stream configuration when audioflinger mixer supports it
        switch (config->channel_mask) {
            case AUDIO_CHANNEL_NONE:
            case AUDIO_CHANNEL_OUT_STEREO:
                out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
                break;
            default:
                ALOGE("%s: Unsupported channel mask %#x for Incall Music", __func__,
                      config->channel_mask);
                config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
                ret = -EINVAL;
                goto error_open;
        }
        switch (config->format) {
            case AUDIO_FORMAT_DEFAULT:
            case AUDIO_FORMAT_PCM_16_BIT:
                out->format = AUDIO_FORMAT_PCM_16_BIT;
                break;
            default:
                ALOGE("%s: Unsupported format %#x for Incall Music", __func__,
                      config->format);
                config->format = AUDIO_FORMAT_PCM_16_BIT;
                ret = -EINVAL;
                goto error_open;
        }

        ret = voice_extn_check_and_set_incall_music_usecase(adev, out);
        if (ret != 0) {
            ALOGE("%s: Incall music delivery usecase cannot be set error:%d",
                __func__, ret);
            goto error_open;
        }
    } else if (out->devices == AUDIO_DEVICE_OUT_TELEPHONY_TX) {
        switch (config->sample_rate) {
            case 0:
                out->sample_rate = AFE_PROXY_SAMPLING_RATE;
                break;
            case 8000:
            case 16000:
            case 48000:
                out->sample_rate = config->sample_rate;
                break;
            default:
                ALOGE("%s: Unsupported sampling rate %d for Telephony TX", __func__,
                      config->sample_rate);
                config->sample_rate = AFE_PROXY_SAMPLING_RATE;
                ret = -EINVAL;
                break;
        }
        //FIXME: add support for MONO stream configuration when audioflinger mixer supports it
        switch (config->channel_mask) {
            case AUDIO_CHANNEL_NONE:
                out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
                break;
            case AUDIO_CHANNEL_OUT_STEREO:
                out->channel_mask = config->channel_mask;
                break;
            default:
                ALOGE("%s: Unsupported channel mask %#x for Telephony TX", __func__,
                      config->channel_mask);
                config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
                ret = -EINVAL;
                break;
        }
        switch (config->format) {
            case AUDIO_FORMAT_DEFAULT:
                out->format = AUDIO_FORMAT_PCM_16_BIT;
                break;
            case AUDIO_FORMAT_PCM_16_BIT:
                out->format = config->format;
                break;
            default:
                ALOGE("%s: Unsupported format %#x for Telephony TX", __func__,
                      config->format);
                config->format = AUDIO_FORMAT_PCM_16_BIT;
                ret = -EINVAL;
                break;
        }
        if (ret != 0)
            goto error_open;

        out->usecase = USECASE_AUDIO_PLAYBACK_AFE_PROXY;
        out->config = pcm_config_afe_proxy_playback;
        out->config.rate = out->sample_rate;
        out->config.channels =
                audio_channel_count_from_out_mask(out->channel_mask);
        out->config.format = pcm_format_from_audio_format(out->format);
        adev->voice_tx_output = out;
    } else {
        unsigned int channels = 0;
        /*Update config params to default if not set by the caller*/
        if (config->sample_rate == 0)
            config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
        if (config->channel_mask == AUDIO_CHANNEL_NONE)
            config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
        if (config->format == AUDIO_FORMAT_DEFAULT)
            config->format = AUDIO_FORMAT_PCM_16_BIT;

        channels = audio_channel_count_from_out_mask(out->channel_mask);

        if (out->flags & AUDIO_OUTPUT_FLAG_INTERACTIVE) {
            out->usecase = get_interactive_usecase(adev);
            out->config = pcm_config_low_latency;
        } else if (out->flags & AUDIO_OUTPUT_FLAG_RAW) {
            out->usecase = USECASE_AUDIO_PLAYBACK_ULL;
            out->realtime = may_use_noirq_mode(adev, USECASE_AUDIO_PLAYBACK_ULL,
                                               out->flags);
            out->config = out->realtime ? pcm_config_rt : pcm_config_low_latency;
        } else if (out->flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
            out->usecase = USECASE_AUDIO_PLAYBACK_MMAP;
            out->config = pcm_config_mmap_playback;
            out->stream.start = out_start;
            out->stream.stop = out_stop;
            out->stream.create_mmap_buffer = out_create_mmap_buffer;
            out->stream.get_mmap_position = out_get_mmap_position;
        } else if (out->flags & AUDIO_OUTPUT_FLAG_FAST) {
            out->usecase = USECASE_AUDIO_PLAYBACK_LOW_LATENCY;
            out->hal_output_suspend_supported =
                property_get_bool("vendor.audio.hal.output.suspend.supported", false);
            out->dynamic_pm_qos_config_supported =
                property_get_bool("vendor.audio.hal.dynamic.qos.config.supported", false);
            if (!out->dynamic_pm_qos_config_supported) {
                ALOGI("%s: dynamic qos voting not enabled for platform", __func__);
            } else {
                ALOGI("%s: dynamic qos voting enabled for platform", __func__);
                //the mixer path will be a string similar to "low-latency-playback resume"
                strlcpy(out->pm_qos_mixer_path, use_case_table[out->usecase], MAX_MIXER_PATH_LEN);
                strlcat(out->pm_qos_mixer_path,
                            " resume", MAX_MIXER_PATH_LEN);
                ALOGI("%s: created %s pm_qos_mixer_path" , __func__,
                        out->pm_qos_mixer_path);
            }
            out->config = pcm_config_low_latency;
        } else if (out->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
            out->usecase = USECASE_AUDIO_PLAYBACK_DEEP_BUFFER;
            out->config = pcm_config_deep_buffer;
            out->config.period_size = get_output_period_size(config->sample_rate, out->format,
                                                 channels, DEEP_BUFFER_OUTPUT_PERIOD_DURATION);
            if (out->config.period_size <= 0) {
                ALOGE("Invalid configuration period size is not valid");
                ret = -EINVAL;
                goto error_open;
            }
        } else if (flags & AUDIO_OUTPUT_FLAG_TTS) {
            out->usecase = USECASE_AUDIO_PLAYBACK_TTS;
            out->config = pcm_config_deep_buffer;
        } else if (config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL) {
            out->usecase = USECASE_AUDIO_PLAYBACK_WITH_HAPTICS;
            out->config = pcm_config_haptics_audio;
            if (force_haptic_path)
                adev->haptics_config = pcm_config_haptics_audio;
            else
                adev->haptics_config = pcm_config_haptics;

            out->config.channels =
                audio_channel_count_from_out_mask(out->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL);

            if (force_haptic_path) {
                out->config.channels = 1;
                adev->haptics_config.channels = 1;
            } else
                adev->haptics_config.channels = audio_channel_count_from_out_mask(out->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
        } else if (out->devices & AUDIO_DEVICE_OUT_BUS) {
            ret = audio_extn_auto_hal_open_output_stream(out);
            if (ret) {
                ALOGE("%s: Failed to open output stream for bus device", __func__);
                ret = -EINVAL;
                goto error_open;
            }
        } else {
            /* primary path is the default path selected if no other outputs are available/suitable */
            out->usecase = GET_USECASE_AUDIO_PLAYBACK_PRIMARY(use_db_as_primary);
            out->config = GET_PCM_CONFIG_AUDIO_PLAYBACK_PRIMARY(use_db_as_primary);
        }
        out->hal_ip_format = format = out->format;
        out->config.format = hal_format_to_pcm(out->hal_ip_format);
        out->hal_op_format = pcm_format_to_hal(out->config.format);
        out->bit_width = format_to_bitwidth_table[out->hal_op_format] << 3;
        out->config.rate = config->sample_rate;
        out->sample_rate = out->config.rate;
        out->config.channels = channels;
        if (out->hal_ip_format != out->hal_op_format) {
            uint32_t buffer_size = out->config.period_size *
                                   format_to_bitwidth_table[out->hal_op_format] *
                                   out->config.channels;
            out->convert_buffer = calloc(1, buffer_size);
            if (out->convert_buffer == NULL){
                ALOGE("Allocation failed for convert buffer for size %d",
                       out->compr_config.fragment_size);
                ret = -ENOMEM;
                goto error_open;
            }
            ALOGD("Convert buffer allocated of size %d", buffer_size);
        }
    }

    ALOGV("%s devices:%d, format:%x, out->sample_rate:%d,out->bit_width:%d out->format:%d out->flags:%x, flags: %x usecase %d",
          __func__, devices, format, out->sample_rate, out->bit_width, out->format, out->flags, flags, out->usecase);

    /* TODO remove this hardcoding and check why width is zero*/
    if (out->bit_width == 0)
        out->bit_width = 16;
    audio_extn_utils_update_stream_output_app_type_cfg(adev->platform,
                                                &adev->streams_output_cfg_list,
                                                devices, out->flags, out->hal_op_format, out->sample_rate,
                                                out->bit_width, out->channel_mask, out->profile,
                                                &out->app_type_cfg);
    if ((out->usecase == (audio_usecase_t)(GET_USECASE_AUDIO_PLAYBACK_PRIMARY(use_db_as_primary))) ||
        (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
        /* Ensure the default output is not selected twice */
        if(adev->primary_output == NULL)
            adev->primary_output = out;
        else {
            ALOGE("%s: Primary output is already opened", __func__);
            ret = -EEXIST;
            goto error_open;
        }
    }

    /* Check if this usecase is already existing */
    pthread_mutex_lock(&adev->lock);
    if ((get_usecase_from_list(adev, out->usecase) != NULL) &&
        (out->usecase != USECASE_COMPRESS_VOIP_CALL)) {
        ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
        pthread_mutex_unlock(&adev->lock);
        ret = -EEXIST;
        goto error_open;
    }

    pthread_mutex_unlock(&adev->lock);

    out->stream.common.get_sample_rate = out_get_sample_rate;
    out->stream.common.set_sample_rate = out_set_sample_rate;
    out->stream.common.get_buffer_size = out_get_buffer_size;
    out->stream.common.get_channels = out_get_channels;
    out->stream.common.get_format = out_get_format;
    out->stream.common.set_format = out_set_format;
    out->stream.common.standby = out_standby;
    out->stream.common.dump = out_dump;
    out->stream.common.set_parameters = out_set_parameters;
    out->stream.common.get_parameters = out_get_parameters;
    out->stream.common.add_audio_effect = out_add_audio_effect;
    out->stream.common.remove_audio_effect = out_remove_audio_effect;
    out->stream.get_latency = out_get_latency;
    out->stream.set_volume = out_set_volume;
#ifdef NO_AUDIO_OUT
    out->stream.write = out_write_for_no_output;
#else
    out->stream.write = out_write;
#endif
    out->stream.get_render_position = out_get_render_position;
    out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
    out->stream.get_presentation_position = out_get_presentation_position;

    if (out->realtime)
        out->af_period_multiplier = af_period_multiplier;
    else
        out->af_period_multiplier = 1;

    out->standby = 1;
    /* out->muted = false; by calloc() */
    /* out->written = 0; by calloc() */

    config->format = out->stream.common.get_format(&out->stream.common);
    config->channel_mask = out->stream.common.get_channels(&out->stream.common);
    config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
    register_format(out->format, out->supported_formats);
    register_channel_mask(out->channel_mask, out->supported_channel_masks);
    register_sample_rate(out->sample_rate, out->supported_sample_rates);

    out->error_log = error_log_create(
            ERROR_LOG_ENTRIES,
            1000000000 /* aggregate consecutive identical errors within one second in ns */);

    /*
       By locking output stream before registering, we allow the callback
       to update stream's state only after stream's initial state is set to
       adev state.
    */
    lock_output_stream(out);
    audio_extn_snd_mon_register_listener(out, out_snd_mon_cb);
    pthread_mutex_lock(&adev->lock);
    out->card_status = adev->card_status;
    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&out->lock);

    stream_app_type_cfg_init(&out->app_type_cfg);

    *stream_out = &out->stream;
    ALOGD("%s: Stream (%p) picks up usecase (%s)", __func__, &out->stream,
           use_case_table[out->usecase]);

    if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
        audio_extn_dts_notify_playback_state(out->usecase, 0, out->sample_rate,
                                             popcount(out->channel_mask), out->playback_started);
    /* setup a channel for client <--> adsp communication for stream events */
    is_direct_passthough = audio_extn_passthru_is_direct_passthrough(out);
    if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) ||
            (out->flags & AUDIO_OUTPUT_FLAG_DIRECT_PCM) ||
        audio_extn_ip_hdlr_intf_supported_for_copp(adev->platform) ||
        (audio_extn_ip_hdlr_intf_supported(config->format, is_direct_passthough, false))) {
        hdlr_stream_cfg.pcm_device_id = platform_get_pcm_device_id(
                out->usecase, PCM_PLAYBACK);
        hdlr_stream_cfg.flags = out->flags;
        hdlr_stream_cfg.type = PCM_PLAYBACK;
        ret = audio_extn_adsp_hdlr_stream_open(&out->adsp_hdlr_stream_handle,
                &hdlr_stream_cfg);
        if (ret) {
            ALOGE("%s: adsp_hdlr_stream_open failed %d",__func__, ret);
            out->adsp_hdlr_stream_handle = NULL;
        }
    }
    ip_hdlr_stream = audio_extn_ip_hdlr_intf_supported(config->format,
                                            is_direct_passthough, false);
    ip_hdlr_dev = audio_extn_ip_hdlr_intf_supported_for_copp(adev->platform);
    if (ip_hdlr_stream || ip_hdlr_dev ) {
        ret = audio_extn_ip_hdlr_intf_init(&out->ip_hdlr_handle, NULL, NULL, adev, out->usecase);
        if (ret < 0) {
            ALOGE("%s: audio_extn_ip_hdlr_intf_init failed %d",__func__, ret);
            out->ip_hdlr_handle = NULL;
        }
    }

    streams_output_ctxt_t *out_ctxt = (streams_output_ctxt_t *)
        calloc(1, sizeof(streams_output_ctxt_t));
    if (out_ctxt == NULL) {
        ALOGE("%s fail to allocate output ctxt", __func__);
        ret = -ENOMEM;
        goto error_open;
    }
    out_ctxt->output = out;

    pthread_mutex_lock(&adev->lock);
    list_add_tail(&adev->active_outputs_list, &out_ctxt->list);
    pthread_mutex_unlock(&adev->lock);

    ALOGV("%s: exit", __func__);
    return 0;

error_open:
    if (out->convert_buffer)
        free(out->convert_buffer);
    free(out);
    *stream_out = NULL;
    ALOGD("%s: exit: ret %d", __func__, ret);
    return ret;
}

void adev_close_output_stream(struct audio_hw_device *dev __unused,
                                     struct audio_stream_out *stream)
{
    struct stream_out *out = (struct stream_out *)stream;
    struct audio_device *adev = out->dev;
    int ret = 0;

    ALOGD("%s: enter:stream_handle(%s)",__func__, use_case_table[out->usecase]);

    // must deregister from sndmonitor first to prevent races
    // between the callback and close_stream
    audio_extn_snd_mon_unregister_listener(out);

    /* close adsp hdrl session before standby */
    if (out->adsp_hdlr_stream_handle) {
        ret = audio_extn_adsp_hdlr_stream_close(out->adsp_hdlr_stream_handle);
        if (ret)
            ALOGE("%s: adsp_hdlr_stream_close failed %d",__func__, ret);
        out->adsp_hdlr_stream_handle = NULL;
    }

    if (out->ip_hdlr_handle) {
        audio_extn_ip_hdlr_intf_deinit(out->ip_hdlr_handle);
        out->ip_hdlr_handle = NULL;
    }

    if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
        pthread_mutex_lock(&adev->lock);
        ret = voice_extn_compress_voip_close_output_stream(&stream->common);
        out->started = 0;
        pthread_mutex_unlock(&adev->lock);
        if(ret != 0)
            ALOGE("%s: Compress voip output cannot be closed, error:%d",
                  __func__, ret);
    } else
        out_standby(&stream->common);

    if (is_offload_usecase(out->usecase)) {
        audio_extn_dts_remove_state_notifier_node(out->usecase);
        destroy_offload_callback_thread(out);
        free_offload_usecase(adev, out->usecase);
        if (out->compr_config.codec != NULL)
            free(out->compr_config.codec);
    }

    out->a2dp_compress_mute = false;

    if (is_interactive_usecase(out->usecase))
        free_interactive_usecase(adev, out->usecase);

    if (out->convert_buffer != NULL) {
        free(out->convert_buffer);
        out->convert_buffer = NULL;
    }

    if (adev->voice_tx_output == out)
        adev->voice_tx_output = NULL;

    error_log_destroy(out->error_log);
    out->error_log = NULL;

    if (adev->primary_output == out)
        adev->primary_output = NULL;

    pthread_cond_destroy(&out->cond);
    pthread_mutex_destroy(&out->lock);

    pthread_mutex_lock(&adev->lock);
    streams_output_ctxt_t *out_ctxt = out_get_stream(adev, out->handle);
    if (out_ctxt != NULL) {
        list_remove(&out_ctxt->list);
        free(out_ctxt);
    } else {
        ALOGW("%s, output stream already closed", __func__);
    }
    free(stream);
    pthread_mutex_unlock(&adev->lock);
    ALOGV("%s: exit", __func__);
}

static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
{
    struct audio_device *adev = (struct audio_device *)dev;
    struct str_parms *parms;
    char value[32];
    int val;
    int ret;
    int status = 0;
    bool a2dp_reconfig = false;
    struct listnode *node;
    struct audio_usecase *usecase = NULL;

    ALOGD("%s: enter: %s", __func__, kvpairs);
    parms = str_parms_create_str(kvpairs);

    if (!parms)
        goto error;

    /* notify adev and input/output streams on the snd card status */
    adev_snd_mon_cb((void *)adev, parms);

    list_for_each(node, &adev->active_outputs_list) {
        streams_output_ctxt_t *out_ctxt = node_to_item(node,
                                            streams_output_ctxt_t,
                                            list);
        out_snd_mon_cb((void *)out_ctxt->output, parms);
    }

    list_for_each(node, &adev->active_inputs_list) {
        streams_input_ctxt_t *in_ctxt = node_to_item(node,
                                            streams_input_ctxt_t,
                                            list);
        in_snd_mon_cb((void *)in_ctxt->input, parms);
    }

    pthread_mutex_lock(&adev->lock);
    ret = str_parms_get_str(parms, "BT_SCO", value, sizeof(value));
    if (ret >= 0) {
        /* When set to false, HAL should disable EC and NS */
        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0){
            adev->bt_sco_on = true;
        } else {
            ALOGD("sco is off, reset sco and route device to handset mic");
            adev->bt_sco_on = false;
            audio_extn_sco_reset_configuration();
            list_for_each(node, &adev->usecase_list) {
                usecase = node_to_item(node, struct audio_usecase, list);
                if ((usecase->type == PCM_CAPTURE) && usecase->stream.in &&
                    (usecase->stream.in->device & AUDIO_DEVICE_IN_ALL_SCO))
                    usecase->stream.in->device = AUDIO_DEVICE_IN_BUILTIN_MIC;
                else
                    continue;
                select_devices(adev, usecase->id);
            }
        }
    }

    status = voice_set_parameters(adev, parms);
    if (status != 0)
        goto done;

    status = platform_set_parameters(adev->platform, parms);
    if (status != 0)
        goto done;

    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
    if (ret >= 0) {
        /* When set to false, HAL should disable EC and NS */
        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
            adev->bluetooth_nrec = true;
        else
            adev->bluetooth_nrec = false;
    }

    ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
    if (ret >= 0) {
        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
            adev->screen_off = false;
        else
            adev->screen_off = true;
        audio_extn_sound_trigger_update_screen_status(adev->screen_off);
    }

    ret = str_parms_get_int(parms, "rotation", &val);
    if (ret >= 0) {
        bool reverse_speakers = false;
        int camera_rotation = CAMERA_ROTATION_LANDSCAPE;
        switch (val) {
        // FIXME: note that the code below assumes that the speakers are in the correct placement
        //   relative to the user when the device is rotated 90deg from its default rotation. This
        //   assumption is device-specific, not platform-specific like this code.
        case 270:
            reverse_speakers = true;
            camera_rotation = CAMERA_ROTATION_INVERT_LANDSCAPE;
            break;
        case 0:
        case 180:
            camera_rotation = CAMERA_ROTATION_PORTRAIT;
            break;
        case 90:
            camera_rotation = CAMERA_ROTATION_LANDSCAPE;
            break;
        default:
            ALOGE("%s: unexpected rotation of %d", __func__, val);
            status = -EINVAL;
        }
        if (status == 0) {
            // check and set swap
            //   - check if orientation changed and speaker active
            //   - set rotation and cache the rotation value
            adev->camera_orientation =
                (adev->camera_orientation & ~CAMERA_ROTATION_MASK) | camera_rotation;
            if (!audio_extn_is_maxx_audio_enabled())
                platform_check_and_set_swap_lr_channels(adev, reverse_speakers);
        }
    }

    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value));
    if (ret >= 0) {
        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
            adev->bt_wb_speech_enabled = true;
        else
            adev->bt_wb_speech_enabled = false;
    }

    ret = str_parms_get_str(parms, "bt_swb", value, sizeof(value));
    if (ret >= 0) {
        val = atoi(value);
        adev->swb_speech_mode = val;
    }

    ret = str_parms_get_str(parms, AUDIO_PARAMETER_DEVICE_CONNECT, value, sizeof(value));
    if (ret >= 0) {
        val = atoi(value);
        audio_devices_t device = (audio_devices_t) val;
        if (audio_is_output_device(val) &&
            (val & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
            ALOGV("cache new ext disp type and edid");
            ret = platform_get_ext_disp_type(adev->platform);
            if (ret < 0) {
                ALOGE("%s: Failed to query disp type, ret:%d", __func__, ret);
            } else {
                platform_cache_edid(adev->platform);
            }
        } else if (audio_is_usb_out_device(device) || audio_is_usb_in_device(device)) {
            /*
             * Do not allow AFE proxy port usage by WFD source when USB headset is connected.
             * Per AudioPolicyManager, USB device is higher priority than WFD.
             * For Voice call over USB headset, voice call audio is routed to AFE proxy ports.
             * If WFD use case occupies AFE proxy, it may result unintended behavior while
             * starting voice call on USB
             */
            ret = str_parms_get_str(parms, "card", value, sizeof(value));
            if (ret >= 0)
                audio_extn_usb_add_device(device, atoi(value));

            if (!audio_extn_usb_is_tunnel_supported()) {
                ALOGV("detected USB connect .. disable proxy");
                adev->allow_afe_proxy_usage = false;
            }
        }
    }

    ret = str_parms_get_str(parms, AUDIO_PARAMETER_DEVICE_DISCONNECT, value, sizeof(value));
    if (ret >= 0) {
        val = atoi(value);
        audio_devices_t device = (audio_devices_t) val;
        /*
         * The HDMI / Displayport disconnect handling has been moved to
         * audio extension to ensure that its parameters are not
         * invalidated prior to updating sysfs of the disconnect event
         * Invalidate will be handled by audio_extn_ext_disp_set_parameters()
         */
        if (audio_is_usb_out_device(device) || audio_is_usb_in_device(device)) {
            ret = str_parms_get_str(parms, "card", value, sizeof(value));
            if (ret >= 0)
                audio_extn_usb_remove_device(device, atoi(value));

            if (!audio_extn_usb_is_tunnel_supported()) {
                ALOGV("detected USB disconnect .. enable proxy");
                adev->allow_afe_proxy_usage = true;
            }
        }
        if (audio_is_a2dp_out_device(device)) {
           struct audio_usecase *usecase;
           struct listnode *node;
           list_for_each(node, &adev->usecase_list) {
               usecase = node_to_item(node, struct audio_usecase, list);
               if (PCM_PLAYBACK == usecase->type && usecase->stream.out &&
                  (usecase->stream.out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
                   usecase->stream.out->a2dp_compress_mute) {
                   struct stream_out *out = usecase->stream.out;
                   ALOGD("Unmuting the stream when Bt-A2dp disconnected and stream is mute");
                   out->a2dp_compress_mute = false;
                   out_set_compr_volume(&out->stream, out->volume_l, out->volume_r);
               }
           }
        }
    }

    audio_extn_hfp_set_parameters(adev, parms);
    audio_extn_qdsp_set_parameters(adev, parms);

    status = audio_extn_a2dp_set_parameters(parms, &a2dp_reconfig);
    if (status >= 0 && a2dp_reconfig) {
        struct audio_usecase *usecase;
        struct listnode *node;
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            if (usecase->stream.out && (usecase->type == PCM_PLAYBACK) &&
                (usecase->devices & AUDIO_DEVICE_OUT_ALL_A2DP)){
                ALOGD("reconfigure a2dp... forcing device switch");
                pthread_mutex_unlock(&adev->lock);
                lock_output_stream(usecase->stream.out);
                pthread_mutex_lock(&adev->lock);
                audio_extn_a2dp_set_handoff_mode(true);
                ALOGD("Switching to speaker and muting the stream before select_devices");
                check_a2dp_restore_l(adev, usecase->stream.out, false);
                //force device switch to re configure encoder
                select_devices(adev, usecase->id);
                ALOGD("Unmuting the stream after select_devices");
                usecase->stream.out->a2dp_compress_mute = false;
                out_set_compr_volume(&usecase->stream.out->stream, usecase->stream.out->volume_l, usecase->stream.out->volume_r);
                audio_extn_a2dp_set_handoff_mode(false);
                pthread_mutex_unlock(&usecase->stream.out->lock);
                break;
            }
        }
    }

    //handle vr audio setparam
    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_VR_AUDIO_MODE,
        value, sizeof(value));
    if (ret >= 0) {
        ALOGI("Setting vr mode to be %s", value);
        if (!strncmp(value, "true", 4)) {
            adev->vr_audio_mode_enabled = true;
            ALOGI("Setting vr mode to true");
        } else if (!strncmp(value, "false", 5)) {
            adev->vr_audio_mode_enabled = false;
            ALOGI("Setting vr mode to false");
        } else {
            ALOGI("wrong vr mode set");
        }
    }

    //FIXME: to be replaced by proper video capture properties API
    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_CAMERA_FACING, value, sizeof(value));
    if (ret >= 0) {
        int camera_facing = CAMERA_FACING_BACK;
        if (strcmp(value, AUDIO_PARAMETER_VALUE_FRONT) == 0)
            camera_facing = CAMERA_FACING_FRONT;
        else if (strcmp(value, AUDIO_PARAMETER_VALUE_BACK) == 0)
            camera_facing = CAMERA_FACING_BACK;
        else {
            ALOGW("%s: invalid camera facing value: %s", __func__, value);
            goto done;
        }
        adev->camera_orientation =
                       (adev->camera_orientation & ~CAMERA_FACING_MASK) | camera_facing;
        struct audio_usecase *usecase;
        struct listnode *node;
        list_for_each(node, &adev->usecase_list) {
            usecase = node_to_item(node, struct audio_usecase, list);
            struct stream_in *in = usecase->stream.in;
            if (usecase->type == PCM_CAPTURE && in != NULL &&
                    in->source == AUDIO_SOURCE_CAMCORDER && !in->standby) {
                select_devices(adev, in->usecase);
            }
        }
    }

    audio_extn_set_parameters(adev, parms);
done:
    str_parms_destroy(parms);
    pthread_mutex_unlock(&adev->lock);
error:
    ALOGV("%s: exit with code(%d)", __func__, status);
    return status;
}

static char* adev_get_parameters(const struct audio_hw_device *dev,
                                 const char *keys)
{
    ALOGD("%s:%s", __func__, keys);

    struct audio_device *adev = (struct audio_device *)dev;
    struct str_parms *reply = str_parms_create();
    struct str_parms *query = str_parms_create_str(keys);
    char *str;
    char value[256] = {0};
    int ret = 0;

    if (!query || !reply) {
        if (reply) {
            str_parms_destroy(reply);
        }
        if (query) {
            str_parms_destroy(query);
        }
        ALOGE("adev_get_parameters: failed to create query or reply");
        return NULL;
    }

    //handle vr audio getparam

    ret = str_parms_get_str(query,
        AUDIO_PARAMETER_KEY_VR_AUDIO_MODE,
        value, sizeof(value));

    if (ret >= 0) {
        bool vr_audio_enabled = false;
        pthread_mutex_lock(&adev->lock);
        vr_audio_enabled = adev->vr_audio_mode_enabled;
        pthread_mutex_unlock(&adev->lock);

        ALOGI("getting vr mode to %d", vr_audio_enabled);

        if (vr_audio_enabled) {
            str_parms_add_str(reply, AUDIO_PARAMETER_KEY_VR_AUDIO_MODE,
                "true");
            goto exit;
        } else {
            str_parms_add_str(reply, AUDIO_PARAMETER_KEY_VR_AUDIO_MODE,
                "false");
            goto exit;
        }
    }

    pthread_mutex_lock(&adev->lock);
    audio_extn_get_parameters(adev, query, reply);
    voice_get_parameters(adev, query, reply);
    audio_extn_a2dp_get_parameters(query, reply);
    platform_get_parameters(adev->platform, query, reply);
    pthread_mutex_unlock(&adev->lock);

exit:
    str = str_parms_to_str(reply);
    str_parms_destroy(query);
    str_parms_destroy(reply);

    ALOGD("%s: exit: returns - %s", __func__, str);
    return str;
}

static int adev_init_check(const struct audio_hw_device *dev __unused)
{
    return 0;
}

static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
{
    int ret;
    struct audio_device *adev = (struct audio_device *)dev;

    audio_extn_extspk_set_voice_vol(adev->extspk, volume);

    pthread_mutex_lock(&adev->lock);
    /* cache volume */
    ret = voice_set_volume(adev, volume);
    pthread_mutex_unlock(&adev->lock);
    return ret;
}

static int adev_set_master_volume(struct audio_hw_device *dev __unused,
                                  float volume __unused)
{
    return -ENOSYS;
}

static int adev_get_master_volume(struct audio_hw_device *dev __unused,
                                  float *volume __unused)
{
    return -ENOSYS;
}

static int adev_set_master_mute(struct audio_hw_device *dev __unused,
                                bool muted __unused)
{
    return -ENOSYS;
}

static int adev_get_master_mute(struct audio_hw_device *dev __unused,
                                bool *muted __unused)
{
    return -ENOSYS;
}

static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
{
    struct audio_device *adev = (struct audio_device *)dev;
    struct listnode *node;
    struct audio_usecase *usecase = NULL;
    int ret = 0;

    pthread_mutex_lock(&adev->lock);
    if (adev->mode != mode) {
        ALOGD("%s: mode %d\n", __func__, mode);
        adev->mode = mode;
        if (voice_is_in_call(adev) &&
            (mode == AUDIO_MODE_NORMAL ||
             (mode == AUDIO_MODE_IN_COMMUNICATION && !voice_is_call_state_active(adev)))) {
            list_for_each(node, &adev->usecase_list) {
                usecase = node_to_item(node, struct audio_usecase, list);
                if (usecase->type == VOICE_CALL)
                    break;
            }
            if (usecase &&
                audio_is_usb_out_device(usecase->out_snd_device & AUDIO_DEVICE_OUT_ALL_USB)) {
                ret = audio_extn_usb_check_and_set_svc_int(usecase,
                                                           true);
                if (ret != 0) {
                    /* default service interval was successfully updated,
                       reopen USB backend with new service interval */
                    check_usecases_codec_backend(adev,
                                                 usecase,
                                                 usecase->out_snd_device);
                }
            }

            voice_stop_call(adev);
            platform_set_gsm_mode(adev->platform, false);
            adev->current_call_output = NULL;
            // restore device for other active usecases after stop call
            list_for_each(node, &adev->usecase_list) {
                usecase = node_to_item(node, struct audio_usecase, list);
                select_devices(adev, usecase->id);
            }
        }
    }
    pthread_mutex_unlock(&adev->lock);
    return 0;
}

static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
{
    int ret;
    struct audio_device *adev = (struct audio_device *)dev;

    pthread_mutex_lock(&adev->lock);
    ALOGD("%s state %d\n", __func__, state);
    ret = voice_set_mic_mute((struct audio_device *)dev, state);

    if (adev->ext_hw_plugin)
        ret = audio_extn_ext_hw_plugin_set_mic_mute(adev->ext_hw_plugin, state);

    adev->mic_muted = state;
    pthread_mutex_unlock(&adev->lock);

    return ret;
}

static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
{
    *state = voice_get_mic_mute((struct audio_device *)dev);
    return 0;
}

static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev __unused,
                                         const struct audio_config *config)
{
    int channel_count = audio_channel_count_from_in_mask(config->channel_mask);

    /* Don't know if USB HIFI in this context so use true to be conservative */
    if (check_input_parameters(config->sample_rate, config->format, channel_count,
                               true /*is_usb_hifi */) != 0)
        return 0;

    return get_input_buffer_size(config->sample_rate, config->format, channel_count,
            false /* is_low_latency: since we don't know, be conservative */);
}

static bool adev_input_allow_hifi_record(struct audio_device *adev,
                                         audio_devices_t devices,
                                         audio_input_flags_t flags,
                                         audio_source_t source) {
    const bool allowed = true;

    if (!audio_is_usb_in_device(devices))
        return !allowed;

    switch (flags) {
        case AUDIO_INPUT_FLAG_NONE:
            break;
        case AUDIO_INPUT_FLAG_FAST: // disallow hifi record for FAST as
                                    // it affects RTD numbers over USB
        default:
            return !allowed;
    }

    switch (source) {
        case AUDIO_SOURCE_DEFAULT:
        case AUDIO_SOURCE_MIC:
        case AUDIO_SOURCE_UNPROCESSED:
            break;
        default:
            return !allowed;
    }

    switch (adev->mode) {
        case 0:
            break;
        default:
            return !allowed;
    }

    return allowed;
}

static int adev_update_voice_comm_input_stream(struct stream_in *in,
                                               struct audio_config *config)
{
    bool valid_rate = (config->sample_rate == 8000 ||
                       config->sample_rate == 16000 ||
                       config->sample_rate == 32000 ||
                       config->sample_rate == 48000);
    bool valid_ch = audio_channel_count_from_in_mask(in->channel_mask) == 1;

    if(!voice_extn_is_compress_voip_supported()) {
        if (valid_rate && valid_ch) {
        in->usecase = USECASE_AUDIO_RECORD_VOIP;
        in->config = default_pcm_config_voip_copp;
        in->config.period_size = VOIP_IO_BUF_SIZE(in->sample_rate,
                                                  DEFAULT_VOIP_BUF_DURATION_MS,
                                                  DEFAULT_VOIP_BIT_DEPTH_BYTE)/2;
        } else {
            ALOGW("%s No valid input in voip, use defaults"
                   "sample rate %u, channel mask 0x%X",
                   __func__, config->sample_rate, in->channel_mask);
        }
        in->config.rate = config->sample_rate;
        in->sample_rate = config->sample_rate;
    } else {
        //XXX needed for voice_extn_compress_voip_open_input_stream
        in->config.rate = config->sample_rate;
        if ((in->dev->mode == AUDIO_MODE_IN_COMMUNICATION ||
             in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
             voice_extn_compress_voip_is_active(in->dev)) &&
            (voice_extn_compress_voip_is_format_supported(in->format)) &&
            valid_rate && valid_ch) {
            voice_extn_compress_voip_open_input_stream(in);
            // update rate entries to match config from AF
            in->config.rate = config->sample_rate;
            in->sample_rate = config->sample_rate;
        } else {
            ALOGW("%s compress voip not active, use defaults", __func__);
        }
    }
    return 0;
}

static int adev_open_input_stream(struct audio_hw_device *dev,
                                  audio_io_handle_t handle,
                                  audio_devices_t devices,
                                  struct audio_config *config,
                                  struct audio_stream_in **stream_in,
                                  audio_input_flags_t flags,
                                  const char *address __unused,
                                  audio_source_t source)
{
    struct audio_device *adev = (struct audio_device *)dev;
    struct stream_in *in;
    int ret = 0, buffer_size, frame_size;
    int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
    bool is_low_latency = false;
    bool channel_mask_updated = false;
    bool is_usb_dev = audio_is_usb_in_device(devices);
    bool may_use_hifi_record = adev_input_allow_hifi_record(adev,
                                                            devices,
                                                            flags,
                                                            source);
    ALOGV("%s: enter: flags %#x, is_usb_dev %d, may_use_hifi_record %d,"
            " sample_rate %u, channel_mask %#x, format %#x",
            __func__, flags, is_usb_dev, may_use_hifi_record,
            config->sample_rate, config->channel_mask, config->format);

    if (is_usb_dev && (!audio_extn_usb_connected(NULL))) {
        is_usb_dev = false;
        devices = AUDIO_DEVICE_IN_BUILTIN_MIC;
        ALOGW("%s: ignore set device to non existing USB card, use input device(%#x)",
              __func__, devices);
    }

    *stream_in = NULL;

    if (!(is_usb_dev && may_use_hifi_record)) {
        if (config->sample_rate == 0)
            config->sample_rate = 48000;
        if (config->channel_mask == AUDIO_CHANNEL_NONE)
            config->channel_mask = AUDIO_CHANNEL_IN_MONO;
        if (config->format == AUDIO_FORMAT_DEFAULT)
            config->format = AUDIO_FORMAT_PCM_16_BIT;

        channel_count = audio_channel_count_from_in_mask(config->channel_mask);

        if (check_input_parameters(config->sample_rate, config->format, channel_count,
                                   false) != 0)
            return -EINVAL;
    }

    pthread_mutex_lock(&adev->lock);
    if (in_get_stream(adev, handle) != NULL) {
        ALOGW("%s, input stream already opened", __func__);
        ret = -EEXIST;
    }
    pthread_mutex_unlock(&adev->lock);
    if (ret)
        return ret;

    in = (struct stream_in *)calloc(1, sizeof(struct stream_in));

    if (!in) {
        ALOGE("failed to allocate input stream");
        return -ENOMEM;
    }

    ALOGD("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x)\
        stream_handle(%p) io_handle(%d) source(%d) format %x",__func__, config->sample_rate,
        config->channel_mask, devices, &in->stream, handle, source, config->format);
    pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
    pthread_mutex_init(&in->pre_lock, (const pthread_mutexattr_t *) NULL);

    in->stream.common.get_sample_rate = in_get_sample_rate;
    in->stream.common.set_sample_rate = in_set_sample_rate;
    in->stream.common.get_buffer_size = in_get_buffer_size;
    in->stream.common.get_channels = in_get_channels;
    in->stream.common.get_format = in_get_format;
    in->stream.common.set_format = in_set_format;
    in->stream.common.standby = in_standby;
    in->stream.common.dump = in_dump;
    in->stream.common.set_parameters = in_set_parameters;
    in->stream.common.get_parameters = in_get_parameters;
    in->stream.common.add_audio_effect = in_add_audio_effect;
    in->stream.common.remove_audio_effect = in_remove_audio_effect;
    in->stream.set_gain = in_set_gain;
    in->stream.read = in_read;
    in->stream.get_input_frames_lost = in_get_input_frames_lost;
    in->stream.get_capture_position = in_get_capture_position;
    in->stream.get_active_microphones = in_get_active_microphones;
    in->stream.set_microphone_direction = in_set_microphone_direction;
    in->stream.set_microphone_field_dimension = in_set_microphone_field_dimension;
    in->stream.update_sink_metadata = in_update_sink_metadata;

    in->device = devices;
    in->source = source;
    in->dev = adev;
    in->standby = 1;
    in->capture_handle = handle;
    in->flags = flags;
    in->bit_width = 16;
    in->af_period_multiplier = 1;
    in->direction = MIC_DIRECTION_UNSPECIFIED;
    in->zoom = 0;
    list_init(&in->aec_list);
    list_init(&in->ns_list);

    ALOGV("%s: source %d, config->channel_mask %#x", __func__, source, config->channel_mask);
    if (source == AUDIO_SOURCE_VOICE_UPLINK ||
        source == AUDIO_SOURCE_VOICE_DOWNLINK) {
        /* Force channel config requested to mono if incall
           record is being requested for only uplink/downlink */
        if (config->channel_mask != AUDIO_CHANNEL_IN_MONO) {
            config->channel_mask = AUDIO_CHANNEL_IN_MONO;
            ret = -EINVAL;
            goto err_open;
        }
    }

    if (is_usb_dev && may_use_hifi_record) {
        /* HiFi record selects an appropriate format, channel, rate combo
           depending on sink capabilities*/
        ret = read_usb_sup_params_and_compare(false /*is_playback*/,
                                              &config->format,
                                              &in->supported_formats[0],
                                              MAX_SUPPORTED_FORMATS,
                                              &config->channel_mask,
                                              &in->supported_channel_masks[0],
                                              MAX_SUPPORTED_CHANNEL_MASKS,
                                              &config->sample_rate,
                                              &in->supported_sample_rates[0],
                                              MAX_SUPPORTED_SAMPLE_RATES);
        if (ret != 0) {
            ret = -EINVAL;
            goto err_open;
        }
        channel_count = audio_channel_count_from_in_mask(config->channel_mask);
    } else if (config->format == AUDIO_FORMAT_DEFAULT) {
        config->format = AUDIO_FORMAT_PCM_16_BIT;
    } else if (property_get_bool("vendor.audio.capture.pcm.32bit.enable", false)
                                 && config->format == AUDIO_FORMAT_PCM_32_BIT) {
            in->config.format = PCM_FORMAT_S32_LE;
            in->bit_width = 32;
    } else if ((config->format == AUDIO_FORMAT_PCM_FLOAT) ||
               (config->format == AUDIO_FORMAT_PCM_32_BIT) ||
               (config->format == AUDIO_FORMAT_PCM_24_BIT_PACKED) ||
               (config->format == AUDIO_FORMAT_PCM_8_24_BIT)) {
        bool ret_error = false;
        in->bit_width = 24;
        /* 24 bit is restricted to UNPROCESSED source only,also format supported
           from HAL is 24_packed and 8_24
         *> In case of UNPROCESSED source, for 24 bit, if format requested is other than
            24_packed return error indicating supported format is 24_packed
         *> In case of any other source requesting 24 bit or float return error
            indicating format supported is 16 bit only.

            on error flinger will retry with supported format passed
         */
        if ((source != AUDIO_SOURCE_UNPROCESSED) &&
            (source != AUDIO_SOURCE_CAMCORDER)) {
            config->format = AUDIO_FORMAT_PCM_16_BIT;
            if (config->sample_rate > 48000)
                config->sample_rate = 48000;
            ret_error = true;
        } else if (!(config->format == AUDIO_FORMAT_PCM_24_BIT_PACKED ||
                     config->format == AUDIO_FORMAT_PCM_8_24_BIT)) {
            config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
            ret_error = true;
        }

        if (ret_error) {
            ret = -EINVAL;
            goto err_open;
        }
    }

    in->channel_mask = config->channel_mask;
    in->format = config->format;

    in->usecase = USECASE_AUDIO_RECORD;

    if (in->source == AUDIO_SOURCE_FM_TUNER) {
        if(!get_usecase_from_list(adev, USECASE_AUDIO_RECORD_FM_VIRTUAL))
            in->usecase = USECASE_AUDIO_RECORD_FM_VIRTUAL;
        else {
            ret = -EINVAL;
            goto err_open;
        }
    }

    if (config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE &&
            (flags & AUDIO_INPUT_FLAG_TIMESTAMP) == 0 &&
            (flags & AUDIO_INPUT_FLAG_COMPRESS) == 0 &&
            (flags & AUDIO_INPUT_FLAG_FAST) != 0) {
        is_low_latency = true;
#if LOW_LATENCY_CAPTURE_USE_CASE
        in->usecase = USECASE_AUDIO_RECORD_LOW_LATENCY;
#endif
        in->realtime = may_use_noirq_mode(adev, in->usecase, in->flags);
        if (!in->realtime) {
            in->config = pcm_config_audio_capture;
            frame_size = audio_stream_in_frame_size(&in->stream);
            buffer_size = get_input_buffer_size(config->sample_rate,
                                                config->format,
                                                channel_count,
                                                is_low_latency);
            in->config.period_size = buffer_size / frame_size;
            in->config.rate = config->sample_rate;
            in->af_period_multiplier = 1;
        } else {
            // period size is left untouched for rt mode playback
            in->config = pcm_config_audio_capture_rt;
            in->af_period_multiplier = af_period_multiplier;
        }
    }

    if ((config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE) &&
               ((in->flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0)) {
        in->realtime = 0;
        in->usecase = USECASE_AUDIO_RECORD_MMAP;
        in->config = pcm_config_mmap_capture;
        in->config.format = pcm_format_from_audio_format(config->format);
        in->stream.start = in_start;
        in->stream.stop = in_stop;
        in->stream.create_mmap_buffer = in_create_mmap_buffer;
        in->stream.get_mmap_position = in_get_mmap_position;
        ALOGV("%s: USECASE_AUDIO_RECORD_MMAP", __func__);
    } else if (in->realtime) {
        in->config = pcm_config_audio_capture_rt;
        in->config.format = pcm_format_from_audio_format(config->format);
        in->af_period_multiplier = af_period_multiplier;
    } else if (is_usb_dev && may_use_hifi_record) {
        in->usecase = USECASE_AUDIO_RECORD_HIFI;
        in->config = pcm_config_audio_capture;
        frame_size = audio_stream_in_frame_size(&in->stream);
        buffer_size = get_input_buffer_size(config->sample_rate,
                                            config->format,
                                            channel_count,
                                            false /*is_low_latency*/);
        in->config.period_size = buffer_size / frame_size;
        in->config.rate = config->sample_rate;
        in->config.format = pcm_format_from_audio_format(config->format);
        switch (config->format) {
        case AUDIO_FORMAT_PCM_32_BIT:
            in->bit_width = 32;
            break;
        case AUDIO_FORMAT_PCM_24_BIT_PACKED:
        case AUDIO_FORMAT_PCM_8_24_BIT:
            in->bit_width = 24;
            break;
        default:
            in->bit_width = 16;
        }
    } else if ((in->device == AUDIO_DEVICE_IN_TELEPHONY_RX) ||
             (in->device == AUDIO_DEVICE_IN_PROXY)) {
        if (config->sample_rate == 0)
            config->sample_rate = AFE_PROXY_SAMPLING_RATE;
        if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
                config->sample_rate != 8000) {
            config->sample_rate = AFE_PROXY_SAMPLING_RATE;
            ret = -EINVAL;
            goto err_open;
        }
        if (config->format == AUDIO_FORMAT_DEFAULT)
            config->format = AUDIO_FORMAT_PCM_16_BIT;
        if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
            config->format = AUDIO_FORMAT_PCM_16_BIT;
            ret = -EINVAL;
            goto err_open;
        }

        in->usecase = USECASE_AUDIO_RECORD_AFE_PROXY;
        in->config = pcm_config_afe_proxy_record;
        in->config.rate = config->sample_rate;
        in->af_period_multiplier = 1;
    } else if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
               in->flags & AUDIO_INPUT_FLAG_VOIP_TX &&
               (config->sample_rate == 8000 ||
                config->sample_rate == 16000 ||
                config->sample_rate == 32000 ||
                config->sample_rate == 48000) &&
               channel_count == 1) {
        in->usecase = USECASE_AUDIO_RECORD_VOIP;
        in->config = pcm_config_audio_capture;
        frame_size = audio_stream_in_frame_size(&in->stream);
        buffer_size = get_stream_buffer_size(VOIP_CAPTURE_PERIOD_DURATION_MSEC,
                                             config->sample_rate,
                                             config->format,
                                             channel_count, false /*is_low_latency*/);
        in->config.period_size = buffer_size / frame_size;
        in->config.period_count = VOIP_CAPTURE_PERIOD_COUNT;
        in->config.rate = config->sample_rate;
        in->af_period_multiplier = 1;
    } else {
        int ret_val;
        pthread_mutex_lock(&adev->lock);
        ret_val = audio_extn_check_and_set_multichannel_usecase(adev,
               in, config, &channel_mask_updated);
        pthread_mutex_unlock(&adev->lock);

        if (!ret_val) {
           if (channel_mask_updated == true) {
               ALOGD("%s: return error to retry with updated channel mask (%#x)",
                   __func__, config->channel_mask);
               ret = -EINVAL;
               goto err_open;
           }
           ALOGD("%s: created multi-channel session succesfully",__func__);
        } else if (audio_extn_compr_cap_enabled() &&
                   audio_extn_compr_cap_format_supported(config->format) &&
                   (in->dev->mode != AUDIO_MODE_IN_COMMUNICATION)) {
            audio_extn_compr_cap_init(in);
        } else if (audio_extn_cin_applicable_stream(in)) {
            ret = audio_extn_cin_configure_input_stream(in, config);
            if (ret)
                goto err_open;
        } else {
            in->config = pcm_config_audio_capture;
            in->config.rate = config->sample_rate;
            in->config.format = pcm_format_from_audio_format(config->format);
            in->format = config->format;
            frame_size = audio_stream_in_frame_size(&in->stream);
            buffer_size = get_input_buffer_size(config->sample_rate,
                                            config->format,
                                            channel_count,
                                            is_low_latency);
            /* prevent division-by-zero */
            if (frame_size == 0) {
                ALOGE("%s: Error frame_size==0", __func__);
                ret = -EINVAL;
                goto err_open;
            }

            in->config.period_size = buffer_size / frame_size;
            in->af_period_multiplier = 1;

            if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
                /* optionally use VOIP usecase depending on config(s) */
                ret = adev_update_voice_comm_input_stream(in, config);
            }

            if (ret) {
                ALOGE("%s AUDIO_SOURCE_VOICE_COMMUNICATION invalid args", __func__);
                goto err_open;
            }
        }
        if (audio_extn_is_concurrent_capture_enabled()) {
            /* Acquire lock to avoid two concurrent use cases initialized to
               same pcm record use case */

            if (in->usecase == USECASE_AUDIO_RECORD) {
                pthread_mutex_lock(&adev->lock);
                if (!(adev->pcm_record_uc_state)) {
                    ALOGV("%s: using USECASE_AUDIO_RECORD",__func__);
                    adev->pcm_record_uc_state = 1;
                    pthread_mutex_unlock(&adev->lock);
                } else {
                    pthread_mutex_unlock(&adev->lock);
                    /* Assign compress record use case for second record */
                    in->usecase = USECASE_AUDIO_RECORD_COMPRESS2;
                    in->flags |= AUDIO_INPUT_FLAG_COMPRESS;
                    ALOGV("%s: overriding usecase with USECASE_AUDIO_RECORD_COMPRESS2 and appending compress flag", __func__);
                    if (audio_extn_cin_applicable_stream(in)) {
                        in->sample_rate = config->sample_rate;
                        ret = audio_extn_cin_configure_input_stream(in, config);
                        if (ret)
                            goto err_open;
                    }
                }
            }
        }
    }
    if (audio_extn_ssr_get_stream() != in)
        in->config.channels = channel_count;

    in->sample_rate  = in->config.rate;

    audio_extn_utils_update_stream_input_app_type_cfg(adev->platform,
                                                &adev->streams_input_cfg_list,
                                                devices, flags, in->format,
                                                in->sample_rate, in->bit_width,
                                                in->profile, &in->app_type_cfg);
    register_format(in->format, in->supported_formats);
    register_channel_mask(in->channel_mask, in->supported_channel_masks);
    register_sample_rate(in->sample_rate, in->supported_sample_rates);

    in->error_log = error_log_create(
            ERROR_LOG_ENTRIES,
            1000000000 /* aggregate consecutive identical errors within one second */);

    /* This stream could be for sound trigger lab,
       get sound trigger pcm if present */
    audio_extn_sound_trigger_check_and_get_session(in);

    lock_input_stream(in);
    audio_extn_snd_mon_register_listener(in, in_snd_mon_cb);
    pthread_mutex_lock(&adev->lock);
    in->card_status = adev->card_status;
    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&in->lock);

    stream_app_type_cfg_init(&in->app_type_cfg);

    *stream_in = &in->stream;

    streams_input_ctxt_t *in_ctxt = (streams_input_ctxt_t *)
        calloc(1, sizeof(streams_input_ctxt_t));
    if (in_ctxt == NULL) {
        ALOGE("%s fail to allocate input ctxt", __func__);
        ret = -ENOMEM;
        goto err_open;
    }
    in_ctxt->input = in;

    pthread_mutex_lock(&adev->lock);
    list_add_tail(&adev->active_inputs_list, &in_ctxt->list);
    pthread_mutex_unlock(&adev->lock);

    ALOGV("%s: exit", __func__);
    return ret;

err_open:
    if (in->usecase == USECASE_AUDIO_RECORD) {
        pthread_mutex_lock(&adev->lock);
        adev->pcm_record_uc_state = 0;
        pthread_mutex_unlock(&adev->lock);
    }
    free(in);
    *stream_in = NULL;
    return ret;
}

static void adev_close_input_stream(struct audio_hw_device *dev,
                                    struct audio_stream_in *stream)
{
    int ret;
    struct stream_in *in = (struct stream_in *)stream;
    struct audio_device *adev = (struct audio_device *)dev;

    ALOGD("%s: enter:stream_handle(%p)",__func__, in);

    /* must deregister from sndmonitor first to prevent races
     * between the callback and close_stream
     */
    audio_extn_snd_mon_unregister_listener(stream);

    /* Disable echo reference if there are no active input, hfp call
     * and sound trigger while closing input stream
     */
    if (adev_get_active_input(adev) == NULL &&
        !audio_extn_hfp_is_active(adev) &&
        !audio_extn_sound_trigger_check_ec_ref_enable())
        platform_set_echo_reference(adev, false, AUDIO_DEVICE_NONE);
    else
        audio_extn_sound_trigger_update_ec_ref_status(false);

    if (in == NULL) {
        ALOGE("%s: audio_stream_in ptr is NULL", __func__);
        return;
    }
    error_log_destroy(in->error_log);
    in->error_log = NULL;


    if (in->usecase == USECASE_COMPRESS_VOIP_CALL) {
        pthread_mutex_lock(&adev->lock);
        ret = voice_extn_compress_voip_close_input_stream(&stream->common);
        pthread_mutex_unlock(&adev->lock);
        if (ret != 0)
            ALOGE("%s: Compress voip input cannot be closed, error:%d",
                  __func__, ret);
    } else
        in_standby(&stream->common);

    pthread_mutex_lock(&adev->lock);
    if (in->usecase == USECASE_AUDIO_RECORD) {
        adev->pcm_record_uc_state = 0;
    }

    if (audio_extn_ssr_get_stream() == in) {
        audio_extn_ssr_deinit();
    }

    if (audio_extn_ffv_get_stream() == in) {
        audio_extn_ffv_stream_deinit();
    }

    if (audio_extn_compr_cap_enabled() &&
            audio_extn_compr_cap_format_supported(in->config.format))
        audio_extn_compr_cap_deinit();

    if (audio_extn_cin_attached_usecase(in->usecase))
        audio_extn_cin_free_input_stream_resources(in);

    if (in->is_st_session) {
        ALOGV("%s: sound trigger pcm stop lab", __func__);
        audio_extn_sound_trigger_stop_lab(in);
    }
    streams_input_ctxt_t *in_ctxt = in_get_stream(adev, in->capture_handle);
    if (in_ctxt != NULL) {
        list_remove(&in_ctxt->list);
        free(in_ctxt);
    } else {
        ALOGW("%s, input stream already closed", __func__);
    }
    free(stream);
    pthread_mutex_unlock(&adev->lock);
    return;
}

/* verifies input and output devices and their capabilities.
 *
 * This verification is required when enabling extended bit-depth or
 * sampling rates, as not all qcom products support it.
 *
 * Suitable for calling only on initialization such as adev_open().
 * It fills the audio_device use_case_table[] array.
 *
 * Has a side-effect that it needs to configure audio routing / devices
 * in order to power up the devices and read the device parameters.
 * It does not acquire any hw device lock. Should restore the devices
 * back to "normal state" upon completion.
 */
static int adev_verify_devices(struct audio_device *adev)
{
    /* enumeration is a bit difficult because one really wants to pull
     * the use_case, device id, etc from the hidden pcm_device_table[].
     * In this case there are the following use cases and device ids.
     *
     * [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = {0, 0},
     * [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = {15, 15},
     * [USECASE_AUDIO_PLAYBACK_HIFI] = {1, 1},
     * [USECASE_AUDIO_PLAYBACK_OFFLOAD] = {9, 9},
     * [USECASE_AUDIO_RECORD] = {0, 0},
     * [USECASE_AUDIO_RECORD_LOW_LATENCY] = {15, 15},
     * [USECASE_VOICE_CALL] = {2, 2},
     *
     * USECASE_AUDIO_PLAYBACK_OFFLOAD, USECASE_AUDIO_PLAYBACK_HIFI omitted.
     * USECASE_VOICE_CALL omitted, but possible for either input or output.
     */

    /* should be the usecases enabled in adev_open_input_stream() */
    static const int test_in_usecases[] = {
             USECASE_AUDIO_RECORD,
             USECASE_AUDIO_RECORD_LOW_LATENCY, /* does not appear to be used */
    };
    /* should be the usecases enabled in adev_open_output_stream()*/
    static const int test_out_usecases[] = {
            USECASE_AUDIO_PLAYBACK_DEEP_BUFFER,
            USECASE_AUDIO_PLAYBACK_LOW_LATENCY,
    };
    static const usecase_type_t usecase_type_by_dir[] = {
            PCM_PLAYBACK,
            PCM_CAPTURE,
    };
    static const unsigned flags_by_dir[] = {
            PCM_OUT,
            PCM_IN,
    };

    size_t i;
    unsigned dir;
    const unsigned card_id = adev->snd_card;

    for (dir = 0; dir < 2; ++dir) {
        const usecase_type_t usecase_type = usecase_type_by_dir[dir];
        const unsigned flags_dir = flags_by_dir[dir];
        const size_t testsize =
                dir ? ARRAY_SIZE(test_in_usecases) : ARRAY_SIZE(test_out_usecases);
        const int *testcases =
                dir ? test_in_usecases : test_out_usecases;
        const audio_devices_t audio_device =
                dir ? AUDIO_DEVICE_IN_BUILTIN_MIC : AUDIO_DEVICE_OUT_SPEAKER;

        for (i = 0; i < testsize; ++i) {
            const audio_usecase_t audio_usecase = testcases[i];
            int device_id;
            struct pcm_params **pparams;
            struct stream_out out;
            struct stream_in in;
            struct audio_usecase uc_info;
            int retval;

            pparams = &adev->use_case_table[audio_usecase];
            pcm_params_free(*pparams); /* can accept null input */
            *pparams = NULL;

            /* find the device ID for the use case (signed, for error) */
            device_id = platform_get_pcm_device_id(audio_usecase, usecase_type);
            if (device_id < 0)
                continue;

            /* prepare structures for device probing */
            memset(&uc_info, 0, sizeof(uc_info));
            uc_info.id = audio_usecase;
            uc_info.type = usecase_type;
            if (dir) {
                memset(&in, 0, sizeof(in));
                in.device = audio_device;
                in.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
                uc_info.stream.in = &in;
            }
            memset(&out, 0, sizeof(out));
            out.devices = audio_device; /* only field needed in select_devices */
            uc_info.stream.out = &out;
            uc_info.devices = audio_device;
            uc_info.in_snd_device = SND_DEVICE_NONE;
            uc_info.out_snd_device = SND_DEVICE_NONE;
            list_add_tail(&adev->usecase_list, &uc_info.list);

            /* select device - similar to start_(in/out)put_stream() */
            retval = select_devices(adev, audio_usecase);
            if (retval >= 0) {
                *pparams = pcm_params_get(card_id, device_id, flags_dir);
#if LOG_NDEBUG == 0
                char info[512]; /* for possible debug info */
                if (*pparams) {
                    ALOGV("%s: (%s) card %d  device %d", __func__,
                            dir ? "input" : "output", card_id, device_id);
                    pcm_params_to_string(*pparams, info, ARRAY_SIZE(info));
                } else {
                    ALOGV("%s: cannot locate card %d  device %d", __func__, card_id, device_id);
                }
#endif
            }

            /* deselect device - similar to stop_(in/out)put_stream() */
            /* 1. Get and set stream specific mixer controls */
            retval = disable_audio_route(adev, &uc_info);
            /* 2. Disable the rx device */
            retval = disable_snd_device(adev,
                    dir ? uc_info.in_snd_device : uc_info.out_snd_device);
            list_remove(&uc_info.list);
        }
    }
    return 0;
}

int adev_create_audio_patch(struct audio_hw_device *dev,
                            unsigned int num_sources,
                            const struct audio_port_config *sources,
                            unsigned int num_sinks,
                            const struct audio_port_config *sinks,
                            audio_patch_handle_t *handle)
{
    int ret;

    ret = audio_extn_hw_loopback_create_audio_patch(dev,
                                        num_sources,
                                        sources,
                                        num_sinks,
                                        sinks,
                                        handle);
    ret |= audio_extn_auto_hal_create_audio_patch(dev,
                                        num_sources,
                                        sources,
                                        num_sinks,
                                        sinks,
                                        handle);
    return ret;
}

int adev_release_audio_patch(struct audio_hw_device *dev,
                           audio_patch_handle_t handle)
{
    int ret;

    ret = audio_extn_hw_loopback_release_audio_patch(dev, handle);
    ret |= audio_extn_auto_hal_release_audio_patch(dev, handle);
    return ret;
}

int adev_get_audio_port(struct audio_hw_device *dev, struct audio_port *config)
{
    int ret = 0;

    ret = audio_extn_hw_loopback_get_audio_port(dev, config);
    ret |= audio_extn_auto_hal_get_audio_port(dev, config);
    return ret;
}

int adev_set_audio_port_config(struct audio_hw_device *dev,
                        const struct audio_port_config *config)
{
    int ret = 0;

    ret = audio_extn_hw_loopback_set_audio_port_config(dev, config);
    ret |= audio_extn_auto_hal_set_audio_port_config(dev, config);
    return ret;
}

static int adev_dump(const audio_hw_device_t *device __unused,
                     int fd __unused)
{
    return 0;
}

static int adev_close(hw_device_t *device)
{
    size_t i;
    struct audio_device *adev_temp = (struct audio_device *)device;

    if (!adev_temp)
        return 0;

    pthread_mutex_lock(&adev_init_lock);

    if ((--audio_device_ref_count) == 0) {
         if (audio_extn_spkr_prot_is_enabled())
             audio_extn_spkr_prot_deinit();
        audio_extn_snd_mon_unregister_listener(adev);
        audio_extn_sound_trigger_deinit(adev);
        audio_extn_listen_deinit(adev);
        audio_extn_qdsp_deinit();
        audio_extn_extspk_deinit(adev->extspk);
        audio_extn_utils_release_streams_cfg_lists(
                      &adev->streams_output_cfg_list,
                      &adev->streams_input_cfg_list);
        if (audio_extn_qap_is_enabled())
            audio_extn_qap_deinit();
        if (audio_extn_qaf_is_enabled())
            audio_extn_qaf_deinit();
        audio_route_free(adev->audio_route);
        audio_extn_gef_deinit(adev);
        free(adev->snd_dev_ref_cnt);
        platform_deinit(adev->platform);
        for (i = 0; i < ARRAY_SIZE(adev->use_case_table); ++i) {
            pcm_params_free(adev->use_case_table[i]);
        }
        if (adev->adm_deinit)
            adev->adm_deinit(adev->adm_data);
        qahwi_deinit(device);
        audio_extn_adsp_hdlr_deinit();
        audio_extn_snd_mon_deinit();
        audio_extn_hw_loopback_deinit(adev);
        audio_extn_ffv_deinit();
        if (adev->device_cfg_params) {
            free(adev->device_cfg_params);
            adev->device_cfg_params = NULL;
        }
        if(adev->ext_hw_plugin)
            audio_extn_ext_hw_plugin_deinit(adev->ext_hw_plugin);
        audio_extn_auto_hal_deinit();
        free(device);
        adev = NULL;
    }
    pthread_mutex_unlock(&adev_init_lock);
    enable_gcov();
    return 0;
}

/* This returns 1 if the input parameter looks at all plausible as a low latency period size,
 * or 0 otherwise.  A return value of 1 doesn't mean the value is guaranteed to work,
 * just that it _might_ work.
 */
static int period_size_is_plausible_for_low_latency(int period_size)
{
    switch (period_size) {
    case 160:
    case 192:
    case 240:
    case 320:
    case 480:
        return 1;
    default:
        return 0;
    }
}

static void adev_snd_mon_cb(void *cookie, struct str_parms *parms)
{
    bool is_snd_card_status = false;
    bool is_ext_device_status = false;
    char value[32];
    int card = -1;
    card_status_t status;

    if (cookie != adev || !parms)
        return;

    if (!parse_snd_card_status(parms, &card, &status)) {
        is_snd_card_status = true;
    } else if (0 < str_parms_get_str(parms, "ext_audio_device", value, sizeof(value))) {
        is_ext_device_status = true;
    } else {
        // not a valid event
        return;
    }

    pthread_mutex_lock(&adev->lock);
    if (card == adev->snd_card || is_ext_device_status) {
        if (is_snd_card_status && adev->card_status != status) {
            adev->card_status = status;
            platform_snd_card_update(adev->platform, status);
            audio_extn_fm_set_parameters(adev, parms);
            audio_extn_auto_hal_set_parameters(adev, parms);
        } else if (is_ext_device_status) {
            platform_set_parameters(adev->platform, parms);
        }
    }
    pthread_mutex_unlock(&adev->lock);
    return;
}

/* out and adev lock held */
static int check_a2dp_restore_l(struct audio_device *adev, struct stream_out *out, bool restore)
{
    struct audio_usecase *uc_info;
    float left_p;
    float right_p;
    audio_devices_t devices;

    uc_info = get_usecase_from_list(adev, out->usecase);
    if (uc_info == NULL) {
        ALOGE("%s: Could not find the usecase (%d) in the list",
              __func__, out->usecase);
        return -EINVAL;
    }

    ALOGD("%s: enter: usecase(%d: %s)", __func__,
          out->usecase, use_case_table[out->usecase]);

    if (restore) {
        // restore A2DP device for active usecases and unmute if required
        if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
            (uc_info->out_snd_device != SND_DEVICE_OUT_BT_A2DP)) {
            ALOGD("%s: restoring A2dp and unmuting stream", __func__);
            select_devices(adev, uc_info->id);
            pthread_mutex_lock(&out->compr_mute_lock);
            if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
                (out->a2dp_compress_mute) && (uc_info->out_snd_device == SND_DEVICE_OUT_BT_A2DP)) {
                out->a2dp_compress_mute = false;
                out_set_compr_volume(&out->stream, out->volume_l, out->volume_r);
            }
            pthread_mutex_unlock(&out->compr_mute_lock);
        }
    } else {
        if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
            // mute compress stream if suspended
            pthread_mutex_lock(&out->compr_mute_lock);
            if (!out->a2dp_compress_mute && !out->standby) {
                ALOGD("%s: selecting speaker and muting stream", __func__);
                devices = out->devices;
                out->devices = AUDIO_DEVICE_OUT_SPEAKER;
                left_p = out->volume_l;
                right_p = out->volume_r;
                if (out->offload_state == OFFLOAD_STATE_PLAYING)
                    compress_pause(out->compr);
                out_set_compr_volume(&out->stream, (float)0, (float)0);
                out->a2dp_compress_mute = true;
                select_devices(adev, out->usecase);
                if (out->offload_state == OFFLOAD_STATE_PLAYING)
                    compress_resume(out->compr);
                out->devices = devices;
                out->volume_l = left_p;
                out->volume_r = right_p;
            }
            pthread_mutex_unlock(&out->compr_mute_lock);
        } else {
            // tear down a2dp path for non offloaded streams
            if (audio_extn_a2dp_source_is_suspended())
                out_standby_l(&out->stream.common);
        }
    }
    ALOGV("%s: exit", __func__);
    return 0;
}

int check_a2dp_restore(struct audio_device *adev, struct stream_out *out, bool restore)
{
    int ret = 0;

    lock_output_stream(out);
    pthread_mutex_lock(&adev->lock);

    ret = check_a2dp_restore_l(adev, out, restore);

    pthread_mutex_unlock(&adev->lock);
    pthread_mutex_unlock(&out->lock);
    return ret;
}

void adev_on_battery_status_changed(bool charging)
{
    pthread_mutex_lock(&adev->lock);
    ALOGI("%s: battery status changed to %scharging", __func__, charging ? "" : "not ");
    adev->is_charging = charging;
    audio_extn_sound_trigger_update_battery_status(charging);
    pthread_mutex_unlock(&adev->lock);
}

static int adev_open(const hw_module_t *module, const char *name,
                     hw_device_t **device)
{
    int ret;
    char value[PROPERTY_VALUE_MAX] = {0};
    char mixer_ctl_name[128] = {0};
    struct mixer_ctl *ctl = NULL;

    ALOGD("%s: enter", __func__);
    if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;

    pthread_mutex_lock(&adev_init_lock);
    if (audio_device_ref_count != 0){
            *device = &adev->device.common;
            audio_device_ref_count++;
            ALOGD("%s: returning existing instance of adev", __func__);
            ALOGD("%s: exit", __func__);
            pthread_mutex_unlock(&adev_init_lock);
            return 0;
    }

    adev = calloc(1, sizeof(struct audio_device));

    if (!adev) {
        pthread_mutex_unlock(&adev_init_lock);
        return -ENOMEM;
    }

    pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);

    // register audio ext hidl at the earliest
    audio_extn_hidl_init();
#ifdef DYNAMIC_LOG_ENABLED
    register_for_dynamic_logging("hal");
#endif

    /* default audio HAL major version */
    uint32_t maj_version = 2;
    if(property_get("vendor.audio.hal.maj.version", value, NULL))
        maj_version = atoi(value);

    adev->device.common.tag = HARDWARE_DEVICE_TAG;
    adev->device.common.version = HARDWARE_DEVICE_API_VERSION(maj_version, 0);
    adev->device.common.module = (struct hw_module_t *)module;
    adev->device.common.close = adev_close;

    adev->device.init_check = adev_init_check;
    adev->device.set_voice_volume = adev_set_voice_volume;
    adev->device.set_master_volume = adev_set_master_volume;
    adev->device.get_master_volume = adev_get_master_volume;
    adev->device.set_master_mute = adev_set_master_mute;
    adev->device.get_master_mute = adev_get_master_mute;
    adev->device.set_mode = adev_set_mode;
    adev->device.set_mic_mute = adev_set_mic_mute;
    adev->device.get_mic_mute = adev_get_mic_mute;
    adev->device.set_parameters = adev_set_parameters;
    adev->device.get_parameters = adev_get_parameters;
    adev->device.get_input_buffer_size = adev_get_input_buffer_size;
    adev->device.open_output_stream = adev_open_output_stream;
    adev->device.close_output_stream = adev_close_output_stream;
    adev->device.open_input_stream = adev_open_input_stream;
    adev->device.close_input_stream = adev_close_input_stream;
    adev->device.create_audio_patch = adev_create_audio_patch;
    adev->device.release_audio_patch = adev_release_audio_patch;
    adev->device.get_audio_port = adev_get_audio_port;
    adev->device.set_audio_port_config = adev_set_audio_port_config;
    adev->device.dump = adev_dump;
    adev->device.get_microphones = adev_get_microphones;

    /* Set the default route before the PCM stream is opened */
    adev->mode = AUDIO_MODE_NORMAL;
    adev->primary_output = NULL;
    adev->out_device = AUDIO_DEVICE_NONE;
    adev->bluetooth_nrec = true;
    adev->acdb_settings = TTY_MODE_OFF;
    adev->allow_afe_proxy_usage = true;
    adev->bt_sco_on = false;
    /* adev->cur_hdmi_channels = 0;  by calloc() */
    adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
    /* Init audio and voice feature */
    audio_extn_feature_init();
    voice_extn_feature_init();
    voice_init(adev);
    list_init(&adev->usecase_list);
    list_init(&adev->active_inputs_list);
    list_init(&adev->active_outputs_list);
    list_init(&adev->audio_patch_record_list);
    adev->audio_patch_index = 0;
    adev->cur_wfd_channels = 2;
    adev->offload_usecases_state = 0;
    adev->pcm_record_uc_state = 0;
    adev->is_channel_status_set = false;
    adev->perf_lock_opts[0] = 0x101;
    adev->perf_lock_opts[1] = 0x20E;
    adev->perf_lock_opts_size = 2;
    adev->dsp_bit_width_enforce_mode = 0;
    adev->enable_hfp = false;
    adev->use_old_pspd_mix_ctrl = false;
    adev->adm_routing_changed = false;

    /* Loads platform specific libraries dynamically */
    adev->platform = platform_init(adev);
    if (!adev->platform) {
        pthread_mutex_destroy(&adev->lock);
        free(adev->snd_dev_ref_cnt);
        free(adev);
        adev = NULL;
        ALOGE("%s: Failed to init platform data, aborting.", __func__);
        *device = NULL;
        pthread_mutex_unlock(&adev_init_lock);
        return -EINVAL;
    }

    adev->extspk = audio_extn_extspk_init(adev);
    if (audio_extn_qap_is_enabled()) {
        ret = audio_extn_qap_init(adev);
        if (ret < 0) {
            pthread_mutex_destroy(&adev->lock);
            free(adev);
            adev = NULL;
            ALOGE("%s: Failed to init platform data, aborting.", __func__);
            *device = NULL;
            pthread_mutex_unlock(&adev_init_lock);
            return ret;
        }
        adev->device.open_output_stream = audio_extn_qap_open_output_stream;
        adev->device.close_output_stream = audio_extn_qap_close_output_stream;
    }

    if (audio_extn_qaf_is_enabled()) {
        ret = audio_extn_qaf_init(adev);
        if (ret < 0) {
            pthread_mutex_destroy(&adev->lock);
            free(adev);
            adev = NULL;
            ALOGE("%s: Failed to init platform data, aborting.", __func__);
            *device = NULL;
            pthread_mutex_unlock(&adev_init_lock);
            return ret;
        }

        adev->device.open_output_stream = audio_extn_qaf_open_output_stream;
        adev->device.close_output_stream = audio_extn_qaf_close_output_stream;
    }

    audio_extn_auto_hal_init(adev);
    adev->ext_hw_plugin = audio_extn_ext_hw_plugin_init(adev);

    if (access(VISUALIZER_LIBRARY_PATH, R_OK) == 0) {
        adev->visualizer_lib = dlopen(VISUALIZER_LIBRARY_PATH, RTLD_NOW);
        if (adev->visualizer_lib == NULL) {
            ALOGE("%s: DLOPEN failed for %s", __func__, VISUALIZER_LIBRARY_PATH);
        } else {
            ALOGV("%s: DLOPEN successful for %s", __func__, VISUALIZER_LIBRARY_PATH);
            adev->visualizer_start_output =
                        (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
                                                        "visualizer_hal_start_output");
            adev->visualizer_stop_output =
                        (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
                                                        "visualizer_hal_stop_output");
        }
    }
    audio_extn_init(adev);
    voice_extn_init(adev);
    audio_extn_listen_init(adev, adev->snd_card);
    audio_extn_gef_init(adev);
    audio_extn_hw_loopback_init(adev);
    audio_extn_ffv_init(adev);

    if (access(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, R_OK) == 0) {
        adev->offload_effects_lib = dlopen(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, RTLD_NOW);
        if (adev->offload_effects_lib == NULL) {
            ALOGE("%s: DLOPEN failed for %s", __func__,
                  OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
        } else {
            ALOGV("%s: DLOPEN successful for %s", __func__,
                  OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
            adev->offload_effects_start_output =
                        (int (*)(audio_io_handle_t, int, struct mixer *))dlsym(adev->offload_effects_lib,
                                         "offload_effects_bundle_hal_start_output");
            adev->offload_effects_stop_output =
                        (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
                                         "offload_effects_bundle_hal_stop_output");
            adev->offload_effects_set_hpx_state =
                        (int (*)(bool))dlsym(adev->offload_effects_lib,
                                         "offload_effects_bundle_set_hpx_state");
            adev->offload_effects_get_parameters =
                        (void (*)(struct str_parms *, struct str_parms *))
                                         dlsym(adev->offload_effects_lib,
                                         "offload_effects_bundle_get_parameters");
            adev->offload_effects_set_parameters =
                        (void (*)(struct str_parms *))dlsym(adev->offload_effects_lib,
                                         "offload_effects_bundle_set_parameters");
        }
    }

    if (access(ADM_LIBRARY_PATH, R_OK) == 0) {
        adev->adm_lib = dlopen(ADM_LIBRARY_PATH, RTLD_NOW);
        if (adev->adm_lib == NULL) {
            ALOGE("%s: DLOPEN failed for %s", __func__, ADM_LIBRARY_PATH);
        } else {
            ALOGV("%s: DLOPEN successful for %s", __func__, ADM_LIBRARY_PATH);
            adev->adm_init = (adm_init_t)
                                    dlsym(adev->adm_lib, "adm_init");
            adev->adm_deinit = (adm_deinit_t)
                                    dlsym(adev->adm_lib, "adm_deinit");
            adev->adm_register_input_stream = (adm_register_input_stream_t)
                                    dlsym(adev->adm_lib, "adm_register_input_stream");
            adev->adm_register_output_stream = (adm_register_output_stream_t)
                                    dlsym(adev->adm_lib, "adm_register_output_stream");
            adev->adm_deregister_stream = (adm_deregister_stream_t)
                                    dlsym(adev->adm_lib, "adm_deregister_stream");
            adev->adm_request_focus = (adm_request_focus_t)
                                    dlsym(adev->adm_lib, "adm_request_focus");
            adev->adm_abandon_focus = (adm_abandon_focus_t)
                                    dlsym(adev->adm_lib, "adm_abandon_focus");
            adev->adm_set_config = (adm_set_config_t)
                                    dlsym(adev->adm_lib, "adm_set_config");
            adev->adm_request_focus_v2 = (adm_request_focus_v2_t)
                                    dlsym(adev->adm_lib, "adm_request_focus_v2");
            adev->adm_is_noirq_avail = (adm_is_noirq_avail_t)
                                    dlsym(adev->adm_lib, "adm_is_noirq_avail");
            adev->adm_on_routing_change = (adm_on_routing_change_t)
                                    dlsym(adev->adm_lib, "adm_on_routing_change");
            adev->adm_request_focus_v2_1 = (adm_request_focus_v2_1_t)
                                    dlsym(adev->adm_lib, "adm_request_focus_v2_1");
        }
    }

    adev->enable_voicerx = false;
    adev->bt_wb_speech_enabled = false;
    adev->swb_speech_mode = SPEECH_MODE_INVALID;
    //initialize this to false for now,
    //this will be set to true through set param
    adev->vr_audio_mode_enabled = false;

    audio_extn_ds2_enable(adev);
    *device = &adev->device.common;

    if (k_enable_extended_precision)
        adev_verify_devices(adev);

    adev->dsp_bit_width_enforce_mode =
        adev_init_dsp_bit_width_enforce_mode(adev->mixer);

    audio_extn_utils_update_streams_cfg_lists(adev->platform, adev->mixer,
                                             &adev->streams_output_cfg_list,
                                             &adev->streams_input_cfg_list);

    audio_device_ref_count++;

    int trial;
    if ((property_get("vendor.audio_hal.period_size", value, NULL) > 0) ||
        (property_get("audio_hal.period_size", value, NULL) > 0)) {
        trial = atoi(value);
        if (period_size_is_plausible_for_low_latency(trial)) {
            pcm_config_low_latency.period_size = trial;
            pcm_config_low_latency.start_threshold = trial / 4;
            pcm_config_low_latency.avail_min = trial / 4;
            configured_low_latency_capture_period_size = trial;
        }
    }
    if ((property_get("vendor.audio_hal.in_period_size", value, NULL) > 0) ||
        (property_get("audio_hal.in_period_size", value, NULL) > 0)) {
        trial = atoi(value);
        if (period_size_is_plausible_for_low_latency(trial)) {
            configured_low_latency_capture_period_size = trial;
        }
    }

    adev->mic_break_enabled = property_get_bool("vendor.audio.mic_break", false);

    adev->camera_orientation = CAMERA_DEFAULT;

    if ((property_get("vendor.audio_hal.period_multiplier",value,NULL) > 0) ||
        (property_get("audio_hal.period_multiplier",value,NULL) > 0)) {
        af_period_multiplier = atoi(value);
        if (af_period_multiplier < 0)
            af_period_multiplier = 2;
        else if (af_period_multiplier > 4)
            af_period_multiplier = 4;

        ALOGV("new period_multiplier = %d", af_period_multiplier);
    }

    audio_extn_qdsp_init(adev->platform);

    adev->multi_offload_enable = property_get_bool("vendor.audio.offload.multiple.enabled", false);
    pthread_mutex_unlock(&adev_init_lock);

    if (adev->adm_init)
        adev->adm_data = adev->adm_init();

    qahwi_init(*device);
    audio_extn_perf_lock_init();
    audio_extn_adsp_hdlr_init(adev->mixer);

    audio_extn_snd_mon_init();
    pthread_mutex_lock(&adev->lock);
    audio_extn_snd_mon_register_listener(adev, adev_snd_mon_cb);
    adev->card_status = CARD_STATUS_ONLINE;
    audio_extn_battery_properties_listener_init(adev_on_battery_status_changed);
    /*
     * if the battery state callback happens before charging can be queried,
     * it will be guarded with the adev->lock held in the cb function and so
     * the callback value will reflect the latest state
     */
    adev->is_charging = audio_extn_battery_properties_is_charging();
    audio_extn_sound_trigger_init(adev); /* dependent on snd_mon_init() */
    audio_extn_sound_trigger_update_battery_status(adev->is_charging);
    audio_extn_audiozoom_init();
    pthread_mutex_unlock(&adev->lock);
    /* Allocate memory for Device config params */
    adev->device_cfg_params = (struct audio_device_config_param*)
                                  calloc(platform_get_max_codec_backend(),
                                  sizeof(struct audio_device_config_param));
    if (adev->device_cfg_params == NULL)
        ALOGE("%s: Memory allocation failed for Device config params", __func__);

    /*
     * Check if new PSPD matrix mixer control is supported. If not
     * supported, then set flag so that old mixer ctrl is sent while
     * sending pspd coefficients on older kernel version. Query mixer
     * control for default pcm id and channel value one.
     */
    snprintf(mixer_ctl_name, sizeof(mixer_ctl_name),
            "AudStr %d ChMixer Weight Ch %d", 0, 1);

    ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    if (!ctl) {
        ALOGE("%s: ERROR. Could not get ctl for mixer cmd - %s",
              __func__, mixer_ctl_name);
        adev->use_old_pspd_mix_ctrl = true;
    }

    ALOGV("%s: exit", __func__);
    return 0;
}

static struct hw_module_methods_t hal_module_methods = {
    .open = adev_open,
};

struct audio_module HAL_MODULE_INFO_SYM = {
    .common = {
        .tag = HARDWARE_MODULE_TAG,
        .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
        .hal_api_version = HARDWARE_HAL_API_VERSION,
        .id = AUDIO_HARDWARE_MODULE_ID,
        .name = "QCOM Audio HAL",
        .author = "The Linux Foundation",
        .methods = &hal_module_methods,
    },
};