summaryrefslogtreecommitdiff
path: root/cras/src/libcras/cras_client.c
blob: 8420db1f35eb07edc0ac59c294eb37a297d0612d (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
/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/*
 * Basic playback flow:
 *  cras_client_create - Create new structure and set to defaults.
 *  cras_client_connect - Connect client to server - sets up server_fd to
 *    communicate with the audio server.  After the client connects, the server
 *    will send back a message containing the client id.
 *  cras_client_add_stream - Add a playback or capture stream. Creates a
 *    client_stream struct and send a file descriptor to server. That file
 *    descriptor and aud_fd are a pair created from socketpair().
 *  client_connected - The server will send a connected message to indicate that
 *    the client should start receiving audio events from aud_fd. This message
 *    also specifies the shared memory region to use to share audio samples.
 *    This region will be shmat'd.
 *  running - Once the connections are established, the client will listen for
 *    requests on aud_fd and fill the shm region with the requested number of
 *    samples. This happens in the aud_cb specified in the stream parameters.
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* For ppoll() */
#endif

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/eventfd.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
#include <sys/types.h>
#include <sys/un.h>
#include <syslog.h>
#include <unistd.h>

#include "cras_client.h"
#include "cras_config.h"
#include "cras_file_wait.h"
#include "cras_messages.h"
#include "cras_observer_ops.h"
#include "cras_shm.h"
#include "cras_types.h"
#include "cras_util.h"
#include "utlist.h"

static const size_t MAX_CMD_MSG_LEN = 256;
static const size_t SERVER_SHUTDOWN_TIMEOUT_US = 500000;
static const size_t SERVER_CONNECT_TIMEOUT_MS = 1000;
static const size_t HOTWORD_FRAME_RATE = 16000;
static const size_t HOTWORD_BLOCK_SIZE = 320;

/* Commands sent from the user to the running client. */
enum { CLIENT_STOP,
       CLIENT_ADD_STREAM,
       CLIENT_REMOVE_STREAM,
       CLIENT_SET_STREAM_VOLUME_SCALER,
       CLIENT_SERVER_CONNECT,
       CLIENT_SERVER_CONNECT_ASYNC,
};

struct command_msg {
	unsigned len;
	unsigned msg_id;
	cras_stream_id_t stream_id;
};

struct set_stream_volume_command_message {
	struct command_msg header;
	float volume_scaler;
};

/* Adds a stream to the client.
 *  stream - The stream to add.
 *  stream_id_out - Filled with the stream id of the new stream.
 *  dev_idx - Index of the device to attach the newly created stream.
 *      NO_DEVICE means not to pin the stream to a device.
 */
struct add_stream_command_message {
	struct command_msg header;
	struct client_stream *stream;
	cras_stream_id_t *stream_id_out;
	uint32_t dev_idx;
};

/* Commands send from a running stream to the client. */
enum { CLIENT_STREAM_EOF,
};

struct stream_msg {
	unsigned msg_id;
	cras_stream_id_t stream_id;
};

enum CRAS_THREAD_STATE {
	CRAS_THREAD_STOP,
	/* Isn't (shouldn't be) running. */
	CRAS_THREAD_WARMUP,
	/* Is started, but not fully functional: waiting
	 * for resources to be ready for example. */
	CRAS_THREAD_RUNNING,
	/* Is running and fully functional. */
};

/* Manage information for a thread. */
struct thread_state {
	pthread_t tid;
	enum CRAS_THREAD_STATE state;
};

/* Parameters used when setting up a capture or playback stream. See comment
 * above cras_client_stream_params_create or libcras_stream_params_set in the
 * header for descriptions. */
struct cras_stream_params {
	enum CRAS_STREAM_DIRECTION direction;
	size_t buffer_frames;
	size_t cb_threshold;
	enum CRAS_STREAM_TYPE stream_type;
	enum CRAS_CLIENT_TYPE client_type;
	uint32_t flags;
	uint64_t effects;
	void *user_data;
	cras_playback_cb_t aud_cb;
	cras_unified_cb_t unified_cb;
	cras_error_cb_t err_cb;
	struct cras_audio_format format;
	libcras_stream_cb_t stream_cb;
};

/* Represents an attached audio stream.
 * id - Unique stream identifier.
 * aud_fd - After server connects audio messages come in here.
 * direction - playback, capture, or loopback (see CRAS_STREAM_DIRECTION).
 * flags - Currently only used for CRAS_INPUT_STREAM_FLAG.
 * volume_scaler - Amount to scale the stream by, 0.0 to 1.0. Client could
 *    change this scaler value before stream actually connected, so we need
 *    to cache it until shm is prepared and apply it.
 * tid - Thread id of the audio thread spawned for this stream.
 * running - Audio thread runs while this is non-zero.
 * wake_fds - Pipe to wake the audio thread.
 * client - The client this stream is attached to.
 * config - Audio stream configuration.
 * shm - Shared memory used to exchange audio samples with the server.
 * prev, next - Form a linked list of streams attached to a client.
 */
struct client_stream {
	cras_stream_id_t id;
	int aud_fd; /* audio messages from server come in here. */
	enum CRAS_STREAM_DIRECTION direction;
	uint32_t flags;
	float volume_scaler;
	struct thread_state thread;
	int wake_fds[2]; /* Pipe to wake the thread */
	struct cras_client *client;
	struct cras_stream_params *config;
	struct cras_audio_shm *shm;
	struct client_stream *prev, *next;
};

/* State of the socket. */
typedef enum cras_socket_state {
	CRAS_SOCKET_STATE_DISCONNECTED,
	/* Not connected. Also used to cleanup the current connection
	 * before restarting the connection attempt. */
	CRAS_SOCKET_STATE_WAIT_FOR_SOCKET,
	/* Waiting for the socket file to exist. Socket file existence
	 * is monitored using cras_file_wait. */
	CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE,
	/* Waiting for the socket to have something at the other end. */
	CRAS_SOCKET_STATE_FIRST_MESSAGE,
	/* Waiting for the first messages from the server and set our
	 * client ID. */
	CRAS_SOCKET_STATE_CONNECTED,
	/* The socket is connected and working. */
	CRAS_SOCKET_STATE_ERROR_DELAY,
	/* There was an error during one of the above states. Sleep for
	 * a bit before continuing. If this state could not be initiated
	 * then we move to the DISCONNECTED state and notify via the
	 * connection callback. */
} cras_socket_state_t;

/* Represents a client used to communicate with the audio server.
 * id - Unique identifier for this client, negative until connected.
 * server_fd - Incoming messages from server.
 * server_fd_state - State of the server's socket.
 * server_event_fd - Eventfd to wait on until a connection is established.
 * stream_fds - Pipe for attached streams.
 * command_fds - Pipe for user commands to thread.
 * command_reply_fds - Pipe for acking/nacking command messages from thread.
 * sock_file - Server communication socket file.
 * sock_file_wait - Structure used to monitor existence of the socket file.
 * sock_file_exists - Set to true when the socket file exists.
 * running - The client thread will run while this is non zero.
 * next_stream_id - ID to give the next stream.
 * stream_start_cond - Condition used during stream startup.
 * stream_start_lock - Lock used during stream startup.
 * tid - Thread ID of the client thread started by "cras_client_run_thread".
 * last_command_result - Passes back the result of the last user command.
 * streams - Linked list of streams attached to this client.
 * server_state - RO shared memory region holding server state.
 * atlog_ro - RO shared memory region holding audio thread log.
 * debug_info_callback - Function to call when debug info is received.
 * atlog_access_callback - Function to call when atlog RO fd is received.
 * get_hotword_models_cb_t - Function to call when hotword models info is ready.
 * server_connection_cb - Function to called when a connection state changes.
 * server_connection_user_arg - User argument for server_connection_cb.
 * thread_priority_cb - Function to call for setting audio thread priority.
 * observer_ops - Functions to call when system state changes.
 * observer_context - Context passed to client in state change callbacks.
 */
struct cras_client {
	int id;
	int server_fd;
	cras_socket_state_t server_fd_state;
	int server_event_fd;
	int stream_fds[2];
	int command_fds[2];
	int command_reply_fds[2];
	const char *sock_file;
	struct cras_file_wait *sock_file_wait;
	bool sock_file_exists;
	struct thread_state thread;
	cras_stream_id_t next_stream_id;
	pthread_cond_t stream_start_cond;
	pthread_mutex_t stream_start_lock;
	int last_command_result;
	struct client_stream *streams;
	const struct cras_server_state *server_state;
	struct audio_thread_event_log *atlog_ro;
	void (*debug_info_callback)(struct cras_client *);
	void (*atlog_access_callback)(struct cras_client *);
	get_hotword_models_cb_t get_hotword_models_cb;
	cras_connection_status_cb_t server_connection_cb;
	void *server_connection_user_arg;
	cras_thread_priority_cb_t thread_priority_cb;
	struct cras_observer_ops observer_ops;
	void *observer_context;
};

/*
 * Holds the client pointer plus internal book keeping.
 *
 * client - The client
 * server_state_rwlock - lock to make the client's server_state thread-safe.
 */
struct client_int {
	struct cras_client client;
	pthread_rwlock_t server_state_rwlock;
};

#define to_client_int(cptr)                                                    \
	((struct client_int *)((char *)cptr -                                  \
			       offsetof(struct client_int, client)))

/*
 * Holds the hotword stream format, params, and ID used when waiting for a
 * hotword. The structure is created by cras_client_enable_hotword_callback and
 * destroyed by cras_client_disable_hotword_callback.
 */
struct cras_hotword_handle {
	struct cras_audio_format *format;
	struct cras_stream_params *params;
	cras_stream_id_t stream_id;
	cras_hotword_trigger_cb_t trigger_cb;
	cras_hotword_error_cb_t err_cb;
	void *user_data;
};

struct cras_stream_cb_data {
	cras_stream_id_t stream_id;
	enum CRAS_STREAM_DIRECTION direction;
	uint8_t *buf;
	unsigned int frames;
	struct timespec sample_ts;
	void *user_arg;
};

int stream_cb_get_stream_id(struct cras_stream_cb_data *data,
			    cras_stream_id_t *id)
{
	*id = data->stream_id;
	return 0;
}

int stream_cb_get_buf(struct cras_stream_cb_data *data, uint8_t **buf)
{
	*buf = data->buf;
	return 0;
}

int stream_cb_get_frames(struct cras_stream_cb_data *data, unsigned int *frames)
{
	*frames = data->frames;
	return 0;
}

int stream_cb_get_latency(struct cras_stream_cb_data *data,
			  struct timespec *latency)
{
	if (data->direction == CRAS_STREAM_INPUT)
		cras_client_calc_capture_latency(&data->sample_ts, latency);
	else
		cras_client_calc_playback_latency(&data->sample_ts, latency);
	return 0;
}

int stream_cb_get_user_arg(struct cras_stream_cb_data *data, void **user_arg)
{
	*user_arg = data->user_arg;
	return 0;
}

struct libcras_stream_cb_data *
libcras_stream_cb_data_create(cras_stream_id_t stream_id,
			      enum CRAS_STREAM_DIRECTION direction,
			      uint8_t *buf, unsigned int frames,
			      struct timespec sample_ts, void *user_arg)
{
	struct libcras_stream_cb_data *data =
		(struct libcras_stream_cb_data *)calloc(
			1, sizeof(struct libcras_stream_cb_data));
	if (!data) {
		syslog(LOG_ERR, "cras_client: calloc: %s", strerror(errno));
		return NULL;
	}
	data->data_ = (struct cras_stream_cb_data *)calloc(
		1, sizeof(struct cras_stream_cb_data));
	if (!data->data_) {
		syslog(LOG_ERR, "cras_client: calloc: %s", strerror(errno));
		free(data);
		return NULL;
	}
	data->api_version = CRAS_API_VERSION;
	data->get_stream_id = stream_cb_get_stream_id;
	data->get_buf = stream_cb_get_buf;
	data->get_frames = stream_cb_get_frames;
	data->get_latency = stream_cb_get_latency;
	data->get_user_arg = stream_cb_get_user_arg;
	data->data_->stream_id = stream_id;
	data->data_->direction = direction;
	data->data_->buf = buf;
	data->data_->frames = frames;
	data->data_->sample_ts = sample_ts;
	data->data_->user_arg = user_arg;
	return data;
}

void libcras_stream_cb_data_destroy(struct libcras_stream_cb_data *data)
{
	if (data)
		free(data->data_);
	free(data);
}

/*
 * Local Helpers
 */

static int client_thread_rm_stream(struct cras_client *client,
				   cras_stream_id_t stream_id);
static int handle_message_from_server(struct cras_client *client);
static int reregister_notifications(struct cras_client *client);

static struct libcras_node_info *
libcras_node_info_create(struct cras_iodev_info *iodev,
			 struct cras_ionode_info *ionode);

/*
 * Unlock the server_state_rwlock if lock_rc is 0.
 *
 * Args:
 *    client - The CRAS client pointer.
 *    lock_rc - The result of server_state_rdlock or
 *              server_state_wrlock.
 */
static void server_state_unlock(const struct cras_client *client, int lock_rc)
{
	struct client_int *client_int;

	if (!client)
		return;
	client_int = to_client_int(client);
	if (lock_rc == 0)
		pthread_rwlock_unlock(&client_int->server_state_rwlock);
}

/*
 * Lock the server_state_rwlock for reading.
 *
 * Also checks that the server_state pointer is valid.
 *
 * Args:
 *    client - The CRAS client pointer.
 * Returns:
 *    0 for success, positive error code on error.
 *    Returns EINVAL if the server state pointer is NULL.
 */
static int server_state_rdlock(const struct cras_client *client)
{
	struct client_int *client_int;
	int lock_rc;

	if (!client)
		return EINVAL;
	client_int = to_client_int(client);
	lock_rc = pthread_rwlock_rdlock(&client_int->server_state_rwlock);
	if (lock_rc != 0)
		return lock_rc;
	if (!client->server_state) {
		pthread_rwlock_unlock(&client_int->server_state_rwlock);
		return EINVAL;
	}
	return 0;
}

/*
 * Lock the server_state_rwlock for writing.
 *
 * Args:
 *    client - The CRAS client pointer.
 * Returns:
 *    0 for success, positive error code on error.
 */
static int server_state_wrlock(const struct cras_client *client)
{
	struct client_int *client_int;

	if (!client)
		return EINVAL;
	client_int = to_client_int(client);
	return pthread_rwlock_wrlock(&client_int->server_state_rwlock);
}

/* Get the stream pointer from a stream id. */
static struct client_stream *stream_from_id(const struct cras_client *client,
					    unsigned int id)
{
	struct client_stream *out;

	DL_SEARCH_SCALAR(client->streams, out, id, id);
	return out;
}

/*
 * Fill a pollfd structure with the current server fd and events.
 */
void server_fill_pollfd(const struct cras_client *client,
			struct pollfd *poll_fd)
{
	int events = 0;

	poll_fd->fd = client->server_fd;
	switch (client->server_fd_state) {
	case CRAS_SOCKET_STATE_DISCONNECTED:
		break;
	case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
	case CRAS_SOCKET_STATE_FIRST_MESSAGE:
	case CRAS_SOCKET_STATE_CONNECTED:
	case CRAS_SOCKET_STATE_ERROR_DELAY:
		events = POLLIN;
		break;
	case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
		events = POLLOUT;
		break;
	}
	poll_fd->events = events;
	poll_fd->revents = 0;
}

/*
 * Change the server_fd_state.
 */
static void server_fd_move_to_state(struct cras_client *client,
				    cras_socket_state_t state)
{
	if (state == client->server_fd_state)
		return;

	client->server_fd_state = state;
}

/*
 * Action to take when in state ERROR_DELAY.
 *
 * In this state we want to sleep for a few seconds before retrying the
 * connection to the audio server.
 *
 * If server_fd is negative: create a timer and setup server_fd with the
 * timer's fd. If server_fd is not negative and there is input, then assume
 * that the timer has expired, and restart the connection by moving to
 * WAIT_FOR_SOCKET state.
 */
static int error_delay_next_action(struct cras_client *client, int poll_revents)
{
	int rc;
	struct itimerspec timeout;

	if (client->server_fd == -1) {
		client->server_fd = timerfd_create(CLOCK_MONOTONIC,
						   TFD_NONBLOCK | TFD_CLOEXEC);
		if (client->server_fd == -1) {
			rc = -errno;
			syslog(LOG_ERR,
			       "cras_client: Could not create timerfd: %s",
			       strerror(-rc));
			return rc;
		}

		/* Setup a relative timeout of 2 seconds. */
		memset(&timeout, 0, sizeof(timeout));
		timeout.it_value.tv_sec = 2;
		rc = timerfd_settime(client->server_fd, 0, &timeout, NULL);
		if (rc != 0) {
			rc = -errno;
			syslog(LOG_ERR,
			       "cras_client: Could not set timeout: %s",
			       strerror(-rc));
			return rc;
		}
		return 0;
	} else if ((poll_revents & POLLIN) == 0) {
		return 0;
	}

	/* Move to the next state: close the timer fd first. */
	close(client->server_fd);
	client->server_fd = -1;
	server_fd_move_to_state(client, CRAS_SOCKET_STATE_WAIT_FOR_SOCKET);
	return 0;
}

/*
 * Action to take when in WAIT_FOR_SOCKET state.
 *
 * In this state we are waiting for the socket file to exist. The existence of
 * the socket file is continually monitored using the cras_file_wait structure
 * and a separate fd. When the sock_file_exists boolean is modified, the state
 * machine is invoked.
 *
 * If the socket file exists, then we move to the WAIT_FOR_WRITABLE state.
 */
static void wait_for_socket_next_action(struct cras_client *client)
{
	if (client->sock_file_exists)
		server_fd_move_to_state(client,
					CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE);
}

/*
 * Action to take when in WAIT_FOR_WRITABLE state.
 *
 * In this state we are initiating a connection the server and waiting for the
 * server to ready for incoming messages.
 *
 * Create the socket to the server, and wait while a connect request results in
 * -EINPROGRESS. Otherwise, we assume that the socket file will be deleted by
 * the server and the server_fd_state will be changed in
 * sock_file_wait_dispatch().
 */
static int wait_for_writable_next_action(struct cras_client *client,
					 int poll_revents)
{
	int rc;
	struct sockaddr_un address;

	if (client->server_fd == -1) {
		client->server_fd = socket(PF_UNIX, SOCK_SEQPACKET, 0);
		if (client->server_fd < 0) {
			rc = -errno;
			syslog(LOG_ERR, "cras_client: server socket failed: %s",
			       strerror(-rc));
			return rc;
		}
	} else if ((poll_revents & POLLOUT) == 0) {
		return 0;
	}

	/* We make the file descriptor non-blocking when we do connect(), so we
	 * don't block indefinitely. */
	cras_make_fd_nonblocking(client->server_fd);

	memset(&address, 0, sizeof(struct sockaddr_un));
	address.sun_family = AF_UNIX;
	strcpy(address.sun_path, client->sock_file);
	rc = connect(client->server_fd, (struct sockaddr *)&address,
		     sizeof(struct sockaddr_un));
	if (rc != 0) {
		rc = -errno;
		/* For -EINPROGRESS, we wait for POLLOUT on the server_fd.
		 * Otherwise CRAS is not running and we assume that the socket
		 * file will be deleted and recreated. Notification of that will
		 * happen via the sock_file_wait_dispatch(). */
		if (rc == -ECONNREFUSED) {
			/* CRAS is not running, don't log this error and just
			 * stay in this state waiting sock_file_wait_dispatch()
			 * to move the state machine. */
			close(client->server_fd);
			client->server_fd = -1;
		} else if (rc != -EINPROGRESS) {
			syslog(LOG_ERR,
			       "cras_client: server connect failed: %s",
			       strerror(-rc));
			return rc;
		}
		return 0;
	}

	cras_make_fd_blocking(client->server_fd);
	server_fd_move_to_state(client, CRAS_SOCKET_STATE_FIRST_MESSAGE);
	return 0;
}

/*
 * Action to take when transitioning to the CONNECTED state.
 */
static int connect_transition_action(struct cras_client *client)
{
	eventfd_t event_value;
	int rc;

	rc = reregister_notifications(client);
	if (rc < 0)
		return rc;

	server_fd_move_to_state(client, CRAS_SOCKET_STATE_CONNECTED);
	/* Notify anyone waiting on this state change that we're
	 * connected. */
	eventfd_read(client->server_event_fd, &event_value);
	eventfd_write(client->server_event_fd, 1);
	if (client->server_connection_cb)
		client->server_connection_cb(
			client, CRAS_CONN_STATUS_CONNECTED,
			client->server_connection_user_arg);
	return 0;
}

/*
 * Action to take when in the FIRST_MESSAGE state.
 *
 * We are waiting for the first message from the server. When our client ID has
 * been set, then we can move to the CONNECTED state.
 */
static int first_message_next_action(struct cras_client *client,
				     int poll_revents)
{
	int rc;

	if (client->server_fd < 0)
		return -EINVAL;

	if ((poll_revents & POLLIN) == 0)
		return 0;

	rc = handle_message_from_server(client);
	if (rc < 0) {
		syslog(LOG_ERR, "handle first message: %s", strerror(-rc));
	} else if (client->id >= 0) {
		rc = connect_transition_action(client);
	} else {
		syslog(LOG_ERR, "did not get ID after first message!");
		rc = -EINVAL;
	}
	return rc;
}

/*
 * Play nice and shutdown the server socket.
 */
static inline int shutdown_and_close_socket(int sockfd)
{
	int rc;
	uint8_t buffer[CRAS_CLIENT_MAX_MSG_SIZE];
	struct timeval tv;

	tv.tv_sec = 0;
	tv.tv_usec = SERVER_SHUTDOWN_TIMEOUT_US;
	setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));

	rc = shutdown(sockfd, SHUT_WR);
	if (rc < 0)
		return rc;
	/* Wait until the socket is closed by the peer. */
	for (;;) {
		rc = recv(sockfd, buffer, sizeof(buffer), 0);
		if (rc <= 0)
			break;
	}
	return close(sockfd);
}

/*
 * Action to take when disconnecting from the server.
 *
 * Clean up the server socket, and the server_state pointer. Move to the next
 * logical state.
 */
static void disconnect_transition_action(struct cras_client *client, bool force)
{
	eventfd_t event_value;
	cras_socket_state_t old_state = client->server_fd_state;
	struct client_stream *s;
	int lock_rc;

	/* Stop all playing streams.
	 * TODO(muirj): Pause and resume streams. */
	DL_FOREACH (client->streams, s) {
		s->config->err_cb(client, s->id, -ENOTCONN,
				  s->config->user_data);
		client_thread_rm_stream(client, s->id);
	}

	/* Clean up the server_state pointer. */
	lock_rc = server_state_wrlock(client);
	if (client->server_state) {
		munmap((void *)client->server_state,
		       sizeof(*client->server_state));
		client->server_state = NULL;
	}
	server_state_unlock(client, lock_rc);

	/* Our ID is unknown now. */
	client->id = -1;

	/* Clean up the server fd. */
	if (client->server_fd >= 0) {
		if (!force)
			shutdown_and_close_socket(client->server_fd);
		else
			close(client->server_fd);
		client->server_fd = -1;
	}

	/* Reset the server_event_fd value to 0 (and cause subsequent threads
	 * waiting on the connection to wait). */
	eventfd_read(client->server_event_fd, &event_value);

	switch (old_state) {
	case CRAS_SOCKET_STATE_DISCONNECTED:
		/* Do nothing: already disconnected. */
		break;
	case CRAS_SOCKET_STATE_ERROR_DELAY:
		/* We're disconnected and there was a failure to setup
		 * automatic reconnection, so call the server error
		 * callback now. */
		server_fd_move_to_state(client, CRAS_SOCKET_STATE_DISCONNECTED);
		if (client->server_connection_cb)
			client->server_connection_cb(
				client, CRAS_CONN_STATUS_FAILED,
				client->server_connection_user_arg);
		break;
	case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
	case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
	case CRAS_SOCKET_STATE_FIRST_MESSAGE:
		/* We are running this state transition while a connection is
		 * in progress for an error case. When there is no error, we
		 * come into this function in the DISCONNECTED state. */
		server_fd_move_to_state(client, CRAS_SOCKET_STATE_ERROR_DELAY);
		break;
	case CRAS_SOCKET_STATE_CONNECTED:
		/* Disconnected from CRAS (for an error), wait for the socket
		 * file to be (re)created. */
		server_fd_move_to_state(client,
					CRAS_SOCKET_STATE_WAIT_FOR_SOCKET);
		/* Notify the caller that we aren't connected anymore. */
		if (client->server_connection_cb)
			client->server_connection_cb(
				client, CRAS_CONN_STATUS_DISCONNECTED,
				client->server_connection_user_arg);
		break;
	}
}

static int server_fd_dispatch(struct cras_client *client, int poll_revents)
{
	int rc = 0;
	cras_socket_state_t old_state;

	if ((poll_revents & POLLHUP) != 0) {
		/* Error or disconnect: cleanup and make a state change now. */
		disconnect_transition_action(client, true);
	}
	old_state = client->server_fd_state;

	switch (client->server_fd_state) {
	case CRAS_SOCKET_STATE_DISCONNECTED:
		/* Assume that we've taken the necessary actions. */
		return -ENOTCONN;
	case CRAS_SOCKET_STATE_ERROR_DELAY:
		rc = error_delay_next_action(client, poll_revents);
		break;
	case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
		wait_for_socket_next_action(client);
		break;
	case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
		rc = wait_for_writable_next_action(client, poll_revents);
		break;
	case CRAS_SOCKET_STATE_FIRST_MESSAGE:
		rc = first_message_next_action(client, poll_revents);
		break;
	case CRAS_SOCKET_STATE_CONNECTED:
		if ((poll_revents & POLLIN) != 0)
			rc = handle_message_from_server(client);
		break;
	}

	if (rc != 0) {
		/* If there is an error, then start-over. */
		rc = server_fd_dispatch(client, POLLHUP);
	} else if (old_state != client->server_fd_state) {
		/* There was a state change, process the new state now. */
		rc = server_fd_dispatch(client, 0);
	}
	return rc;
}

/*
 * Start connecting to the server if we aren't already.
 */
static int server_connect(struct cras_client *client)
{
	if (client->server_fd_state != CRAS_SOCKET_STATE_DISCONNECTED)
		return 0;
	/* Start waiting for the server socket to exist. */
	server_fd_move_to_state(client, CRAS_SOCKET_STATE_WAIT_FOR_SOCKET);
	return server_fd_dispatch(client, 0);
}

/*
 * Disconnect from the server if we haven't already.
 */
static void server_disconnect(struct cras_client *client)
{
	if (client->server_fd_state == CRAS_SOCKET_STATE_DISCONNECTED)
		return;
	/* Set the disconnected state first so that the disconnect
	 * transition doesn't move the server state to ERROR_DELAY. */
	server_fd_move_to_state(client, CRAS_SOCKET_STATE_DISCONNECTED);
	disconnect_transition_action(client, false);
}

/*
 * Called when something happens to the socket file.
 */
static void sock_file_wait_callback(void *context, cras_file_wait_event_t event,
				    const char *filename)
{
	struct cras_client *client = (struct cras_client *)context;
	switch (event) {
	case CRAS_FILE_WAIT_EVENT_CREATED:
		client->sock_file_exists = 1;
		switch (client->server_fd_state) {
		case CRAS_SOCKET_STATE_DISCONNECTED:
		case CRAS_SOCKET_STATE_ERROR_DELAY:
		case CRAS_SOCKET_STATE_FIRST_MESSAGE:
		case CRAS_SOCKET_STATE_CONNECTED:
			break;
		case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
		case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
			/* The socket file exists. Tell the server state
			 * machine. */
			server_fd_dispatch(client, 0);
			break;
		}
		break;
	case CRAS_FILE_WAIT_EVENT_DELETED:
		client->sock_file_exists = 0;
		switch (client->server_fd_state) {
		case CRAS_SOCKET_STATE_DISCONNECTED:
			break;
		case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
		case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
		case CRAS_SOCKET_STATE_ERROR_DELAY:
		case CRAS_SOCKET_STATE_FIRST_MESSAGE:
		case CRAS_SOCKET_STATE_CONNECTED:
			/* Restart the connection process. */
			server_disconnect(client);
			server_connect(client);
			break;
		}
		break;
	case CRAS_FILE_WAIT_EVENT_NONE:
		break;
	}
}

/*
 * Service the sock_file_wait's fd.
 *
 * If the socket file is deleted, then cause a disconnect from the server.
 * Otherwise, start a reconnect depending on the server_fd_state.
 */
static int sock_file_wait_dispatch(struct cras_client *client, int poll_revents)
{
	int rc;

	if ((poll_revents & POLLIN) == 0)
		return 0;

	rc = cras_file_wait_dispatch(client->sock_file_wait);
	if (rc == -EAGAIN || rc == -EWOULDBLOCK)
		rc = 0;
	else if (rc != 0)
		syslog(LOG_ERR, "cras_file_wait_dispatch: %s", strerror(-rc));
	return rc;
}

/*
 * Waits until we have heard back from the server so that we know we are
 * connected.
 *
 * The connected success/failure message is always the first message the server
 * sends. Return non zero if client is connected to the server. A return code
 * of zero means that the client is not connected to the server.
 */
static int check_server_connected_wait(struct cras_client *client,
				       struct timespec *timeout)
{
	int rc = 0;
	struct pollfd poll_fd;

	poll_fd.fd = client->server_event_fd;
	poll_fd.events = POLLIN;
	poll_fd.revents = 0;

	/* The server_event_fd is only read and written by the functions
	 * that connect to the server. When a connection is established the
	 * eventfd has a value of 1 and cras_poll will return immediately
	 * with 1. When there is no connection to the server, then this
	 * function waits until the timeout has expired or a non-zero value
	 * is written to the server_event_fd. */
	while (rc == 0)
		rc = cras_poll(&poll_fd, 1, timeout, NULL);
	return rc > 0;
}

/* Returns non-zero if the thread is running (not stopped). */
static inline int thread_is_running(struct thread_state *thread)
{
	return thread->state != CRAS_THREAD_STOP;
}

/*
 * Opens the server socket and connects to it.
 * Args:
 *    client - Client pointer created with cras_client_create().
 *    timeout - Connection timeout.
 * Returns:
 *    0 for success, negative error code on failure.
 */
static int connect_to_server(struct cras_client *client,
			     struct timespec *timeout, bool use_command_thread)
{
	int rc;
	struct pollfd poll_fd[2];
	struct timespec connected_timeout;

	if (!client)
		return -EINVAL;

	if (thread_is_running(&client->thread) && use_command_thread) {
		rc = cras_client_connect_async(client);
		if (rc == 0) {
			rc = check_server_connected_wait(client, timeout);
			return rc ? 0 : -ESHUTDOWN;
		}
	}

	connected_timeout.tv_sec = 0;
	connected_timeout.tv_nsec = 0;
	if (check_server_connected_wait(client, &connected_timeout))
		return 0;

	poll_fd[0].fd = cras_file_wait_get_fd(client->sock_file_wait);
	poll_fd[0].events = POLLIN;

	rc = server_connect(client);
	while (rc == 0) {
		// Wait until we've connected or until there is a timeout.
		// Meanwhile handle incoming actions on our fds.

		server_fill_pollfd(client, &(poll_fd[1]));
		rc = cras_poll(poll_fd, 2, timeout, NULL);
		if (rc <= 0)
			continue;

		if (poll_fd[0].revents) {
			rc = sock_file_wait_dispatch(client,
						     poll_fd[0].revents);
			continue;
		}

		if (poll_fd[1].revents) {
			rc = server_fd_dispatch(client, poll_fd[1].revents);
			if (rc == 0 && client->server_fd_state ==
					       CRAS_SOCKET_STATE_CONNECTED)
				break;
		}
	}

	if (rc != 0)
		syslog(LOG_ERR, "cras_client: Connect server failed: %s",
		       strerror(-rc));

	return rc;
}

static int connect_to_server_wait_retry(struct cras_client *client,
					int timeout_ms, bool use_command_thread)
{
	struct timespec timeout_value;
	struct timespec *timeout;

	if (timeout_ms < 0) {
		timeout = NULL;
	} else {
		timeout = &timeout_value;
		ms_to_timespec(timeout_ms, timeout);
	}

	/* If connected, wait for the first message from the server
	 * indicating it's ready. */
	return connect_to_server(client, timeout, use_command_thread);
}

/*
 * Tries to connect to the server.  Waits for the initial message from the
 * server.  This will happen near instantaneously if the server is already
 * running.
 */
static int connect_to_server_wait(struct cras_client *client,
				  bool use_command_thread)
{
	return connect_to_server_wait_retry(client, SERVER_CONNECT_TIMEOUT_MS,
					    use_command_thread);
}

/*
 * Audio thread.
 */

/* Sends a message from the stream to the client to indicate an error.
 * If the running stream encounters an error, then it must tell the client
 * to stop running it.
 */
static int send_stream_message(const struct client_stream *stream,
			       unsigned msg_id)
{
	int res;
	struct stream_msg msg;

	msg.stream_id = stream->id;
	msg.msg_id = msg_id;
	res = write(stream->client->stream_fds[1], &msg, sizeof(msg));
	if (res != sizeof(msg))
		return -EPIPE;

	return 0;
}

/* Blocks until there is data to be read from the read_fd or until woken by an
 * incoming "poke" on wake_fd. Up to "len" bytes are read into "buf". */
static int read_with_wake_fd(int wake_fd, int read_fd, uint8_t *buf, size_t len)
{
	struct pollfd pollfds[2];
	int nread = 0;
	int nfds = 1;
	int rc;
	char tmp;

	pollfds[0].fd = wake_fd;
	pollfds[0].events = POLLIN;
	if (read_fd >= 0) {
		nfds++;
		pollfds[1].fd = read_fd;
		pollfds[1].events = POLLIN;
	}

	rc = poll(pollfds, nfds, -1);
	if (rc < 0)
		return rc;
	if (read_fd >= 0 && pollfds[1].revents & POLLIN) {
		nread = read(read_fd, buf, len);
		if (nread != (int)len)
			return -EIO;
	}
	if (pollfds[0].revents & POLLIN) {
		rc = read(wake_fd, &tmp, 1);
		if (rc < 0)
			return rc;
	}

	return nread;
}
/* Check the availability and configures a capture buffer.
 * Args:
 *     stream - The input stream to configure buffer for.
 *     captured_frames - To be filled with the pointer to the beginning of
 *         captured buffer.
 *     num_frames - Number of captured frames.
 * Returns:
 *     Number of frames available in captured_frames.
 */
static unsigned int config_capture_buf(struct client_stream *stream,
				       uint8_t **captured_frames,
				       unsigned int num_frames)
{
	/* Always return the beginning of the read buffer because Chrome expects
	 * so. */
	*captured_frames = cras_shm_get_read_buffer_base(stream->shm);

	/* Don't ask for more frames than the client desires. */
	if (stream->flags & BULK_AUDIO_OK)
		num_frames = MIN(num_frames, stream->config->buffer_frames);
	else
		num_frames = MIN(num_frames, stream->config->cb_threshold);

	/* If shm readable frames is less than client requests, that means
	 * overrun has happened in server side. Don't send partial corrupted
	 * buffer to client. */
	if (cras_shm_get_curr_read_frames(stream->shm) < num_frames)
		return 0;

	return num_frames;
}

static void complete_capture_read_current(struct client_stream *stream,
					  unsigned int num_frames)
{
	cras_shm_buffer_read_current(stream->shm, num_frames);
}

static int send_capture_reply(struct client_stream *stream, unsigned int frames,
			      int err)
{
	struct audio_message aud_msg;
	int rc;

	if (!cras_stream_uses_input_hw(stream->direction))
		return 0;

	aud_msg.id = AUDIO_MESSAGE_DATA_CAPTURED;
	aud_msg.frames = frames;
	aud_msg.error = err;

	rc = write(stream->aud_fd, &aud_msg, sizeof(aud_msg));
	if (rc != sizeof(aud_msg))
		return -EPIPE;

	return 0;
}

/* For capture streams this handles the message signalling that data is ready to
 * be passed to the user of this stream.  Calls the audio callback with the new
 * samples, and mark them as read.
 * Args:
 *    stream - The stream the message was received for.
 *    num_frames - The number of captured frames.
 * Returns:
 *    0, unless there is a fatal error or the client declares enod of file.
 */
static int handle_capture_data_ready(struct client_stream *stream,
				     unsigned int num_frames)
{
	int frames;
	struct cras_stream_params *config;
	uint8_t *captured_frames;
	struct timespec ts;
	int rc = 0;
	struct libcras_stream_cb_data *data;

	config = stream->config;
	/* If this message is for an output stream, log error and drop it. */
	if (!cras_stream_has_input(stream->direction)) {
		syslog(LOG_ERR, "cras_client: Play data to input\n");
		return 0;
	}

	num_frames = config_capture_buf(stream, &captured_frames, num_frames);
	if (num_frames == 0)
		return 0;

	cras_timespec_to_timespec(&ts, &stream->shm->header->ts);

	if (config->stream_cb) {
		data = libcras_stream_cb_data_create(
			stream->id, stream->direction, captured_frames,
			num_frames, ts, config->user_data);
		if (!data)
			return -errno;
		frames = config->stream_cb(data);
		libcras_stream_cb_data_destroy(data);
		data = NULL;
	} else if (config->unified_cb) {
		frames = config->unified_cb(stream->client, stream->id,
					    captured_frames, NULL, num_frames,
					    &ts, NULL, config->user_data);
	} else {
		frames = config->aud_cb(stream->client, stream->id,
					captured_frames, num_frames, &ts,
					config->user_data);
	}
	if (frames < 0) {
		send_stream_message(stream, CLIENT_STREAM_EOF);
		rc = frames;
		goto reply_captured;
	}
	if (frames == 0)
		return 0;

	complete_capture_read_current(stream, frames);
reply_captured:
	return send_capture_reply(stream, frames, rc);
}

/* Notifies the server that "frames" samples have been written. */
static int send_playback_reply(struct client_stream *stream,
			       unsigned int frames, int error)
{
	struct audio_message aud_msg;
	int rc;

	if (!cras_stream_uses_output_hw(stream->direction))
		return 0;

	aud_msg.id = AUDIO_MESSAGE_DATA_READY;
	aud_msg.frames = frames;
	aud_msg.error = error;

	rc = write(stream->aud_fd, &aud_msg, sizeof(aud_msg));
	if (rc != sizeof(aud_msg))
		return -EPIPE;

	return 0;
}

/* For playback streams when current buffer is empty, this handles the request
 * for more samples by calling the audio callback for the thread, and signaling
 * the server that the samples have been written. */
static int handle_playback_request(struct client_stream *stream,
				   unsigned int num_frames)
{
	uint8_t *buf;
	int frames;
	int rc = 0;
	struct cras_stream_params *config;
	struct cras_audio_shm *shm = stream->shm;
	struct timespec ts;
	struct libcras_stream_cb_data *data;

	config = stream->config;

	/* If this message is for an input stream, log error and drop it. */
	if (stream->direction != CRAS_STREAM_OUTPUT) {
		syslog(LOG_ERR, "cras_client: Record data from output\n");
		return 0;
	}

	buf = cras_shm_get_write_buffer_base(shm);

	/* Limit the amount of frames to the configured amount. */
	num_frames = MIN(num_frames, config->cb_threshold);

	cras_timespec_to_timespec(&ts, &shm->header->ts);

	/* Get samples from the user */
	if (config->stream_cb) {
		data = libcras_stream_cb_data_create(stream->id,
						     stream->direction, buf,
						     num_frames, ts,
						     config->user_data);
		if (!data)
			return -errno;
		frames = config->stream_cb(data);
		libcras_stream_cb_data_destroy(data);
		data = NULL;
	} else if (config->unified_cb) {
		frames = config->unified_cb(stream->client, stream->id, NULL,
					    buf, num_frames, NULL, &ts,
					    config->user_data);
	} else {
		frames = config->aud_cb(stream->client, stream->id, buf,
					num_frames, &ts, config->user_data);
	}
	if (frames < 0) {
		send_stream_message(stream, CLIENT_STREAM_EOF);
		rc = frames;
		goto reply_written;
	}

	cras_shm_buffer_written_start(shm, frames);

reply_written:
	/* Signal server that data is ready, or that an error has occurred. */
	rc = send_playback_reply(stream, frames, rc);
	return rc;
}

static void audio_thread_set_priority(struct client_stream *stream)
{
	/* Use provided callback to set priority if available. */
	if (stream->client->thread_priority_cb) {
		stream->client->thread_priority_cb(stream->client);
		return;
	}

	/* Try to get RT scheduling, if that fails try to set the nice value. */
	if (cras_set_rt_scheduling(CRAS_CLIENT_RT_THREAD_PRIORITY) ||
	    cras_set_thread_priority(CRAS_CLIENT_RT_THREAD_PRIORITY))
		cras_set_nice_level(CRAS_CLIENT_NICENESS_LEVEL);
}

/* Listens to the audio socket for messages from the server indicating that
 * the stream needs to be serviced.  One of these runs per stream. */
static void *audio_thread(void *arg)
{
	struct client_stream *stream = (struct client_stream *)arg;
	int thread_terminated = 0;
	struct audio_message aud_msg;
	int aud_fd;
	int num_read;

	if (arg == NULL)
		return (void *)-EIO;

	audio_thread_set_priority(stream);

	/* Notify the control thread that we've started. */
	pthread_mutex_lock(&stream->client->stream_start_lock);
	pthread_cond_broadcast(&stream->client->stream_start_cond);
	pthread_mutex_unlock(&stream->client->stream_start_lock);

	while (thread_is_running(&stream->thread) && !thread_terminated) {
		/* While we are warming up, aud_fd may not be valid and some
		 * shared memory resources may not yet be available. */
		aud_fd = (stream->thread.state == CRAS_THREAD_WARMUP) ?
				 -1 :
				 stream->aud_fd;
		num_read =
			read_with_wake_fd(stream->wake_fds[0], aud_fd,
					  (uint8_t *)&aud_msg, sizeof(aud_msg));
		if (num_read < 0)
			return (void *)-EIO;
		if (num_read == 0)
			continue;

		switch (aud_msg.id) {
		case AUDIO_MESSAGE_DATA_READY:
			thread_terminated = handle_capture_data_ready(
				stream, aud_msg.frames);
			break;
		case AUDIO_MESSAGE_REQUEST_DATA:
			thread_terminated =
				handle_playback_request(stream, aud_msg.frames);
			break;
		default:
			break;
		}
	}

	return NULL;
}

/* Pokes the audio thread so that it can notice if it has been terminated. */
static int wake_aud_thread(struct client_stream *stream)
{
	int rc;

	rc = write(stream->wake_fds[1], &rc, 1);
	if (rc != 1)
		return rc;
	return 0;
}

/* Stop the audio thread for the given stream.
 * Args:
 *    stream - Stream for which to stop the audio thread.
 *    join - When non-zero, attempt to join the audio thread (wait for it to
 *           complete).
 */
static void stop_aud_thread(struct client_stream *stream, int join)
{
	if (thread_is_running(&stream->thread)) {
		stream->thread.state = CRAS_THREAD_STOP;
		wake_aud_thread(stream);
		if (join)
			pthread_join(stream->thread.tid, NULL);
	}

	if (stream->wake_fds[0] >= 0) {
		close(stream->wake_fds[0]);
		close(stream->wake_fds[1]);
		stream->wake_fds[0] = -1;
	}
}

/* Start the audio thread for this stream.
 * Returns when the thread has started and is waiting.
 * Args:
 *    stream - The stream that needs an audio thread.
 * Returns:
 *    0 for success, or a negative error code.
 */
static int start_aud_thread(struct client_stream *stream)
{
	int rc;
	struct timespec future;

	rc = pipe(stream->wake_fds);
	if (rc < 0) {
		rc = -errno;
		syslog(LOG_ERR, "cras_client: pipe: %s", strerror(-rc));
		return rc;
	}

	stream->thread.state = CRAS_THREAD_WARMUP;

	pthread_mutex_lock(&stream->client->stream_start_lock);
	rc = pthread_create(&stream->thread.tid, NULL, audio_thread, stream);
	if (rc) {
		pthread_mutex_unlock(&stream->client->stream_start_lock);
		syslog(LOG_ERR, "cras_client: Couldn't create audio stream: %s",
		       strerror(rc));
		stream->thread.state = CRAS_THREAD_STOP;
		stop_aud_thread(stream, 0);
		return -rc;
	}

	clock_gettime(CLOCK_REALTIME, &future);
	future.tv_sec += 2; /* Wait up to two seconds. */
	rc = pthread_cond_timedwait(&stream->client->stream_start_cond,
				    &stream->client->stream_start_lock,
				    &future);
	pthread_mutex_unlock(&stream->client->stream_start_lock);
	if (rc != 0) {
		/* Something is very wrong: try to cancel the thread and don't
		 * wait for it. */
		syslog(LOG_ERR, "cras_client: Client thread not responding: %s",
		       strerror(rc));
		stop_aud_thread(stream, 0);
		return -rc;
	}
	return 0;
}

/*
 * Client thread.
 */

/* Gets the update_count of the server state shm region. */
static inline unsigned
begin_server_state_read(const struct cras_server_state *state)
{
	unsigned count;

	/* Version will be odd when the server is writing. */
	while ((count = *(volatile unsigned *)&state->update_count) & 1)
		sched_yield();
	__sync_synchronize();
	return count;
}

/* Checks if the update count of the server state shm region has changed from
 * count.  Returns 0 if the count still matches.
 */
static inline int end_server_state_read(const struct cras_server_state *state,
					unsigned count)
{
	__sync_synchronize();
	if (count != *(volatile unsigned *)&state->update_count)
		return -EAGAIN;
	return 0;
}

/* Release shm areas if references to them are held. */
static void free_shm(struct client_stream *stream)
{
	cras_audio_shm_destroy(stream->shm);
	stream->shm = NULL;
}

/* Handles the stream connected message from the server.  Check if we need a
 * format converter, configure the shared memory region, and start the audio
 * thread that will handle requests from the server. */
static int stream_connected(struct client_stream *stream,
			    const struct cras_client_stream_connected *msg,
			    const int stream_fds[2], const unsigned int num_fds)
{
	int rc, samples_prot;
	unsigned int i;
	struct cras_shm_info header_info, samples_info;

	if (msg->err || num_fds != 2) {
		syslog(LOG_ERR, "cras_client: Error setting up stream %d\n",
		       msg->err);
		rc = msg->err;
		goto err_ret;
	}

	rc = cras_shm_info_init_with_fd(stream_fds[0], cras_shm_header_size(),
					&header_info);
	if (rc < 0)
		goto err_ret;

	rc = cras_shm_info_init_with_fd(stream_fds[1], msg->samples_shm_size,
					&samples_info);
	if (rc < 0) {
		cras_shm_info_cleanup(&header_info);
		goto err_ret;
	}

	if (stream->direction == CRAS_STREAM_OUTPUT)
		samples_prot = PROT_WRITE;
	else
		samples_prot = PROT_READ;

	rc = cras_audio_shm_create(&header_info, &samples_info, samples_prot,
				   &stream->shm);
	if (rc < 0) {
		syslog(LOG_ERR, "cras_client: Error configuring shm");
		goto err_ret;
	}
	cras_shm_copy_shared_config(stream->shm);
	cras_shm_set_volume_scaler(stream->shm, stream->volume_scaler);

	stream->thread.state = CRAS_THREAD_RUNNING;
	wake_aud_thread(stream);

	close(stream_fds[0]);
	close(stream_fds[1]);
	return 0;
err_ret:
	stop_aud_thread(stream, 1);
	for (i = 0; i < num_fds; i++)
		close(stream_fds[i]);
	free_shm(stream);
	return rc;
}

static int send_connect_message(struct cras_client *client,
				struct client_stream *stream, uint32_t dev_idx)
{
	int rc;
	struct cras_connect_message serv_msg;
	int sock[2] = { -1, -1 };

	/* Create a socket pair for the server to notify of audio events. */
	rc = socketpair(AF_UNIX, SOCK_STREAM, 0, sock);
	if (rc != 0) {
		rc = -errno;
		syslog(LOG_ERR, "cras_client: socketpair: %s", strerror(-rc));
		goto fail;
	}

	cras_fill_connect_message(&serv_msg, stream->config->direction,
				  stream->id, stream->config->stream_type,
				  stream->config->client_type,
				  stream->config->buffer_frames,
				  stream->config->cb_threshold, stream->flags,
				  stream->config->effects,
				  stream->config->format, dev_idx);

	rc = cras_send_with_fds(client->server_fd, &serv_msg, sizeof(serv_msg),
				&sock[1], 1);
	if (rc != sizeof(serv_msg)) {
		rc = EIO;
		syslog(LOG_ERR,
		       "cras_client: add_stream: Send server message failed.");
		goto fail;
	}

	stream->aud_fd = sock[0];
	close(sock[1]);
	return 0;

fail:
	if (sock[0] != -1)
		close(sock[0]);
	if (sock[1] != -1)
		close(sock[1]);
	return rc;
}

/* Adds a stream to a running client.  Checks to make sure that the client is
 * attached, waits if it isn't.  The stream is prepared on the  main thread and
 * passed here. */
static int client_thread_add_stream(struct cras_client *client,
				    struct client_stream *stream,
				    cras_stream_id_t *stream_id_out,
				    uint32_t dev_idx)
{
	int rc;
	cras_stream_id_t new_id;
	struct client_stream *out;

	if ((stream->flags & HOTWORD_STREAM) == HOTWORD_STREAM) {
		int hotword_idx;
		hotword_idx = cras_client_get_first_dev_type_idx(
			client, CRAS_NODE_TYPE_HOTWORD, CRAS_STREAM_INPUT);

		/* Find the hotword device index. */
		if (dev_idx == NO_DEVICE) {
			if (hotword_idx < 0) {
				syslog(LOG_ERR,
				       "cras_client: add_stream: No hotword dev");
				return hotword_idx;
			} else {
				dev_idx = (uint32_t)hotword_idx;
			}
		}
		/* A known Use case for client to pin hotword stream on a not
		 * hotword device is to use internal mic for Assistant to work
		 * on board without usable DSP hotwording. We assume there will
		 * be only one hotword device exists. */
		else if (dev_idx != (uint32_t)hotword_idx) {
			/* Unmask the flag to fallback to normal pinned stream
			 * on specified device. */
			stream->flags &= ~HOTWORD_STREAM;
		}
	}

	/* Find an available stream id. */
	do {
		new_id = cras_get_stream_id(client->id, client->next_stream_id);
		client->next_stream_id++;
		DL_SEARCH_SCALAR(client->streams, out, id, new_id);
	} while (out != NULL);

	stream->id = new_id;
	*stream_id_out = new_id;
	stream->client = client;

	/* Start the audio thread. */
	rc = start_aud_thread(stream);
	if (rc != 0)
		return rc;

	/* Start the thread associated with this stream. */
	/* send a message to the server asking that the stream be started. */
	rc = send_connect_message(client, stream, dev_idx);
	if (rc != 0) {
		stop_aud_thread(stream, 1);
		return rc;
	}

	/* Add the stream to the linked list */
	DL_APPEND(client->streams, stream);

	return 0;
}

/* Removes a stream from a running client from within the running client's
 * context. */
static int client_thread_rm_stream(struct cras_client *client,
				   cras_stream_id_t stream_id)
{
	struct cras_disconnect_stream_message msg;
	struct client_stream *stream = stream_from_id(client, stream_id);
	int rc;

	if (stream == NULL)
		return 0;

	/* Tell server to remove. */
	if (client->server_fd_state == CRAS_SOCKET_STATE_CONNECTED) {
		cras_fill_disconnect_stream_message(&msg, stream_id);
		rc = write(client->server_fd, &msg, sizeof(msg));
		if (rc < 0)
			syslog(LOG_ERR,
			       "cras_client: error removing stream from server\n");
	}

	/* And shut down locally. */
	stop_aud_thread(stream, 1);

	free_shm(stream);

	DL_DELETE(client->streams, stream);
	if (stream->aud_fd >= 0)
		close(stream->aud_fd);

	free(stream->config);
	free(stream);

	return 0;
}

/* Sets the volume scaling factor for a playback or capture stream. */
static int client_thread_set_stream_volume(struct cras_client *client,
					   cras_stream_id_t stream_id,
					   float volume_scaler)
{
	struct client_stream *stream;

	stream = stream_from_id(client, stream_id);
	if (stream == NULL || volume_scaler > 1.0 || volume_scaler < 0.0)
		return -EINVAL;

	stream->volume_scaler = volume_scaler;
	if (stream->shm)
		cras_shm_set_volume_scaler(stream->shm, volume_scaler);

	return 0;
}

/* Attach to the shm region containing the audio thread log. */
static void attach_atlog_shm(struct cras_client *client, int fd)
{
	client->atlog_ro = (struct audio_thread_event_log *)mmap(
		NULL, sizeof(*client->atlog_ro), PROT_READ, MAP_SHARED, fd, 0);
	close(fd);
}

/* Attach to the shm region containing the server state. */
static int client_attach_shm(struct cras_client *client, int shm_fd)
{
	int lock_rc;
	int rc;

	lock_rc = server_state_wrlock(client);
	if (client->server_state) {
		rc = -EBUSY;
		goto error;
	}

	client->server_state = (struct cras_server_state *)mmap(
		NULL, sizeof(*client->server_state), PROT_READ, MAP_SHARED,
		shm_fd, 0);
	rc = -errno;
	close(shm_fd);
	if (client->server_state == (struct cras_server_state *)-1) {
		syslog(LOG_ERR,
		       "cras_client: mmap failed to map shm for client: %s",
		       strerror(-rc));
		goto error;
	}

	if (client->server_state->state_version != CRAS_SERVER_STATE_VERSION) {
		munmap((void *)client->server_state,
		       sizeof(*client->server_state));
		client->server_state = NULL;
		rc = -EINVAL;
		syslog(LOG_ERR, "cras_client: Unknown server_state version.");
	} else {
		rc = 0;
	}

error:
	server_state_unlock(client, lock_rc);
	return rc;
}

static void cras_client_get_hotword_models_ready(struct cras_client *client,
						 const char *hotword_models)
{
	if (!client->get_hotword_models_cb)
		return;
	client->get_hotword_models_cb(client, hotword_models);
	client->get_hotword_models_cb = NULL;
}

/* Handles messages from the cras server. */
static int handle_message_from_server(struct cras_client *client)
{
	uint8_t buf[CRAS_CLIENT_MAX_MSG_SIZE];
	struct cras_client_message *msg;
	int rc = 0;
	int nread;
	int server_fds[2];
	unsigned int num_fds = 2;

	msg = (struct cras_client_message *)buf;
	nread = cras_recv_with_fds(client->server_fd, buf, sizeof(buf),
				   server_fds, &num_fds);
	if (nread < (int)sizeof(msg->length) || (int)msg->length != nread)
		return -EIO;

	switch (msg->id) {
	case CRAS_CLIENT_CONNECTED: {
		struct cras_client_connected *cmsg =
			(struct cras_client_connected *)msg;
		if (num_fds != 1)
			return -EINVAL;
		rc = client_attach_shm(client, server_fds[0]);
		if (rc)
			return rc;
		client->id = cmsg->client_id;

		break;
	}
	case CRAS_CLIENT_STREAM_CONNECTED: {
		struct cras_client_stream_connected *cmsg =
			(struct cras_client_stream_connected *)msg;
		struct client_stream *stream =
			stream_from_id(client, cmsg->stream_id);
		if (stream == NULL) {
			if (num_fds != 2) {
				syslog(LOG_ERR,
				       "cras_client: Error receiving "
				       "stream 0x%x connected message",
				       cmsg->stream_id);
				return -EINVAL;
			}

			/*
			 * Usually, the fds should be closed in stream_connected
			 * callback. However, sometimes a stream is removed
			 * before it is connected.
			 */
			close(server_fds[0]);
			close(server_fds[1]);
			break;
		}
		rc = stream_connected(stream, cmsg, server_fds, num_fds);
		if (rc < 0)
			stream->config->err_cb(stream->client, stream->id, rc,
					       stream->config->user_data);
		break;
	}
	case CRAS_CLIENT_AUDIO_DEBUG_INFO_READY:
		if (client->debug_info_callback)
			client->debug_info_callback(client);
		client->debug_info_callback = NULL;
		break;
	case CRAS_CLIENT_ATLOG_FD_READY:
		if (num_fds != 1 || server_fds[0] < 0)
			return -EINVAL;
		attach_atlog_shm(client, server_fds[0]);
		if (client->atlog_access_callback)
			client->atlog_access_callback(client);
		client->atlog_access_callback = NULL;
		break;
	case CRAS_CLIENT_GET_HOTWORD_MODELS_READY: {
		struct cras_client_get_hotword_models_ready *cmsg =
			(struct cras_client_get_hotword_models_ready *)msg;
		cras_client_get_hotword_models_ready(
			client, (const char *)cmsg->hotword_models);
		break;
	}
	case CRAS_CLIENT_OUTPUT_VOLUME_CHANGED: {
		struct cras_client_volume_changed *cmsg =
			(struct cras_client_volume_changed *)msg;
		if (client->observer_ops.output_volume_changed)
			client->observer_ops.output_volume_changed(
				client->observer_context, cmsg->volume);
		break;
	}
	case CRAS_CLIENT_OUTPUT_MUTE_CHANGED: {
		struct cras_client_mute_changed *cmsg =
			(struct cras_client_mute_changed *)msg;
		if (client->observer_ops.output_mute_changed)
			client->observer_ops.output_mute_changed(
				client->observer_context, cmsg->muted,
				cmsg->user_muted, cmsg->mute_locked);
		break;
	}
	case CRAS_CLIENT_CAPTURE_GAIN_CHANGED: {
		struct cras_client_volume_changed *cmsg =
			(struct cras_client_volume_changed *)msg;
		if (client->observer_ops.capture_gain_changed)
			client->observer_ops.capture_gain_changed(
				client->observer_context, cmsg->volume);
		break;
	}
	case CRAS_CLIENT_CAPTURE_MUTE_CHANGED: {
		struct cras_client_mute_changed *cmsg =
			(struct cras_client_mute_changed *)msg;
		if (client->observer_ops.capture_mute_changed)
			client->observer_ops.capture_mute_changed(
				client->observer_context, cmsg->muted,
				cmsg->mute_locked);
		break;
	}
	case CRAS_CLIENT_NODES_CHANGED: {
		if (client->observer_ops.nodes_changed)
			client->observer_ops.nodes_changed(
				client->observer_context);
		break;
	}
	case CRAS_CLIENT_ACTIVE_NODE_CHANGED: {
		struct cras_client_active_node_changed *cmsg =
			(struct cras_client_active_node_changed *)msg;
		enum CRAS_STREAM_DIRECTION direction =
			(enum CRAS_STREAM_DIRECTION)cmsg->direction;
		if (client->observer_ops.active_node_changed)
			client->observer_ops.active_node_changed(
				client->observer_context, direction,
				cmsg->node_id);
		break;
	}
	case CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED: {
		struct cras_client_node_value_changed *cmsg =
			(struct cras_client_node_value_changed *)msg;
		if (client->observer_ops.output_node_volume_changed)
			client->observer_ops.output_node_volume_changed(
				client->observer_context, cmsg->node_id,
				cmsg->value);
		break;
	}
	case CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED: {
		struct cras_client_node_value_changed *cmsg =
			(struct cras_client_node_value_changed *)msg;
		if (client->observer_ops.node_left_right_swapped_changed)
			client->observer_ops.node_left_right_swapped_changed(
				client->observer_context, cmsg->node_id,
				cmsg->value);
		break;
	}
	case CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED: {
		struct cras_client_node_value_changed *cmsg =
			(struct cras_client_node_value_changed *)msg;
		if (client->observer_ops.input_node_gain_changed)
			client->observer_ops.input_node_gain_changed(
				client->observer_context, cmsg->node_id,
				cmsg->value);
		break;
	}
	case CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED: {
		struct cras_client_num_active_streams_changed *cmsg =
			(struct cras_client_num_active_streams_changed *)msg;
		enum CRAS_STREAM_DIRECTION direction =
			(enum CRAS_STREAM_DIRECTION)cmsg->direction;
		if (client->observer_ops.num_active_streams_changed)
			client->observer_ops.num_active_streams_changed(
				client->observer_context, direction,
				cmsg->num_active_streams);
		break;
	}
	default:
		break;
	}

	return 0;
}

/* Handles messages from streams to this client. */
static int handle_stream_message(struct cras_client *client, int poll_revents)
{
	struct stream_msg msg;
	int rc;

	if ((poll_revents & POLLIN) == 0)
		return 0;

	rc = read(client->stream_fds[0], &msg, sizeof(msg));
	if (rc < 0)
		syslog(LOG_ERR, "cras_client: Stream read failed %d\n", errno);
	/* The only reason a stream sends a message is if it needs to be
	 * removed. An error on read would mean the same thing so regardless of
	 * what gets us here, just remove the stream */
	client_thread_rm_stream(client, msg.stream_id);
	return 0;
}

/* Handles messages from users to this client. */
static int handle_command_message(struct cras_client *client, int poll_revents)
{
	uint8_t buf[MAX_CMD_MSG_LEN];
	struct command_msg *msg = (struct command_msg *)buf;
	int rc, to_read;

	if ((poll_revents & POLLIN) == 0)
		return 0;

	rc = read(client->command_fds[0], buf, sizeof(msg->len));
	if (rc != sizeof(msg->len) || msg->len > MAX_CMD_MSG_LEN) {
		rc = -EIO;
		goto cmd_msg_complete;
	}
	to_read = msg->len - rc;
	rc = read(client->command_fds[0], &buf[0] + rc, to_read);
	if (rc != to_read) {
		rc = -EIO;
		goto cmd_msg_complete;
	}

	switch (msg->msg_id) {
	case CLIENT_STOP: {
		struct client_stream *s;

		/* Stop all playing streams */
		DL_FOREACH (client->streams, s)
			client_thread_rm_stream(client, s->id);

		/* And stop this client */
		client->thread.state = CRAS_THREAD_STOP;
		rc = 0;
		break;
	}
	case CLIENT_ADD_STREAM: {
		struct add_stream_command_message *add_msg =
			(struct add_stream_command_message *)msg;
		rc = client_thread_add_stream(client, add_msg->stream,
					      add_msg->stream_id_out,
					      add_msg->dev_idx);
		break;
	}
	case CLIENT_REMOVE_STREAM:
		rc = client_thread_rm_stream(client, msg->stream_id);
		break;
	case CLIENT_SET_STREAM_VOLUME_SCALER: {
		struct set_stream_volume_command_message *vol_msg =
			(struct set_stream_volume_command_message *)msg;
		rc = client_thread_set_stream_volume(client,
						     vol_msg->header.stream_id,
						     vol_msg->volume_scaler);
		break;
	}
	case CLIENT_SERVER_CONNECT:
		rc = connect_to_server_wait(client, false);
		break;
	case CLIENT_SERVER_CONNECT_ASYNC:
		rc = server_connect(client);
		break;
	default:
		assert(0);
		break;
	}

cmd_msg_complete:
	/* Wake the waiting main thread with the result of the command. */
	if (write(client->command_reply_fds[1], &rc, sizeof(rc)) != sizeof(rc))
		return -EIO;
	return rc;
}

/*  This thread handles non audio sample communication with the audio server.
 *  The client program will call fucntions below to send messages to this thread
 *  to add or remove streams or change parameters.
 */
static void *client_thread(void *arg)
{
	struct cras_client *client = (struct cras_client *)arg;
	struct pollfd pollfds[4];
	int (*cbs[4])(struct cras_client * client, int poll_revents);
	unsigned int num_pollfds, i;
	int rc;

	if (arg == NULL)
		return (void *)-EINVAL;

	while (thread_is_running(&client->thread)) {
		num_pollfds = 0;

		rc = cras_file_wait_get_fd(client->sock_file_wait);
		if (rc >= 0) {
			cbs[num_pollfds] = sock_file_wait_dispatch;
			pollfds[num_pollfds].fd = rc;
			pollfds[num_pollfds].events = POLLIN;
			pollfds[num_pollfds].revents = 0;
			num_pollfds++;
		} else
			syslog(LOG_ERR, "file wait fd: %d", rc);
		if (client->server_fd >= 0) {
			cbs[num_pollfds] = server_fd_dispatch;
			server_fill_pollfd(client, &(pollfds[num_pollfds]));
			num_pollfds++;
		}
		if (client->command_fds[0] >= 0) {
			cbs[num_pollfds] = handle_command_message;
			pollfds[num_pollfds].fd = client->command_fds[0];
			pollfds[num_pollfds].events = POLLIN;
			pollfds[num_pollfds].revents = 0;
			num_pollfds++;
		}
		if (client->stream_fds[0] >= 0) {
			cbs[num_pollfds] = handle_stream_message;
			pollfds[num_pollfds].fd = client->stream_fds[0];
			pollfds[num_pollfds].events = POLLIN;
			pollfds[num_pollfds].revents = 0;
			num_pollfds++;
		}

		rc = poll(pollfds, num_pollfds, -1);
		if (rc <= 0)
			continue;

		for (i = 0; i < num_pollfds; i++) {
			/* Only do one at a time, since some messages may
			 * result in change to other fds. */
			if (pollfds[i].revents) {
				cbs[i](client, pollfds[i].revents);
				break;
			}
		}
	}

	/* close the command reply pipe. */
	close(client->command_reply_fds[1]);
	client->command_reply_fds[1] = -1;

	return NULL;
}

/* Sends a message to the client thread to complete an action requested by the
 * user.  Then waits for the action to complete and returns the result. */
static int send_command_message(struct cras_client *client,
				struct command_msg *msg)
{
	int rc, cmd_res;
	if (client == NULL || !thread_is_running(&client->thread))
		return -EINVAL;

	rc = write(client->command_fds[1], msg, msg->len);
	if (rc != (int)msg->len)
		return -EPIPE;

	/* Wait for command to complete. */
	rc = read(client->command_reply_fds[0], &cmd_res, sizeof(cmd_res));
	if (rc != sizeof(cmd_res))
		return -EPIPE;
	return cmd_res;
}

/* Send a simple message to the client thread that holds no data. */
static int send_simple_cmd_msg(struct cras_client *client,
			       cras_stream_id_t stream_id, unsigned msg_id)
{
	struct command_msg msg;

	msg.len = sizeof(msg);
	msg.stream_id = stream_id;
	msg.msg_id = msg_id;

	return send_command_message(client, &msg);
}

/* Sends the set volume message to the client thread. */
static int send_stream_volume_command_msg(struct cras_client *client,
					  cras_stream_id_t stream_id,
					  float volume_scaler)
{
	struct set_stream_volume_command_message msg;

	msg.header.len = sizeof(msg);
	msg.header.stream_id = stream_id;
	msg.header.msg_id = CLIENT_SET_STREAM_VOLUME_SCALER;
	msg.volume_scaler = volume_scaler;

	return send_command_message(client, &msg.header);
}

/* Sends a message back to the client and returns the error code. */
static int write_message_to_server(struct cras_client *client,
				   const struct cras_server_message *msg)
{
	ssize_t write_rc = -EPIPE;

	if (client->server_fd_state == CRAS_SOCKET_STATE_CONNECTED ||
	    client->server_fd_state == CRAS_SOCKET_STATE_FIRST_MESSAGE) {
		write_rc = write(client->server_fd, msg, msg->length);
		if (write_rc < 0)
			write_rc = -errno;
	}

	if (write_rc != (ssize_t)msg->length &&
	    client->server_fd_state != CRAS_SOCKET_STATE_FIRST_MESSAGE)
		return -EPIPE;

	if (write_rc < 0)
		return write_rc;
	else if (write_rc != (ssize_t)msg->length)
		return -EIO;
	else
		return 0;
}

/* Fills server socket file to connect by client's connection type. */
static int fill_socket_file(struct cras_client *client,
			    enum CRAS_CONNECTION_TYPE conn_type)
{
	int rc;

	client->sock_file =
		(const char *)calloc(CRAS_MAX_SOCKET_PATH_SIZE, sizeof(char));
	if (client->sock_file == NULL)
		return -ENOMEM;

	rc = cras_fill_socket_path(conn_type, (char *)client->sock_file);
	if (rc < 0) {
		free((void *)client->sock_file);
		return rc;
	}
	return 0;
}

/*
 * Exported Client Interface
 */

int cras_client_create_with_type(struct cras_client **client,
				 enum CRAS_CONNECTION_TYPE conn_type)
{
	int rc;
	struct client_int *client_int;
	pthread_condattr_t cond_attr;

	if (!cras_validate_connection_type(conn_type)) {
		syslog(LOG_ERR, "Input connection type is not supported.\n");
		return -EINVAL;
	}

	/* Ignore SIGPIPE while using this API. */
	signal(SIGPIPE, SIG_IGN);

	client_int = (struct client_int *)calloc(1, sizeof(*client_int));
	if (!client_int)
		return -ENOMEM;
	*client = &client_int->client;
	(*client)->server_fd = -1;
	(*client)->id = -1;

	rc = pthread_rwlock_init(&client_int->server_state_rwlock, NULL);
	if (rc != 0) {
		syslog(LOG_ERR, "cras_client: Could not init state rwlock.");
		rc = -rc;
		goto free_client;
	}

	rc = pthread_mutex_init(&(*client)->stream_start_lock, NULL);
	if (rc != 0) {
		syslog(LOG_ERR, "cras_client: Could not init start lock.");
		rc = -rc;
		goto free_rwlock;
	}

	pthread_condattr_init(&cond_attr);
	pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
	rc = pthread_cond_init(&(*client)->stream_start_cond, &cond_attr);
	pthread_condattr_destroy(&cond_attr);
	if (rc != 0) {
		syslog(LOG_ERR, "cras_client: Could not init start cond.");
		rc = -rc;
		goto free_lock;
	}

	(*client)->server_event_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
	if ((*client)->server_event_fd < 0) {
		syslog(LOG_ERR, "cras_client: Could not setup server eventfd.");
		rc = -errno;
		goto free_cond;
	}

	rc = fill_socket_file((*client), conn_type);
	if (rc < 0) {
		goto free_server_event_fd;
	}

	rc = cras_file_wait_create((*client)->sock_file,
				   CRAS_FILE_WAIT_FLAG_NONE,
				   sock_file_wait_callback, *client,
				   &(*client)->sock_file_wait);
	if (rc < 0 && rc != -ENOENT) {
		syslog(LOG_ERR,
		       "cras_client: Could not setup watch for '%s': %s",
		       (*client)->sock_file, strerror(-rc));
		goto free_error;
	}
	(*client)->sock_file_exists = (rc == 0);

	/* Pipes used by the main thread and the client thread to send commands
	 * and replies. */
	rc = pipe((*client)->command_fds);
	if (rc < 0)
		goto free_error;
	/* Pipe used to communicate between the client thread and the audio
	 * thread. */
	rc = pipe((*client)->stream_fds);
	if (rc < 0) {
		close((*client)->command_fds[0]);
		close((*client)->command_fds[1]);
		goto free_error;
	}
	(*client)->command_reply_fds[0] = -1;
	(*client)->command_reply_fds[1] = -1;

	return 0;
free_error:
	cras_file_wait_destroy((*client)->sock_file_wait);
	free((void *)(*client)->sock_file);
free_server_event_fd:
	if ((*client)->server_event_fd >= 0)
		close((*client)->server_event_fd);
free_cond:
	pthread_cond_destroy(&(*client)->stream_start_cond);
free_lock:
	pthread_mutex_destroy(&(*client)->stream_start_lock);
free_rwlock:
	pthread_rwlock_destroy(&client_int->server_state_rwlock);
free_client:
	*client = NULL;
	free(client_int);
	return rc;
}

int cras_client_create(struct cras_client **client)
{
	return cras_client_create_with_type(client, CRAS_CONTROL);
}

void cras_client_destroy(struct cras_client *client)
{
	struct client_int *client_int;
	if (client == NULL)
		return;
	client_int = to_client_int(client);
	client->server_connection_cb = NULL;
	cras_client_stop(client);
	server_disconnect(client);
	close(client->server_event_fd);
	close(client->command_fds[0]);
	close(client->command_fds[1]);
	close(client->stream_fds[0]);
	close(client->stream_fds[1]);
	cras_file_wait_destroy(client->sock_file_wait);
	pthread_rwlock_destroy(&client_int->server_state_rwlock);
	free((void *)client->sock_file);
	free(client_int);
}

int cras_client_connect(struct cras_client *client)
{
	return connect_to_server(client, NULL, true);
}

int cras_client_connect_timeout(struct cras_client *client,
				unsigned int timeout_ms)
{
	return connect_to_server_wait_retry(client, timeout_ms, true);
}

int cras_client_connected_wait(struct cras_client *client)
{
	return send_simple_cmd_msg(client, 0, CLIENT_SERVER_CONNECT);
}

int cras_client_connect_async(struct cras_client *client)
{
	return send_simple_cmd_msg(client, 0, CLIENT_SERVER_CONNECT_ASYNC);
}

struct cras_stream_params *cras_client_stream_params_create(
	enum CRAS_STREAM_DIRECTION direction, size_t buffer_frames,
	size_t cb_threshold, size_t unused, enum CRAS_STREAM_TYPE stream_type,
	uint32_t flags, void *user_data, cras_playback_cb_t aud_cb,
	cras_error_cb_t err_cb, struct cras_audio_format *format)
{
	struct cras_stream_params *params;

	params = (struct cras_stream_params *)malloc(sizeof(*params));
	if (params == NULL)
		return NULL;

	params->direction = direction;
	params->buffer_frames = buffer_frames;
	params->cb_threshold = cb_threshold;
	params->effects = 0;
	params->stream_type = stream_type;
	params->client_type = CRAS_CLIENT_TYPE_UNKNOWN;
	params->flags = flags;
	params->user_data = user_data;
	params->aud_cb = aud_cb;
	params->unified_cb = 0;
	params->stream_cb = 0;
	params->err_cb = err_cb;
	memcpy(&(params->format), format, sizeof(*format));
	return params;
}

void cras_client_stream_params_set_client_type(
	struct cras_stream_params *params, enum CRAS_CLIENT_TYPE client_type)
{
	params->client_type = client_type;
}

void cras_client_stream_params_enable_aec(struct cras_stream_params *params)
{
	params->effects |= APM_ECHO_CANCELLATION;
}

void cras_client_stream_params_disable_aec(struct cras_stream_params *params)
{
	params->effects &= ~APM_ECHO_CANCELLATION;
}

void cras_client_stream_params_enable_ns(struct cras_stream_params *params)
{
	params->effects |= APM_NOISE_SUPRESSION;
}

void cras_client_stream_params_disable_ns(struct cras_stream_params *params)
{
	params->effects &= ~APM_NOISE_SUPRESSION;
}

void cras_client_stream_params_enable_agc(struct cras_stream_params *params)
{
	params->effects |= APM_GAIN_CONTROL;
}

void cras_client_stream_params_disable_agc(struct cras_stream_params *params)
{
	params->effects &= ~APM_GAIN_CONTROL;
}

void cras_client_stream_params_enable_vad(struct cras_stream_params *params)
{
	params->effects |= APM_VOICE_DETECTION;
}

void cras_client_stream_params_disable_vad(struct cras_stream_params *params)
{
	params->effects &= ~APM_VOICE_DETECTION;
}

struct cras_stream_params *cras_client_unified_params_create(
	enum CRAS_STREAM_DIRECTION direction, unsigned int block_size,
	enum CRAS_STREAM_TYPE stream_type, uint32_t flags, void *user_data,
	cras_unified_cb_t unified_cb, cras_error_cb_t err_cb,
	struct cras_audio_format *format)
{
	struct cras_stream_params *params;

	params = (struct cras_stream_params *)malloc(sizeof(*params));
	if (params == NULL)
		return NULL;

	params->direction = direction;
	params->buffer_frames = block_size * 2;
	params->cb_threshold = block_size;
	params->stream_type = stream_type;
	params->client_type = CRAS_CLIENT_TYPE_UNKNOWN;
	params->flags = flags;
	params->effects = 0;
	params->user_data = user_data;
	params->aud_cb = 0;
	params->unified_cb = unified_cb;
	params->stream_cb = 0;
	params->err_cb = err_cb;
	memcpy(&(params->format), format, sizeof(*format));

	return params;
}

void cras_client_stream_params_destroy(struct cras_stream_params *params)
{
	free(params);
}

static inline int cras_client_send_add_stream_command_message(
	struct cras_client *client, uint32_t dev_idx,
	cras_stream_id_t *stream_id_out, struct cras_stream_params *config)
{
	struct add_stream_command_message cmd_msg;
	struct client_stream *stream;
	int rc = 0;

	if (client == NULL || config == NULL || stream_id_out == NULL)
		return -EINVAL;

	if (config->stream_cb == NULL && config->aud_cb == NULL &&
	    config->unified_cb == NULL)
		return -EINVAL;

	if (config->err_cb == NULL)
		return -EINVAL;

	stream = (struct client_stream *)calloc(1, sizeof(*stream));
	if (stream == NULL) {
		rc = -ENOMEM;
		goto add_failed;
	}
	stream->config =
		(struct cras_stream_params *)malloc(sizeof(*(stream->config)));
	if (stream->config == NULL) {
		rc = -ENOMEM;
		goto add_failed;
	}
	memcpy(stream->config, config, sizeof(*config));
	stream->aud_fd = -1;
	stream->wake_fds[0] = -1;
	stream->wake_fds[1] = -1;
	stream->direction = config->direction;
	stream->flags = config->flags;

	/* Caller might not set this volume scaler after stream created,
	 * so always initialize it to 1.0f */
	stream->volume_scaler = 1.0f;

	cmd_msg.header.len = sizeof(cmd_msg);
	cmd_msg.header.msg_id = CLIENT_ADD_STREAM;
	cmd_msg.header.stream_id = stream->id;
	cmd_msg.stream = stream;
	cmd_msg.stream_id_out = stream_id_out;
	cmd_msg.dev_idx = dev_idx;
	rc = send_command_message(client, &cmd_msg.header);
	if (rc < 0) {
		syslog(LOG_ERR,
		       "cras_client: adding stream failed in thread %d", rc);
		goto add_failed;
	}

	return 0;

add_failed:
	if (stream) {
		if (stream->config)
			free(stream->config);
		free(stream);
	}
	return rc;
}

int cras_client_add_stream(struct cras_client *client,
			   cras_stream_id_t *stream_id_out,
			   struct cras_stream_params *config)
{
	return cras_client_send_add_stream_command_message(
		client, NO_DEVICE, stream_id_out, config);
}

int cras_client_add_pinned_stream(struct cras_client *client, uint32_t dev_idx,
				  cras_stream_id_t *stream_id_out,
				  struct cras_stream_params *config)
{
	return cras_client_send_add_stream_command_message(
		client, dev_idx, stream_id_out, config);
}

int cras_client_rm_stream(struct cras_client *client,
			  cras_stream_id_t stream_id)
{
	if (client == NULL)
		return -EINVAL;

	return send_simple_cmd_msg(client, stream_id, CLIENT_REMOVE_STREAM);
}

int cras_client_set_stream_volume(struct cras_client *client,
				  cras_stream_id_t stream_id,
				  float volume_scaler)
{
	if (client == NULL)
		return -EINVAL;

	return send_stream_volume_command_msg(client, stream_id, volume_scaler);
}

int cras_client_set_system_volume(struct cras_client *client, size_t volume)
{
	struct cras_set_system_volume msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_system_volume(&msg, volume);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_system_mute(struct cras_client *client, int mute)
{
	struct cras_set_system_mute msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_system_mute(&msg, mute);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_user_mute(struct cras_client *client, int mute)
{
	struct cras_set_system_mute msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_user_mute(&msg, mute);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_system_mute_locked(struct cras_client *client, int locked)
{
	struct cras_set_system_mute msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_system_mute_locked(&msg, locked);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_system_capture_mute(struct cras_client *client, int mute)
{
	struct cras_set_system_mute msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_system_capture_mute(&msg, mute);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_system_capture_mute_locked(struct cras_client *client,
					       int locked)
{
	struct cras_set_system_mute msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_system_capture_mute_locked(&msg, locked);
	return write_message_to_server(client, &msg.header);
}

size_t cras_client_get_system_volume(const struct cras_client *client)
{
	size_t volume;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	volume = client->server_state->volume;
	server_state_unlock(client, lock_rc);
	return volume;
}

long cras_client_get_system_capture_gain(const struct cras_client *client)
{
	long gain;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	gain = client->server_state->capture_gain;
	server_state_unlock(client, lock_rc);
	return gain;
}

int cras_client_get_system_muted(const struct cras_client *client)
{
	int muted;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	muted = client->server_state->mute;
	server_state_unlock(client, lock_rc);
	return muted;
}

int cras_client_get_user_muted(const struct cras_client *client)
{
	int muted;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	muted = client->server_state->user_mute;
	server_state_unlock(client, lock_rc);
	return muted;
}

int cras_client_get_system_capture_muted(const struct cras_client *client)
{
	int muted;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	muted = client->server_state->capture_mute;
	server_state_unlock(client, lock_rc);
	return muted;
}

long cras_client_get_system_min_volume(const struct cras_client *client)
{
	long min_volume;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	min_volume = client->server_state->min_volume_dBFS;
	server_state_unlock(client, lock_rc);
	return min_volume;
}

long cras_client_get_system_max_volume(const struct cras_client *client)
{
	long max_volume;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	max_volume = client->server_state->max_volume_dBFS;
	server_state_unlock(client, lock_rc);
	return max_volume;
}

int cras_client_get_default_output_buffer_size(struct cras_client *client)
{
	int default_output_buffer_size;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return -EINVAL;

	default_output_buffer_size =
		client->server_state->default_output_buffer_size;
	server_state_unlock(client, lock_rc);
	return default_output_buffer_size;
}

const struct audio_debug_info *
cras_client_get_audio_debug_info(const struct cras_client *client)
{
	const struct audio_debug_info *debug_info;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	debug_info = &client->server_state->audio_debug_info;
	server_state_unlock(client, lock_rc);
	return debug_info;
}

const struct main_thread_debug_info *
cras_client_get_main_thread_debug_info(const struct cras_client *client)
{
	const struct main_thread_debug_info *debug_info;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	debug_info = &client->server_state->main_thread_debug_info;
	server_state_unlock(client, lock_rc);
	return debug_info;
}

const struct cras_bt_debug_info *
cras_client_get_bt_debug_info(const struct cras_client *client)
{
	const struct cras_bt_debug_info *debug_info;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	debug_info = &client->server_state->bt_debug_info;
	server_state_unlock(client, lock_rc);
	return debug_info;
}

const struct cras_audio_thread_snapshot_buffer *
cras_client_get_audio_thread_snapshot_buffer(const struct cras_client *client)
{
	const struct cras_audio_thread_snapshot_buffer *snapshot_buffer;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	snapshot_buffer = &client->server_state->snapshot_buffer;
	server_state_unlock(client, lock_rc);
	return snapshot_buffer;
}

unsigned cras_client_get_num_active_streams(const struct cras_client *client,
					    struct timespec *ts)
{
	unsigned num_streams, version, i;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

read_active_streams_again:
	version = begin_server_state_read(client->server_state);
	num_streams = 0;
	for (i = 0; i < CRAS_NUM_DIRECTIONS; i++)
		num_streams += client->server_state->num_active_streams[i];
	if (ts) {
		if (num_streams)
			clock_gettime(CLOCK_MONOTONIC_RAW, ts);
		else
			cras_timespec_to_timespec(
				ts,
				&client->server_state->last_active_stream_time);
	}
	if (end_server_state_read(client->server_state, version))
		goto read_active_streams_again;

	server_state_unlock(client, lock_rc);
	return num_streams;
}

int cras_client_run_thread(struct cras_client *client)
{
	int rc;

	if (client == NULL)
		return -EINVAL;
	if (thread_is_running(&client->thread))
		return 0;

	assert(client->command_reply_fds[0] == -1 &&
	       client->command_reply_fds[1] == -1);

	if (pipe(client->command_reply_fds) < 0)
		return -EIO;
	client->thread.state = CRAS_THREAD_RUNNING;
	rc = pthread_create(&client->thread.tid, NULL, client_thread, client);
	if (rc) {
		client->thread.state = CRAS_THREAD_STOP;
		return -rc;
	}

	return 0;
}

int cras_client_stop(struct cras_client *client)
{
	if (client == NULL)
		return -EINVAL;
	if (!thread_is_running(&client->thread))
		return 0;

	send_simple_cmd_msg(client, 0, CLIENT_STOP);
	pthread_join(client->thread.tid, NULL);

	/* The other end of the reply pipe is closed by the client thread, just
	 * clost the read end here. */
	close(client->command_reply_fds[0]);
	client->command_reply_fds[0] = -1;

	return 0;
}

void cras_client_set_connection_status_cb(
	struct cras_client *client, cras_connection_status_cb_t connection_cb,
	void *user_arg)
{
	client->server_connection_cb = connection_cb;
	client->server_connection_user_arg = user_arg;
}

void cras_client_set_thread_priority_cb(struct cras_client *client,
					cras_thread_priority_cb_t cb)
{
	client->thread_priority_cb = cb;
}

int cras_client_get_output_devices(const struct cras_client *client,
				   struct cras_iodev_info *devs,
				   struct cras_ionode_info *nodes,
				   size_t *num_devs, size_t *num_nodes)
{
	const struct cras_server_state *state;
	unsigned avail_devs, avail_nodes, version;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return -EINVAL;
	state = client->server_state;

read_outputs_again:
	version = begin_server_state_read(state);
	avail_devs = MIN(*num_devs, state->num_output_devs);
	memcpy(devs, state->output_devs, avail_devs * sizeof(*devs));
	avail_nodes = MIN(*num_nodes, state->num_output_nodes);
	memcpy(nodes, state->output_nodes, avail_nodes * sizeof(*nodes));
	if (end_server_state_read(state, version))
		goto read_outputs_again;
	server_state_unlock(client, lock_rc);

	*num_devs = avail_devs;
	*num_nodes = avail_nodes;

	return 0;
}

int cras_client_get_input_devices(const struct cras_client *client,
				  struct cras_iodev_info *devs,
				  struct cras_ionode_info *nodes,
				  size_t *num_devs, size_t *num_nodes)
{
	const struct cras_server_state *state;
	unsigned avail_devs, avail_nodes, version;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (!client)
		return -EINVAL;
	state = client->server_state;

read_inputs_again:
	version = begin_server_state_read(state);
	avail_devs = MIN(*num_devs, state->num_input_devs);
	memcpy(devs, state->input_devs, avail_devs * sizeof(*devs));
	avail_nodes = MIN(*num_nodes, state->num_input_nodes);
	memcpy(nodes, state->input_nodes, avail_nodes * sizeof(*nodes));
	if (end_server_state_read(state, version))
		goto read_inputs_again;
	server_state_unlock(client, lock_rc);

	*num_devs = avail_devs;
	*num_nodes = avail_nodes;

	return 0;
}

int cras_client_get_attached_clients(const struct cras_client *client,
				     struct cras_attached_client_info *clients,
				     size_t max_clients)
{
	const struct cras_server_state *state;
	unsigned num, version;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return -EINVAL;
	state = client->server_state;

read_clients_again:
	version = begin_server_state_read(state);
	num = MIN(max_clients, state->num_attached_clients);
	memcpy(clients, state->client_info, num * sizeof(*clients));
	if (end_server_state_read(state, version))
		goto read_clients_again;
	server_state_unlock(client, lock_rc);

	return num;
}

/* Find an output ionode on an iodev with the matching name.
 *
 * Args:
 *    dev_name - The prefix of the iodev name.
 *    node_name - The prefix of the ionode name.
 *    dev_info - The information about the iodev will be returned here.
 *    node_info - The information about the ionode will be returned here.
 * Returns:
 *    0 if successful, -1 if the node cannot be found.
 */
static int cras_client_find_output_node(const struct cras_client *client,
					const char *dev_name,
					const char *node_name,
					struct cras_iodev_info *dev_info,
					struct cras_ionode_info *node_info)
{
	size_t ndevs, nnodes;
	struct cras_iodev_info *devs = NULL;
	struct cras_ionode_info *nodes = NULL;
	int rc = -1;
	unsigned i, j;

	if (!client || !dev_name || !node_name)
		goto quit;

	devs = (struct cras_iodev_info *)malloc(CRAS_MAX_IODEVS *
						sizeof(*devs));
	if (!devs)
		goto quit;

	nodes = (struct cras_ionode_info *)malloc(CRAS_MAX_IONODES *
						  sizeof(*nodes));
	if (!nodes)
		goto quit;

	ndevs = CRAS_MAX_IODEVS;
	nnodes = CRAS_MAX_IONODES;
	rc = cras_client_get_output_devices(client, devs, nodes, &ndevs,
					    &nnodes);
	if (rc < 0)
		goto quit;

	for (i = 0; i < ndevs; i++)
		if (!strncmp(dev_name, devs[i].name, strlen(dev_name)))
			goto found_dev;
	rc = -1;
	goto quit;

found_dev:
	for (j = 0; j < nnodes; j++)
		if (nodes[j].iodev_idx == devs[i].idx &&
		    !strncmp(node_name, nodes[j].name, strlen(node_name)))
			goto found_node;
	rc = -1;
	goto quit;

found_node:
	*dev_info = devs[i];
	*node_info = nodes[j];
	rc = 0;

quit:
	free(devs);
	free(nodes);
	return rc;
}

int cras_client_get_node_by_id(const struct cras_client *client, int input,
			       const cras_node_id_t node_id,
			       struct cras_ionode_info *node_info)
{
	size_t ndevs, nnodes;
	struct cras_iodev_info *devs = NULL;
	struct cras_ionode_info *nodes = NULL;
	int rc = -EINVAL;
	unsigned i;

	if (!client || !node_info) {
		rc = -EINVAL;
		goto quit;
	}

	devs = (struct cras_iodev_info *)malloc(CRAS_MAX_IODEVS *
						sizeof(*devs));
	if (!devs) {
		rc = -ENOMEM;
		goto quit;
	}

	nodes = (struct cras_ionode_info *)malloc(CRAS_MAX_IONODES *
						  sizeof(*nodes));
	if (!nodes) {
		rc = -ENOMEM;
		goto quit;
	}

	ndevs = CRAS_MAX_IODEVS;
	nnodes = CRAS_MAX_IONODES;
	if (input)
		rc = cras_client_get_input_devices(client, devs, nodes, &ndevs,
						   &nnodes);
	else
		rc = cras_client_get_output_devices(client, devs, nodes, &ndevs,
						    &nnodes);
	if (rc < 0)
		goto quit;

	rc = -ENOENT;
	for (i = 0; i < nnodes; i++) {
		if (node_id == cras_make_node_id(nodes[i].iodev_idx,
						 nodes[i].ionode_idx)) {
			memcpy(node_info, &nodes[i], sizeof(*node_info));
			rc = 0;
			break;
		}
	}

quit:
	free(devs);
	free(nodes);
	return rc;
}

int cras_client_output_dev_plugged(const struct cras_client *client,
				   const char *name)
{
	struct cras_iodev_info dev_info;
	struct cras_ionode_info node_info = { 0 };

	if (cras_client_find_output_node(client, name, "Front Headphone Jack",
					 &dev_info, &node_info) < 0)
		return 0;

	return node_info.plugged;
}

int cras_client_set_node_attr(struct cras_client *client,
			      cras_node_id_t node_id, enum ionode_attr attr,
			      int value)
{
	struct cras_set_node_attr msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_node_attr(&msg, node_id, attr, value);
	return write_message_to_server(client, &msg.header);
}

int cras_client_select_node(struct cras_client *client,
			    enum CRAS_STREAM_DIRECTION direction,
			    cras_node_id_t node_id)
{
	struct cras_select_node msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_select_node(&msg, direction, node_id);
	return write_message_to_server(client, &msg.header);
}

int cras_client_add_active_node(struct cras_client *client,
				enum CRAS_STREAM_DIRECTION direction,
				cras_node_id_t node_id)
{
	struct cras_add_active_node msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_add_active_node(&msg, direction, node_id);
	return write_message_to_server(client, &msg.header);
}

int cras_client_rm_active_node(struct cras_client *client,
			       enum CRAS_STREAM_DIRECTION direction,
			       cras_node_id_t node_id)
{
	struct cras_rm_active_node msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_rm_active_node(&msg, direction, node_id);
	return write_message_to_server(client, &msg.header);
}

int cras_client_format_bytes_per_frame(struct cras_audio_format *fmt)
{
	if (fmt == NULL)
		return -EINVAL;

	return cras_get_format_bytes(fmt);
}

int cras_client_calc_playback_latency(const struct timespec *sample_time,
				      struct timespec *delay)
{
	struct timespec now;

	if (delay == NULL)
		return -EINVAL;

	clock_gettime(CLOCK_MONOTONIC_RAW, &now);

	/* for output return time until sample is played (t - now) */
	subtract_timespecs(sample_time, &now, delay);
	return 0;
}

int cras_client_calc_capture_latency(const struct timespec *sample_time,
				     struct timespec *delay)
{
	struct timespec now;

	if (delay == NULL)
		return -EINVAL;

	clock_gettime(CLOCK_MONOTONIC_RAW, &now);

	/* For input want time since sample read (now - t) */
	subtract_timespecs(&now, sample_time, delay);
	return 0;
}

int cras_client_reload_dsp(struct cras_client *client)
{
	struct cras_reload_dsp msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_reload_dsp(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_dump_dsp_info(struct cras_client *client)
{
	struct cras_dump_dsp_info msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_dump_dsp_info(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_update_audio_debug_info(
	struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
{
	struct cras_dump_audio_thread msg;

	if (client == NULL)
		return -EINVAL;

	if (client->debug_info_callback != NULL)
		return -EINVAL;
	client->debug_info_callback = debug_info_cb;

	cras_fill_dump_audio_thread(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_get_atlog_access(struct cras_client *client,
				 void (*atlog_access_cb)(struct cras_client *))
{
	struct cras_get_atlog_fd msg;

	if (client == NULL)
		return -EINVAL;

	if (client->atlog_access_callback != NULL)
		return -EINVAL;
	client->atlog_access_callback = atlog_access_cb;

	cras_fill_get_atlog_fd(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_read_atlog(struct cras_client *client, uint64_t *read_idx,
			   uint64_t *missing,
			   struct audio_thread_event_log *buf)
{
	struct audio_thread_event_log log;
	uint64_t i, sync_write_pos, len = 0;
	struct timespec timestamp, last_timestamp;

	if (!client->atlog_ro)
		return -EINVAL;

	sync_write_pos = client->atlog_ro->sync_write_pos;
	__sync_synchronize();
	memcpy(&log, client->atlog_ro, sizeof(log));

	if (sync_write_pos <= *read_idx)
		return 0;

	*missing = 0;
	for (i = sync_write_pos - 1; i >= *read_idx; --i) {
		uint64_t pos = i % log.len;
		timestamp.tv_sec = log.log[pos].tag_sec & 0x00ffffff;
		timestamp.tv_nsec = log.log[pos].nsec;

		if (i != sync_write_pos - 1 &&
		    timespec_after(&timestamp, &last_timestamp)) {
			if (*read_idx)
				*missing = i - *read_idx + 1;
			*read_idx = i + 1;
			break;
		}
		last_timestamp = timestamp;

		if (!i)
			break;
	}

	/* Copies the continuous part of log. */
	if ((sync_write_pos - 1) % log.len < *read_idx % log.len) {
		len = log.len - *read_idx % log.len;
		memcpy(buf->log, &log.log[*read_idx % log.len],
		       sizeof(struct audio_thread_event) * len);
		memcpy(&buf->log[len], log.log,
		       sizeof(struct audio_thread_event) *
			       ((sync_write_pos - 1) % log.len + 1));
		len = sync_write_pos - *read_idx;
	} else {
		len = sync_write_pos - *read_idx;
		memcpy(buf->log, &log.log[*read_idx % log.len],
		       sizeof(struct audio_thread_event) * len);
	}

	*read_idx = sync_write_pos;
	return len;
}

int cras_client_update_main_thread_debug_info(
	struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
{
	struct cras_dump_main msg;

	if (client == NULL)
		return -EINVAL;
	if (client->debug_info_callback != NULL)
		return -EINVAL;
	client->debug_info_callback = debug_info_cb;
	cras_fill_dump_main(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_update_bt_debug_info(
	struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
{
	struct cras_dump_bt msg;

	if (client == NULL)
		return -EINVAL;

	if (client->debug_info_callback != NULL)
		return -EINVAL;
	client->debug_info_callback = debug_info_cb;

	cras_fill_dump_bt(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_update_audio_thread_snapshots(
	struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
{
	struct cras_dump_snapshots msg;

	if (client == NULL)
		return -EINVAL;

	if (client->debug_info_callback != NULL)
		return -EINVAL;
	client->debug_info_callback = debug_info_cb;

	cras_fill_dump_snapshots(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_get_max_supported_channels(const struct cras_client *client,
					   cras_node_id_t node_id,
					   uint32_t *max_channels)
{
	size_t ndevs, nnodes;
	struct cras_iodev_info *devs = NULL;
	struct cras_ionode_info *nodes = NULL;
	int rc = -EINVAL;
	unsigned i;

	if (!client) {
		rc = -EINVAL;
		goto quit;
	}

	devs = (struct cras_iodev_info *)malloc(CRAS_MAX_IODEVS *
						sizeof(*devs));
	if (!devs) {
		rc = -ENOMEM;
		goto quit;
	}

	nodes = (struct cras_ionode_info *)malloc(CRAS_MAX_IONODES *
						  sizeof(*nodes));
	if (!nodes) {
		rc = -ENOMEM;
		goto quit;
	}

	ndevs = CRAS_MAX_IODEVS;
	nnodes = CRAS_MAX_IONODES;
	rc = cras_client_get_output_devices(client, devs, nodes, &ndevs,
					    &nnodes);
	if (rc < 0)
		goto quit;

	rc = -ENOENT;
	uint32_t iodev_idx;
	for (i = 0; i < nnodes; i++) {
		if (node_id == cras_make_node_id(nodes[i].iodev_idx,
						 nodes[i].ionode_idx)) {
			iodev_idx = nodes[i].iodev_idx;
			rc = 0;
			break;
		}
	}

	if (rc < 0)
		goto quit;

	rc = -ENOENT;
	for (i = 0; i < ndevs; i++) {
		if (iodev_idx == devs[i].idx) {
			*max_channels = devs[i].max_supported_channels;
			rc = 0;
			break;
		}
	}

quit:
	free(devs);
	free(nodes);
	return rc;
}

int cras_client_set_node_volume(struct cras_client *client,
				cras_node_id_t node_id, uint8_t volume)
{
	struct cras_set_node_attr msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_node_attr(&msg, node_id, IONODE_ATTR_VOLUME, volume);
	return write_message_to_server(client, &msg.header);
}

int cras_client_swap_node_left_right(struct cras_client *client,
				     cras_node_id_t node_id, int enable)
{
	struct cras_set_node_attr msg;

	if (client == NULL)
		return -EINVAL;

	cras_fill_set_node_attr(&msg, node_id, IONODE_ATTR_SWAP_LEFT_RIGHT,
				enable);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_node_capture_gain(struct cras_client *client,
				      cras_node_id_t node_id, long gain)
{
	struct cras_set_node_attr msg;

	if (client == NULL)
		return -EINVAL;
	if (gain > INT_MAX || gain < INT_MIN)
		return -EINVAL;

	cras_fill_set_node_attr(&msg, node_id, IONODE_ATTR_CAPTURE_GAIN, gain);
	return write_message_to_server(client, &msg.header);
}

int cras_client_add_test_iodev(struct cras_client *client,
			       enum TEST_IODEV_TYPE type)
{
	struct cras_add_test_dev msg;

	cras_fill_add_test_dev(&msg, type);
	return write_message_to_server(client, &msg.header);
}

int cras_client_test_iodev_command(struct cras_client *client,
				   unsigned int iodev_idx,
				   enum CRAS_TEST_IODEV_CMD command,
				   unsigned int data_len, const uint8_t *data)
{
	struct cras_test_dev_command *msg;
	int rc;

	msg = (struct cras_test_dev_command *)malloc(sizeof(*msg) + data_len);
	cras_fill_test_dev_command(msg, iodev_idx, command, data_len, data);
	rc = write_message_to_server(client, &msg->header);
	free(msg);
	return rc;
}

int cras_client_config_global_remix(struct cras_client *client,
				    unsigned num_channels, float *coefficient)
{
	struct cras_config_global_remix *msg;
	int rc;
	size_t nchan = (size_t)num_channels;

	msg = (struct cras_config_global_remix *)malloc(
		sizeof(*msg) + nchan * nchan * sizeof(*coefficient));
	cras_fill_config_global_remix_command(msg, num_channels, coefficient,
					      num_channels * num_channels);
	rc = write_message_to_server(client, &msg->header);
	free(msg);
	return rc;
}

int cras_client_get_first_node_type_idx(const struct cras_client *client,
					enum CRAS_NODE_TYPE type,
					enum CRAS_STREAM_DIRECTION direction,
					cras_node_id_t *node_id)
{
	const struct cras_server_state *state;
	unsigned int version;
	unsigned int i;
	const struct cras_ionode_info *node_list;
	unsigned int num_nodes;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return -EINVAL;
	state = client->server_state;

read_nodes_again:
	version = begin_server_state_read(state);
	if (direction == CRAS_STREAM_OUTPUT) {
		node_list = state->output_nodes;
		num_nodes = state->num_output_nodes;
	} else {
		node_list = state->input_nodes;
		num_nodes = state->num_input_nodes;
	}
	for (i = 0; i < num_nodes; i++) {
		if ((enum CRAS_NODE_TYPE)node_list[i].type_enum == type) {
			*node_id = cras_make_node_id(node_list[i].iodev_idx,
						     node_list[i].ionode_idx);
			server_state_unlock(client, lock_rc);
			return 0;
		}
	}
	if (end_server_state_read(state, version))
		goto read_nodes_again;
	server_state_unlock(client, lock_rc);

	return -ENODEV;
}

int cras_client_get_first_dev_type_idx(const struct cras_client *client,
				       enum CRAS_NODE_TYPE type,
				       enum CRAS_STREAM_DIRECTION direction)
{
	cras_node_id_t node_id;
	int rc;

	rc = cras_client_get_first_node_type_idx(client, type, direction,
						 &node_id);
	if (rc)
		return rc;

	return dev_index_of(node_id);
}

int cras_client_set_suspend(struct cras_client *client, int suspend)
{
	struct cras_server_message msg;

	cras_fill_suspend_message(&msg, suspend);
	return write_message_to_server(client, &msg);
}

int cras_client_get_hotword_models(struct cras_client *client,
				   cras_node_id_t node_id,
				   get_hotword_models_cb_t cb)
{
	struct cras_get_hotword_models msg;

	if (!client)
		return -EINVAL;
	client->get_hotword_models_cb = cb;

	cras_fill_get_hotword_models_message(&msg, node_id);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_hotword_model(struct cras_client *client,
				  cras_node_id_t node_id,
				  const char *model_name)
{
	struct cras_set_hotword_model msg;

	cras_fill_set_hotword_model_message(&msg, node_id, model_name);
	return write_message_to_server(client, &msg.header);
}

int cras_client_set_aec_dump(struct cras_client *client,
			     cras_stream_id_t stream_id, int start, int fd)
{
	struct cras_set_aec_dump msg;

	cras_fill_set_aec_dump_message(&msg, stream_id, start);

	if (fd != -1)
		return cras_send_with_fds(client->server_fd, &msg, sizeof(msg),
					  &fd, 1);
	else
		return write_message_to_server(client, &msg.header);
}

int cras_client_reload_aec_config(struct cras_client *client)
{
	struct cras_reload_aec_config msg;

	cras_fill_reload_aec_config(&msg);
	return write_message_to_server(client, &msg.header);
}

int cras_client_get_aec_supported(struct cras_client *client)
{
	int aec_supported;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return 0;

	aec_supported = client->server_state->aec_supported;
	server_state_unlock(client, lock_rc);
	return aec_supported;
}

int cras_client_get_aec_group_id(struct cras_client *client)
{
	int aec_group_id;
	int lock_rc;

	lock_rc = server_state_rdlock(client);
	if (lock_rc)
		return -1;

	aec_group_id = client->server_state->aec_group_id;
	server_state_unlock(client, lock_rc);
	return aec_group_id;
}

int cras_client_set_bt_wbs_enabled(struct cras_client *client, bool enabled)
{
	struct cras_set_bt_wbs_enabled msg;

	cras_fill_set_bt_wbs_enabled(&msg, enabled);
	return write_message_to_server(client, &msg.header);
}

void cras_client_set_state_change_callback_context(struct cras_client *client,
						   void *context)
{
	if (!client)
		return;
	client->observer_context = context;
}

static int cras_send_register_notification(struct cras_client *client,
					   enum CRAS_CLIENT_MESSAGE_ID msg_id,
					   int do_register)
{
	struct cras_register_notification msg;
	int rc;

	/* This library automatically re-registers notifications when
	 * reconnecting, so we can ignore message send failure due to no
	 * connection. */
	cras_fill_register_notification_message(&msg, msg_id, do_register);
	rc = write_message_to_server(client, &msg.header);
	if (rc == -EPIPE)
		rc = 0;
	return rc;
}

int cras_client_set_output_volume_changed_callback(
	struct cras_client *client,
	cras_client_output_volume_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.output_volume_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_OUTPUT_VOLUME_CHANGED, cb != NULL);
}

int cras_client_set_output_mute_changed_callback(
	struct cras_client *client, cras_client_output_mute_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.output_mute_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_OUTPUT_MUTE_CHANGED, cb != NULL);
}

int cras_client_set_capture_gain_changed_callback(
	struct cras_client *client,
	cras_client_capture_gain_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.capture_gain_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_CAPTURE_GAIN_CHANGED, cb != NULL);
}

int cras_client_set_capture_mute_changed_callback(
	struct cras_client *client,
	cras_client_capture_mute_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.capture_mute_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_CAPTURE_MUTE_CHANGED, cb != NULL);
}

int cras_client_set_nodes_changed_callback(
	struct cras_client *client, cras_client_nodes_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.nodes_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_NODES_CHANGED, cb != NULL);
}

int cras_client_set_active_node_changed_callback(
	struct cras_client *client, cras_client_active_node_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.active_node_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_ACTIVE_NODE_CHANGED, cb != NULL);
}

int cras_client_set_output_node_volume_changed_callback(
	struct cras_client *client,
	cras_client_output_node_volume_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.output_node_volume_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED, cb != NULL);
}

int cras_client_set_node_left_right_swapped_changed_callback(
	struct cras_client *client,
	cras_client_node_left_right_swapped_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.node_left_right_swapped_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED,
		cb != NULL);
}

int cras_client_set_input_node_gain_changed_callback(
	struct cras_client *client,
	cras_client_input_node_gain_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.input_node_gain_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED, cb != NULL);
}

int cras_client_set_num_active_streams_changed_callback(
	struct cras_client *client,
	cras_client_num_active_streams_changed_callback cb)
{
	if (!client)
		return -EINVAL;
	client->observer_ops.num_active_streams_changed = cb;
	return cras_send_register_notification(
		client, CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED, cb != NULL);
}

static int reregister_notifications(struct cras_client *client)
{
	int rc;

	if (client->observer_ops.output_volume_changed) {
		rc = cras_client_set_output_volume_changed_callback(
			client, client->observer_ops.output_volume_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.output_mute_changed) {
		rc = cras_client_set_output_mute_changed_callback(
			client, client->observer_ops.output_mute_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.capture_gain_changed) {
		rc = cras_client_set_capture_gain_changed_callback(
			client, client->observer_ops.capture_gain_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.capture_mute_changed) {
		rc = cras_client_set_capture_mute_changed_callback(
			client, client->observer_ops.capture_mute_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.nodes_changed) {
		rc = cras_client_set_nodes_changed_callback(
			client, client->observer_ops.nodes_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.active_node_changed) {
		rc = cras_client_set_active_node_changed_callback(
			client, client->observer_ops.active_node_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.output_node_volume_changed) {
		rc = cras_client_set_output_node_volume_changed_callback(
			client,
			client->observer_ops.output_node_volume_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.node_left_right_swapped_changed) {
		rc = cras_client_set_node_left_right_swapped_changed_callback(
			client,
			client->observer_ops.node_left_right_swapped_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.input_node_gain_changed) {
		rc = cras_client_set_input_node_gain_changed_callback(
			client, client->observer_ops.input_node_gain_changed);
		if (rc != 0)
			return rc;
	}
	if (client->observer_ops.num_active_streams_changed) {
		rc = cras_client_set_num_active_streams_changed_callback(
			client,
			client->observer_ops.num_active_streams_changed);
		if (rc != 0)
			return rc;
	}
	return 0;
}

static int hotword_read_cb(struct cras_client *client,
			   cras_stream_id_t stream_id,
			   uint8_t *captured_samples, uint8_t *playback_samples,
			   unsigned int frames,
			   const struct timespec *captured_time,
			   const struct timespec *playback_time, void *user_arg)
{
	struct cras_hotword_handle *handle;

	handle = (struct cras_hotword_handle *)user_arg;
	if (handle->trigger_cb)
		handle->trigger_cb(client, handle, handle->user_data);

	return 0;
}

static int hotword_err_cb(struct cras_client *client,
			  cras_stream_id_t stream_id, int error, void *user_arg)
{
	struct cras_hotword_handle *handle;

	handle = (struct cras_hotword_handle *)user_arg;
	if (handle->err_cb)
		handle->err_cb(client, handle, error, handle->user_data);

	return 0;
}

int cras_client_enable_hotword_callback(struct cras_client *client,
					void *user_data,
					cras_hotword_trigger_cb_t trigger_cb,
					cras_hotword_error_cb_t err_cb,
					struct cras_hotword_handle **handle_out)
{
	struct cras_hotword_handle *handle;
	int ret = 0;

	if (!client)
		return -EINVAL;

	handle = (struct cras_hotword_handle *)calloc(1, sizeof(*handle));
	if (!handle)
		return -ENOMEM;

	handle->format = cras_audio_format_create(SND_PCM_FORMAT_S16_LE,
						  HOTWORD_FRAME_RATE, 1);
	if (!handle->format) {
		ret = -ENOMEM;
		goto cleanup;
	}

	handle->params = cras_client_unified_params_create(
		CRAS_STREAM_INPUT, HOTWORD_BLOCK_SIZE, CRAS_STREAM_TYPE_DEFAULT,
		HOTWORD_STREAM | TRIGGER_ONLY, (void *)handle, hotword_read_cb,
		hotword_err_cb, handle->format);
	if (!handle->params) {
		ret = -ENOMEM;
		goto cleanup_format;
	}

	handle->trigger_cb = trigger_cb;
	handle->err_cb = err_cb;
	handle->user_data = user_data;

	ret = cras_client_add_stream(client, &handle->stream_id,
				     handle->params);
	if (ret)
		goto cleanup_params;

	*handle_out = handle;
	return 0;

cleanup_params:
	cras_client_stream_params_destroy(handle->params);
cleanup_format:
	cras_audio_format_destroy(handle->format);
cleanup:
	free(handle);
	return ret;
}

int cras_client_disable_hotword_callback(struct cras_client *client,
					 struct cras_hotword_handle *handle)
{
	if (!client || !handle)
		return -EINVAL;

	cras_client_rm_stream(client, handle->stream_id);
	cras_audio_format_destroy(handle->format);
	cras_client_stream_params_destroy(handle->params);
	free(handle);
	return 0;
}

int get_nodes(struct cras_client *client, enum CRAS_STREAM_DIRECTION direction,
	      struct libcras_node_info ***nodes, size_t *num)
{
	struct cras_iodev_info iodevs[CRAS_MAX_IODEVS];
	struct cras_ionode_info ionodes[CRAS_MAX_IONODES];
	size_t num_devs = CRAS_MAX_IODEVS, num_nodes = CRAS_MAX_IONODES;
	int rc, i, j;

	*num = 0;
	if (direction == CRAS_STREAM_INPUT) {
		rc = cras_client_get_input_devices(client, iodevs, ionodes,
						   &num_devs, &num_nodes);
	} else {
		rc = cras_client_get_output_devices(client, iodevs, ionodes,
						    &num_devs, &num_nodes);
	}

	if (rc < 0) {
		syslog(LOG_ERR, "Failed to get devices: %d", rc);
		return rc;
	}

	*nodes = (struct libcras_node_info **)calloc(
		num_nodes, sizeof(struct libcras_node_info *));

	for (i = 0; i < num_devs; i++) {
		for (j = 0; j < num_nodes; j++) {
			if (iodevs[i].idx != ionodes[j].iodev_idx)
				continue;
			(*nodes)[*num] = libcras_node_info_create(&iodevs[i],
								  &ionodes[j]);
			if ((*nodes)[*num] == NULL) {
				rc = -errno;
				goto clean;
			}
			(*num)++;
		}
	}
	return 0;
clean:
	for (i = 0; i < *num; i++)
		libcras_node_info_destroy((*nodes)[i]);
	free(*nodes);
	*nodes = NULL;
	*num = 0;
	return rc;
}

int get_default_output_buffer_size(struct cras_client *client, int *size)
{
	int rc = cras_client_get_default_output_buffer_size(client);
	if (rc < 0)
		return rc;
	*size = rc;
	return 0;
}

int get_aec_group_id(struct cras_client *client, int *id)
{
	int rc = cras_client_get_aec_group_id(client);
	if (rc < 0)
		return rc;
	*id = rc;
	return 0;
}

int get_aec_supported(struct cras_client *client, int *supported)
{
	*supported = cras_client_get_aec_supported(client);
	return 0;
}

int get_system_muted(struct cras_client *client, int *muted)
{
	*muted = cras_client_get_system_muted(client);
	return 0;
}

int get_loopback_dev_idx(struct cras_client *client, int *idx)
{
	int rc = cras_client_get_first_dev_type_idx(
		client, CRAS_NODE_TYPE_POST_MIX_PRE_DSP, CRAS_STREAM_INPUT);
	if (rc < 0)
		return rc;
	*idx = rc;
	return 0;
}

struct libcras_client *libcras_client_create()
{
	struct libcras_client *client = (struct libcras_client *)calloc(
		1, sizeof(struct libcras_client));
	if (!client) {
		syslog(LOG_ERR, "cras_client: calloc failed");
		return NULL;
	}
	if (cras_client_create(&client->client_)) {
		libcras_client_destroy(client);
		return NULL;
	}
	client->api_version = CRAS_API_VERSION;
	client->connect = cras_client_connect;
	client->connect_timeout = cras_client_connect_timeout;
	client->connected_wait = cras_client_connected_wait;
	client->run_thread = cras_client_run_thread;
	client->stop = cras_client_stop;
	client->add_pinned_stream = cras_client_add_pinned_stream;
	client->rm_stream = cras_client_rm_stream;
	client->set_stream_volume = cras_client_set_stream_volume;
	client->get_nodes = get_nodes;
	client->get_default_output_buffer_size = get_default_output_buffer_size;
	client->get_aec_group_id = get_aec_group_id;
	client->get_aec_supported = get_aec_supported;
	client->get_system_muted = get_system_muted;
	client->set_system_mute = cras_client_set_system_mute;
	client->get_loopback_dev_idx = get_loopback_dev_idx;
	return client;
}

void libcras_client_destroy(struct libcras_client *client)
{
	cras_client_destroy(client->client_);
	free(client);
}

int stream_params_set(struct cras_stream_params *params,
		      enum CRAS_STREAM_DIRECTION direction,
		      size_t buffer_frames, size_t cb_threshold,
		      enum CRAS_STREAM_TYPE stream_type,
		      enum CRAS_CLIENT_TYPE client_type, uint32_t flags,
		      void *user_data, libcras_stream_cb_t stream_cb,
		      cras_error_cb_t err_cb, size_t rate,
		      snd_pcm_format_t format, size_t num_channels)
{
	params->direction = direction;
	params->buffer_frames = buffer_frames;
	params->cb_threshold = cb_threshold;
	params->stream_type = stream_type;
	params->client_type = client_type;
	params->flags = flags;
	params->user_data = user_data;
	params->stream_cb = stream_cb;
	params->err_cb = err_cb;
	params->format.frame_rate = rate;
	params->format.format = format;
	params->format.num_channels = num_channels;
	return 0;
}

int stream_params_set_channel_layout(struct cras_stream_params *params,
				     int length, const int8_t *layout)
{
	if (length != CRAS_CH_MAX)
		return -EINVAL;
	return cras_audio_format_set_channel_layout(&params->format, layout);
}

struct libcras_stream_params *libcras_stream_params_create()
{
	struct libcras_stream_params *params =
		(struct libcras_stream_params *)calloc(
			1, sizeof(struct libcras_stream_params));
	if (!params) {
		syslog(LOG_ERR, "cras_client: calloc failed");
		return NULL;
	}
	params->params_ = (struct cras_stream_params *)calloc(
		1, sizeof(struct cras_stream_params));
	if (params->params_ == NULL) {
		syslog(LOG_ERR, "cras_client: calloc failed");
		free(params->params_);
		return NULL;
	}
	params->api_version = CRAS_API_VERSION;
	params->set = stream_params_set;
	params->set_channel_layout = stream_params_set_channel_layout;
	params->enable_aec = cras_client_stream_params_enable_aec;
	return params;
}

void libcras_stream_params_destroy(struct libcras_stream_params *params)
{
	free(params->params_);
	free(params);
}

struct cras_node_info {
	uint64_t id;
	uint32_t dev_idx;
	uint32_t node_idx;
	uint32_t max_supported_channels;
	bool plugged;
	bool active;
	char type[CRAS_NODE_TYPE_BUFFER_SIZE];
	char node_name[CRAS_NODE_NAME_BUFFER_SIZE];
	char dev_name[CRAS_IODEV_NAME_BUFFER_SIZE];
};

int cras_node_info_get_id(struct cras_node_info *node, uint64_t *id)
{
	(*id) = node->id;
	return 0;
}

int cras_node_info_get_dev_idx(struct cras_node_info *node, uint32_t *dev_idx)
{
	(*dev_idx) = node->dev_idx;
	return 0;
}

int cras_node_info_get_node_idx(struct cras_node_info *node, uint32_t *node_idx)
{
	(*node_idx) = node->node_idx;
	return 0;
}

int cras_node_info_get_max_supported_channels(struct cras_node_info *node,
					      uint32_t *max_supported_channels)
{
	(*max_supported_channels) = node->max_supported_channels;
	return 0;
}

int cras_node_info_is_plugged(struct cras_node_info *node, bool *is_plugged)
{
	(*is_plugged) = node->plugged;
	return 0;
}

int cras_node_info_is_active(struct cras_node_info *node, bool *is_active)
{
	(*is_active) = node->active;
	return 0;
}

int cras_node_info_get_type(struct cras_node_info *node, char **type)
{
	(*type) = node->type;
	return 0;
}

int cras_node_info_get_node_name(struct cras_node_info *node, char **node_name)
{
	(*node_name) = node->node_name;
	return 0;
}

int cras_node_info_get_dev_name(struct cras_node_info *node, char **dev_name)
{
	(*dev_name) = node->dev_name;
	return 0;
}

struct libcras_node_info *
libcras_node_info_create(struct cras_iodev_info *iodev,
			 struct cras_ionode_info *ionode)
{
	struct libcras_node_info *node = (struct libcras_node_info *)calloc(
		1, sizeof(struct libcras_node_info));
	if (!node) {
		syslog(LOG_ERR, "cras_client: calloc failed");
		return NULL;
	}
	node->node_ = (struct cras_node_info *)calloc(
		1, sizeof(struct cras_node_info));
	if (node->node_ == NULL) {
		syslog(LOG_ERR, "cras_client: calloc failed");
		free(node);
		return NULL;
	}
	node->api_version = CRAS_API_VERSION;
	node->node_->id =
		cras_make_node_id(ionode->iodev_idx, ionode->ionode_idx);
	node->node_->dev_idx = ionode->iodev_idx;
	node->node_->node_idx = ionode->ionode_idx;
	node->node_->max_supported_channels = iodev->max_supported_channels;
	node->node_->plugged = ionode->plugged;
	node->node_->active = ionode->active;
	strncpy(node->node_->type, ionode->type, CRAS_NODE_TYPE_BUFFER_SIZE);
	node->node_->type[CRAS_NODE_TYPE_BUFFER_SIZE - 1] = '\0';
	strncpy(node->node_->node_name, ionode->name,
		CRAS_NODE_NAME_BUFFER_SIZE);
	node->node_->node_name[CRAS_NODE_NAME_BUFFER_SIZE - 1] = '\0';
	strncpy(node->node_->dev_name, iodev->name,
		CRAS_IODEV_NAME_BUFFER_SIZE);
	node->node_->dev_name[CRAS_IODEV_NAME_BUFFER_SIZE - 1] = '\0';
	node->get_id = cras_node_info_get_id;
	node->get_dev_idx = cras_node_info_get_dev_idx;
	node->get_node_idx = cras_node_info_get_node_idx;
	node->get_max_supported_channels =
		cras_node_info_get_max_supported_channels;
	node->is_plugged = cras_node_info_is_plugged;
	node->is_active = cras_node_info_is_active;
	node->get_type = cras_node_info_get_type;
	node->get_node_name = cras_node_info_get_node_name;
	node->get_dev_name = cras_node_info_get_dev_name;
	return node;
}

void libcras_node_info_destroy(struct libcras_node_info *node)
{
	free(node->node_);
	free(node);
}

void libcras_node_info_array_destroy(struct libcras_node_info **nodes,
				     size_t num)
{
	int i;
	for (i = 0; i < num; i++)
		libcras_node_info_destroy(nodes[i]);
	free(nodes);
}