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
|
/* //device/include/server/AudioFlinger/AudioFlinger.cpp
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#define LOG_TAG "AudioFlinger"
//#define LOG_NDEBUG 0
#include <math.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
#include <binder/Parcel.h>
#include <binder/IPCThreadState.h>
#include <utils/String16.h>
#include <utils/threads.h>
#include <cutils/properties.h>
#include <media/AudioTrack.h>
#include <media/AudioRecord.h>
#include <private/media/AudioTrackShared.h>
#include <hardware_legacy/AudioHardwareInterface.h>
#include "AudioMixer.h"
#include "AudioFlinger.h"
#ifdef WITH_A2DP
#include "A2dpAudioInterface.h"
#endif
// ----------------------------------------------------------------------------
// the sim build doesn't have gettid
#ifndef HAVE_GETTID
# define gettid getpid
#endif
// ----------------------------------------------------------------------------
namespace android {
static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
static const char* kHardwareLockedString = "Hardware lock is taken\n";
//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
static const unsigned long kBufferRecoveryInUsecs = 2000;
static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
static const float MAX_GAIN = 4096.0f;
// retry counts for buffer fill timeout
// 50 * ~20msecs = 1 second
static const int8_t kMaxTrackRetries = 50;
static const int8_t kMaxTrackStartupRetries = 50;
static const int kDumpLockRetries = 50;
static const int kDumpLockSleep = 20000;
#define AUDIOFLINGER_SECURITY_ENABLED 1
// ----------------------------------------------------------------------------
static bool recordingAllowed() {
#ifndef HAVE_ANDROID_OS
return true;
#endif
#if AUDIOFLINGER_SECURITY_ENABLED
if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
return ok;
#else
if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
return true;
#endif
}
static bool settingsAllowed() {
#ifndef HAVE_ANDROID_OS
return true;
#endif
#if AUDIOFLINGER_SECURITY_ENABLED
if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
return ok;
#else
if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
return true;
#endif
}
// ----------------------------------------------------------------------------
AudioFlinger::AudioFlinger()
: BnAudioFlinger(),
mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
{
mHardwareStatus = AUDIO_HW_IDLE;
mAudioHardware = AudioHardwareInterface::create();
mHardwareStatus = AUDIO_HW_INIT;
if (mAudioHardware->initCheck() == NO_ERROR) {
// open 16-bit output stream for s/w mixer
setMode(AudioSystem::MODE_NORMAL);
setMasterVolume(1.0f);
setMasterMute(false);
} else {
LOGE("Couldn't even initialize the stubbed audio hardware!");
}
}
AudioFlinger::~AudioFlinger()
{
while (!mRecordThreads.isEmpty()) {
// closeInput() will remove first entry from mRecordThreads
closeInput(mRecordThreads.keyAt(0));
}
while (!mPlaybackThreads.isEmpty()) {
// closeOutput() will remove first entry from mPlaybackThreads
closeOutput(mPlaybackThreads.keyAt(0));
}
if (mAudioHardware) {
delete mAudioHardware;
}
}
status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
result.append("Clients:\n");
for (size_t i = 0; i < mClients.size(); ++i) {
wp<Client> wClient = mClients.valueAt(i);
if (wClient != 0) {
sp<Client> client = wClient.promote();
if (client != 0) {
snprintf(buffer, SIZE, " pid: %d\n", client->pid());
result.append(buffer);
}
}
}
write(fd, result.string(), result.size());
return NO_ERROR;
}
status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
int hardwareStatus = mHardwareStatus;
snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
result.append(buffer);
write(fd, result.string(), result.size());
return NO_ERROR;
}
status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "Permission Denial: "
"can't dump AudioFlinger from pid=%d, uid=%d\n",
IPCThreadState::self()->getCallingPid(),
IPCThreadState::self()->getCallingUid());
result.append(buffer);
write(fd, result.string(), result.size());
return NO_ERROR;
}
static bool tryLock(Mutex& mutex)
{
bool locked = false;
for (int i = 0; i < kDumpLockRetries; ++i) {
if (mutex.tryLock() == NO_ERROR) {
locked = true;
break;
}
usleep(kDumpLockSleep);
}
return locked;
}
status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
{
if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
dumpPermissionDenial(fd, args);
} else {
// get state of hardware lock
bool hardwareLocked = tryLock(mHardwareLock);
if (!hardwareLocked) {
String8 result(kHardwareLockedString);
write(fd, result.string(), result.size());
} else {
mHardwareLock.unlock();
}
bool locked = tryLock(mLock);
// failed to lock - AudioFlinger is probably deadlocked
if (!locked) {
String8 result(kDeadlockedString);
write(fd, result.string(), result.size());
}
dumpClients(fd, args);
dumpInternals(fd, args);
// dump playback threads
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
mPlaybackThreads.valueAt(i)->dump(fd, args);
}
// dump record threads
for (size_t i = 0; i < mRecordThreads.size(); i++) {
mRecordThreads.valueAt(i)->dump(fd, args);
}
if (mAudioHardware) {
mAudioHardware->dumpState(fd, args);
}
if (locked) mLock.unlock();
}
return NO_ERROR;
}
// IAudioFlinger interface
sp<IAudioTrack> AudioFlinger::createTrack(
pid_t pid,
int streamType,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
const sp<IMemory>& sharedBuffer,
int output,
status_t *status)
{
sp<PlaybackThread::Track> track;
sp<TrackHandle> trackHandle;
sp<Client> client;
wp<Client> wclient;
status_t lStatus;
if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
LOGE("invalid stream type");
lStatus = BAD_VALUE;
goto Exit;
}
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
LOGE("unknown output thread");
lStatus = BAD_VALUE;
goto Exit;
}
wclient = mClients.valueFor(pid);
if (wclient != NULL) {
client = wclient.promote();
} else {
client = new Client(this, pid);
mClients.add(pid, client);
}
track = thread->createTrack_l(client, streamType, sampleRate, format,
channelCount, frameCount, sharedBuffer, &lStatus);
}
if (lStatus == NO_ERROR) {
trackHandle = new TrackHandle(track);
} else {
track.clear();
}
Exit:
if(status) {
*status = lStatus;
}
return trackHandle;
}
uint32_t AudioFlinger::sampleRate(int output) const
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
LOGW("sampleRate() unknown thread %d", output);
return 0;
}
return thread->sampleRate();
}
int AudioFlinger::channelCount(int output) const
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
LOGW("channelCount() unknown thread %d", output);
return 0;
}
return thread->channelCount();
}
int AudioFlinger::format(int output) const
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
LOGW("format() unknown thread %d", output);
return 0;
}
return thread->format();
}
size_t AudioFlinger::frameCount(int output) const
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
LOGW("frameCount() unknown thread %d", output);
return 0;
}
return thread->frameCount();
}
uint32_t AudioFlinger::latency(int output) const
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
LOGW("latency() unknown thread %d", output);
return 0;
}
return thread->latency();
}
status_t AudioFlinger::setMasterVolume(float value)
{
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
// when hw supports master volume, don't scale in sw mixer
AutoMutex lock(mHardwareLock);
mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
value = 1.0f;
}
mHardwareStatus = AUDIO_HW_IDLE;
mMasterVolume = value;
for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
mPlaybackThreads.valueAt(i)->setMasterVolume(value);
return NO_ERROR;
}
status_t AudioFlinger::setMode(int mode)
{
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
LOGW("Illegal value: setMode(%d)", mode);
return BAD_VALUE;
}
AutoMutex lock(mHardwareLock);
mHardwareStatus = AUDIO_HW_SET_MODE;
status_t ret = mAudioHardware->setMode(mode);
mHardwareStatus = AUDIO_HW_IDLE;
return ret;
}
status_t AudioFlinger::setMicMute(bool state)
{
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
AutoMutex lock(mHardwareLock);
mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
status_t ret = mAudioHardware->setMicMute(state);
mHardwareStatus = AUDIO_HW_IDLE;
return ret;
}
bool AudioFlinger::getMicMute() const
{
bool state = AudioSystem::MODE_INVALID;
mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
mAudioHardware->getMicMute(&state);
mHardwareStatus = AUDIO_HW_IDLE;
return state;
}
status_t AudioFlinger::setMasterMute(bool muted)
{
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
mMasterMute = muted;
for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
mPlaybackThreads.valueAt(i)->setMasterMute(muted);
return NO_ERROR;
}
float AudioFlinger::masterVolume() const
{
return mMasterVolume;
}
bool AudioFlinger::masterMute() const
{
return mMasterMute;
}
status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
{
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
return BAD_VALUE;
}
AutoMutex lock(mLock);
PlaybackThread *thread = NULL;
if (output) {
thread = checkPlaybackThread_l(output);
if (thread == NULL) {
return BAD_VALUE;
}
}
status_t ret = NO_ERROR;
if (stream == AudioSystem::VOICE_CALL ||
stream == AudioSystem::BLUETOOTH_SCO) {
float hwValue;
if (stream == AudioSystem::VOICE_CALL) {
hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
// offset value to reflect actual hardware volume that never reaches 0
// 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
value = 0.01 + 0.99 * value;
} else { // (type == AudioSystem::BLUETOOTH_SCO)
hwValue = 1.0f;
}
AutoMutex lock(mHardwareLock);
mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
ret = mAudioHardware->setVoiceVolume(hwValue);
mHardwareStatus = AUDIO_HW_IDLE;
}
mStreamTypes[stream].volume = value;
if (thread == NULL) {
for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
} else {
thread->setStreamVolume(stream, value);
}
return ret;
}
status_t AudioFlinger::setStreamMute(int stream, bool muted)
{
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
return BAD_VALUE;
}
mStreamTypes[stream].mute = muted;
for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
return NO_ERROR;
}
float AudioFlinger::streamVolume(int stream, int output) const
{
if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
return 0.0f;
}
AutoMutex lock(mLock);
float volume;
if (output) {
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
return 0.0f;
}
volume = thread->streamVolume(stream);
} else {
volume = mStreamTypes[stream].volume;
}
// remove correction applied by setStreamVolume()
if (stream == AudioSystem::VOICE_CALL) {
volume = (volume - 0.01) / 0.99 ;
}
return volume;
}
bool AudioFlinger::streamMute(int stream) const
{
if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
return true;
}
return mStreamTypes[stream].mute;
}
bool AudioFlinger::isMusicActive() const
{
Mutex::Autolock _l(mLock);
for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
return true;
}
}
return false;
}
status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
{
status_t result;
LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
// check calling permissions
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
// ioHandle == 0 means the parameters are global to the audio hardware interface
if (ioHandle == 0) {
AutoMutex lock(mHardwareLock);
mHardwareStatus = AUDIO_SET_PARAMETER;
result = mAudioHardware->setParameters(keyValuePairs);
mHardwareStatus = AUDIO_HW_IDLE;
return result;
}
// Check if parameters are for an output
PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
if (playbackThread != NULL) {
return playbackThread->setParameters(keyValuePairs);
}
// Check if parameters are for an input
RecordThread *recordThread = checkRecordThread_l(ioHandle);
if (recordThread != NULL) {
return recordThread->setParameters(keyValuePairs);
}
return BAD_VALUE;
}
String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
{
// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
if (ioHandle == 0) {
return mAudioHardware->getParameters(keys);
}
PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
if (playbackThread != NULL) {
return playbackThread->getParameters(keys);
}
RecordThread *recordThread = checkRecordThread_l(ioHandle);
if (recordThread != NULL) {
return recordThread->getParameters(keys);
}
return String8("");
}
size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
{
return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
}
void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
{
LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
Mutex::Autolock _l(mLock);
sp<IBinder> binder = client->asBinder();
if (mNotificationClients.indexOf(binder) < 0) {
LOGV("Adding notification client %p", binder.get());
binder->linkToDeath(this);
mNotificationClients.add(binder);
}
// the config change is always sent from playback or record threads to avoid deadlock
// with AudioSystem::gLock
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
}
for (size_t i = 0; i < mRecordThreads.size(); i++) {
mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
}
}
void AudioFlinger::binderDied(const wp<IBinder>& who) {
LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
Mutex::Autolock _l(mLock);
IBinder *binder = who.unsafe_get();
if (binder != NULL) {
int index = mNotificationClients.indexOf(binder);
if (index >= 0) {
LOGV("Removing notification client %p", binder);
mNotificationClients.removeAt(index);
}
}
}
// audioConfigChanged_l() must be called with AudioFlinger::mLock held
void AudioFlinger::audioConfigChanged_l(int event, const sp<ThreadBase>& thread, void *param2) {
int ioHandle = 0;
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
if (mPlaybackThreads.valueAt(i) == thread) {
ioHandle = mPlaybackThreads.keyAt(i);
break;
}
}
if (ioHandle == 0) {
for (size_t i = 0; i < mRecordThreads.size(); i++) {
if (mRecordThreads.valueAt(i) == thread) {
ioHandle = mRecordThreads.keyAt(i);
break;
}
}
}
if (ioHandle != 0) {
size_t size = mNotificationClients.size();
for (size_t i = 0; i < size; i++) {
sp<IBinder> binder = mNotificationClients.itemAt(i);
LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
client->ioConfigChanged(event, ioHandle, param2);
}
}
}
void AudioFlinger::removeClient(pid_t pid)
{
LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mutex::Autolock _l(mLock);
mClients.removeItem(pid);
}
// ----------------------------------------------------------------------------
AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
: Thread(false),
mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
mFormat(0), mFrameSize(1), mStandby(false)
{
}
AudioFlinger::ThreadBase::~ThreadBase()
{
mParamCond.broadcast();
mNewParameters.clear();
}
void AudioFlinger::ThreadBase::exit()
{
// keep a strong ref on ourself so that we want get
// destroyed in the middle of requestExitAndWait()
sp <ThreadBase> strongMe = this;
LOGV("ThreadBase::exit");
{
AutoMutex lock(&mLock);
requestExit();
mWaitWorkCV.signal();
}
requestExitAndWait();
}
uint32_t AudioFlinger::ThreadBase::sampleRate() const
{
return mSampleRate;
}
int AudioFlinger::ThreadBase::channelCount() const
{
return mChannelCount;
}
int AudioFlinger::ThreadBase::format() const
{
return mFormat;
}
size_t AudioFlinger::ThreadBase::frameCount() const
{
return mFrameCount;
}
status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
{
status_t status;
LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mutex::Autolock _l(mLock);
mNewParameters.add(keyValuePairs);
mWaitWorkCV.signal();
mParamCond.wait(mLock);
status = mParamStatus;
mWaitWorkCV.signal();
return status;
}
void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
{
Mutex::Autolock _l(mLock);
sendConfigEvent_l(event, param);
}
// sendConfigEvent_l() must be called with ThreadBase::mLock held
void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
{
ConfigEvent *configEvent = new ConfigEvent();
configEvent->mEvent = event;
configEvent->mParam = param;
mConfigEvents.add(configEvent);
LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
mWaitWorkCV.signal();
}
void AudioFlinger::ThreadBase::processConfigEvents()
{
mLock.lock();
while(!mConfigEvents.isEmpty()) {
LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
ConfigEvent *configEvent = mConfigEvents[0];
mConfigEvents.removeAt(0);
// release mLock because audioConfigChanged() will lock AudioFlinger mLock
// before calling Audioflinger::audioConfigChanged_l() thus creating
// potential cross deadlock between AudioFlinger::mLock and mLock
mLock.unlock();
audioConfigChanged(configEvent->mEvent, configEvent->mParam);
delete configEvent;
mLock.lock();
}
mLock.unlock();
}
// ----------------------------------------------------------------------------
AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
: ThreadBase(audioFlinger),
mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
{
readOutputParameters();
mMasterVolume = mAudioFlinger->masterVolume();
mMasterMute = mAudioFlinger->masterMute();
for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
}
// notify client processes that a new input has been opened
sendConfigEvent(AudioSystem::OUTPUT_OPENED);
}
AudioFlinger::PlaybackThread::~PlaybackThread()
{
delete [] mMixBuffer;
}
status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
{
dumpInternals(fd, args);
dumpTracks(fd, args);
return NO_ERROR;
}
status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
result.append(buffer);
result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (track != 0) {
track->dump(buffer, SIZE);
result.append(buffer);
}
}
snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
result.append(buffer);
result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
for (size_t i = 0; i < mActiveTracks.size(); ++i) {
wp<Track> wTrack = mActiveTracks[i];
if (wTrack != 0) {
sp<Track> track = wTrack.promote();
if (track != 0) {
track->dump(buffer, SIZE);
result.append(buffer);
}
}
}
write(fd, result.string(), result.size());
return NO_ERROR;
}
status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "Output thread %p internals\n", this);
result.append(buffer);
snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
result.append(buffer);
snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
result.append(buffer);
snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
result.append(buffer);
snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
result.append(buffer);
snprintf(buffer, SIZE, "standby: %d\n", mStandby);
result.append(buffer);
write(fd, result.string(), result.size());
return NO_ERROR;
}
// Thread virtuals
status_t AudioFlinger::PlaybackThread::readyToRun()
{
if (mSampleRate == 0) {
LOGE("No working audio driver found.");
return NO_INIT;
}
LOGI("AudioFlinger's thread %p ready to run", this);
return NO_ERROR;
}
void AudioFlinger::PlaybackThread::onFirstRef()
{
const size_t SIZE = 256;
char buffer[SIZE];
snprintf(buffer, SIZE, "Playback Thread %p", this);
run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
}
// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
const sp<AudioFlinger::Client>& client,
int streamType,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
const sp<IMemory>& sharedBuffer,
status_t *status)
{
sp<Track> track;
status_t lStatus;
if (mType == DIRECT) {
if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
sampleRate, format, channelCount, mOutput);
lStatus = BAD_VALUE;
goto Exit;
}
} else {
// Resampler implementation limits input sampling rate to 2 x output sampling rate.
if (sampleRate > mSampleRate*2) {
LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
lStatus = BAD_VALUE;
goto Exit;
}
}
if (mOutput == 0) {
LOGE("Audio driver not initialized.");
lStatus = NO_INIT;
goto Exit;
}
{ // scope for mLock
Mutex::Autolock _l(mLock);
track = new Track(this, client, streamType, sampleRate, format,
channelCount, frameCount, sharedBuffer);
if (track->getCblk() == NULL) {
lStatus = NO_MEMORY;
goto Exit;
}
mTracks.add(track);
}
lStatus = NO_ERROR;
Exit:
if(status) {
*status = lStatus;
}
return track;
}
uint32_t AudioFlinger::PlaybackThread::latency() const
{
if (mOutput) {
return mOutput->latency();
}
else {
return 0;
}
}
status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
{
mMasterVolume = value;
return NO_ERROR;
}
status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
{
mMasterMute = muted;
return NO_ERROR;
}
float AudioFlinger::PlaybackThread::masterVolume() const
{
return mMasterVolume;
}
bool AudioFlinger::PlaybackThread::masterMute() const
{
return mMasterMute;
}
status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
{
mStreamTypes[stream].volume = value;
return NO_ERROR;
}
status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
{
mStreamTypes[stream].mute = muted;
return NO_ERROR;
}
float AudioFlinger::PlaybackThread::streamVolume(int stream) const
{
return mStreamTypes[stream].volume;
}
bool AudioFlinger::PlaybackThread::streamMute(int stream) const
{
return mStreamTypes[stream].mute;
}
bool AudioFlinger::PlaybackThread::isMusicActive() const
{
Mutex::Autolock _l(mLock);
size_t count = mActiveTracks.size();
for (size_t i = 0 ; i < count ; ++i) {
sp<Track> t = mActiveTracks[i].promote();
if (t == 0) continue;
Track* const track = t.get();
if (t->type() == AudioSystem::MUSIC)
return true;
}
return false;
}
// addTrack_l() must be called with ThreadBase::mLock held
status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
{
status_t status = ALREADY_EXISTS;
// here the track could be either new, or restarted
// in both cases "unstop" the track
if (track->isPaused()) {
track->mState = TrackBase::RESUMING;
LOGV("PAUSED => RESUMING (%d)", track->name());
} else {
track->mState = TrackBase::ACTIVE;
LOGV("? => ACTIVE (%d)", track->name());
}
// set retry count for buffer fill
track->mRetryCount = kMaxTrackStartupRetries;
if (mActiveTracks.indexOf(track) < 0) {
// the track is newly added, make sure it fills up all its
// buffers before playing. This is to ensure the client will
// effectively get the latency it requested.
track->mFillingUpStatus = Track::FS_FILLING;
track->mResetDone = false;
mActiveTracks.add(track);
status = NO_ERROR;
}
LOGV("mWaitWorkCV.broadcast");
mWaitWorkCV.broadcast();
return status;
}
// destroyTrack_l() must be called with ThreadBase::mLock held
void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
{
track->mState = TrackBase::TERMINATED;
if (mActiveTracks.indexOf(track) < 0) {
LOGV("remove track (%d) and delete from mixer", track->name());
mTracks.remove(track);
deleteTrackName_l(track->name());
}
}
String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
{
return mOutput->getParameters(keys);
}
void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
AudioSystem::OutputDescriptor desc;
void *param2 = 0;
LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
switch (event) {
case AudioSystem::OUTPUT_OPENED:
case AudioSystem::OUTPUT_CONFIG_CHANGED:
desc.channels = mChannelCount;
desc.samplingRate = mSampleRate;
desc.format = mFormat;
desc.frameCount = mFrameCount;
desc.latency = latency();
param2 = &desc;
break;
case AudioSystem::STREAM_CONFIG_CHANGED:
param2 = ¶m;
case AudioSystem::OUTPUT_CLOSED:
default:
break;
}
Mutex::Autolock _l(mAudioFlinger->mLock);
mAudioFlinger->audioConfigChanged_l(event, this, param2);
}
void AudioFlinger::PlaybackThread::readOutputParameters()
{
mSampleRate = mOutput->sampleRate();
mChannelCount = AudioSystem::popCount(mOutput->channels());
mFormat = mOutput->format();
mFrameSize = mOutput->frameSize();
mFrameCount = mOutput->bufferSize() / mFrameSize;
mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
// FIXME - Current mixer implementation only supports stereo output: Always
// Allocate a stereo buffer even if HW output is mono.
if (mMixBuffer != NULL) delete mMixBuffer;
mMixBuffer = new int16_t[mFrameCount * 2];
memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
}
// ----------------------------------------------------------------------------
AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
: PlaybackThread(audioFlinger, output),
mAudioMixer(0)
{
mType = PlaybackThread::MIXER;
mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
// FIXME - Current mixer implementation only supports stereo output
if (mChannelCount == 1) {
LOGE("Invalid audio hardware channel count");
}
}
AudioFlinger::MixerThread::~MixerThread()
{
delete mAudioMixer;
}
bool AudioFlinger::MixerThread::threadLoop()
{
unsigned long sleepTime = 0;
int16_t* curBuf = mMixBuffer;
Vector< sp<Track> > tracksToRemove;
size_t enabledTracks = 0;
nsecs_t standbyTime = systemTime();
size_t mixBufferSize = mFrameCount * mFrameSize;
nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
while (!exitPending())
{
processConfigEvents();
enabledTracks = 0;
{ // scope for mLock
Mutex::Autolock _l(mLock);
if (checkForNewParameters_l()) {
mixBufferSize = mFrameCount * mFrameSize;
maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
}
const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
// put audio hardware into standby after short delay
if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
mSuspended) {
if (!mStandby) {
LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
mOutput->standby();
mStandby = true;
mBytesWritten = 0;
}
if (!activeTracks.size() && mConfigEvents.isEmpty()) {
// we're about to wait, flush the binder command buffer
IPCThreadState::self()->flushCommands();
if (exitPending()) break;
// wait until we have something to do...
LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
mWaitWorkCV.wait(mLock);
LOGV("MixerThread %p TID %d waking up\n", this, gettid());
if (mMasterMute == false) {
char value[PROPERTY_VALUE_MAX];
property_get("ro.audio.silent", value, "0");
if (atoi(value)) {
LOGD("Silence is golden");
setMasterMute(true);
}
}
standbyTime = systemTime() + kStandbyTimeInNsecs;
sleepTime = 0;
continue;
}
}
enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
}
// output audio to hardware
if (mSuspended) {
usleep(kMaxBufferRecoveryInUsecs);
} else {
if (LIKELY(enabledTracks)) {
// mix buffers...
mAudioMixer->process(curBuf);
sleepTime = 0;
standbyTime = systemTime() + kStandbyTimeInNsecs;
} else {
sleepTime += kBufferRecoveryInUsecs;
// There was nothing to mix this round, which means all
// active tracks were late. Sleep a little bit to give
// them another chance. If we're too late, write 0s to audio
// hardware to avoid underrun.
if (mBytesWritten == 0 || sleepTime < kMaxBufferRecoveryInUsecs) {
usleep(kBufferRecoveryInUsecs);
} else {
memset (curBuf, 0, mixBufferSize);
sleepTime = 0;
}
}
// sleepTime == 0 means PCM data were written to mMixBuffer[]
if (sleepTime == 0) {
mLastWriteTime = systemTime();
mInWrite = true;
int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
if (bytesWritten > 0) mBytesWritten += bytesWritten;
mNumWrites++;
mInWrite = false;
mStandby = false;
nsecs_t delta = systemTime() - mLastWriteTime;
if (delta > maxPeriod) {
LOGW("write blocked for %llu msecs", ns2ms(delta));
mNumDelayedWrites++;
}
}
}
// finally let go of all our tracks, without the lock held
// since we can't guarantee the destructors won't acquire that
// same lock.
tracksToRemove.clear();
}
if (!mStandby) {
mOutput->standby();
}
LOGV("MixerThread %p exiting", this);
return false;
}
// prepareTracks_l() must be called with ThreadBase::mLock held
size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
{
size_t enabledTracks = 0;
// find out which tracks need to be processed
size_t count = activeTracks.size();
for (size_t i=0 ; i<count ; i++) {
sp<Track> t = activeTracks[i].promote();
if (t == 0) continue;
Track* const track = t.get();
audio_track_cblk_t* cblk = track->cblk();
// The first time a track is added we wait
// for all its buffers to be filled before processing it
mAudioMixer->setActiveTrack(track->name());
if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
!track->isPaused())
{
//LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
// compute volume for this track
int16_t left, right;
if (track->isMuted() || mMasterMute || track->isPausing() ||
mStreamTypes[track->type()].mute) {
left = right = 0;
if (track->isPausing()) {
track->setPaused();
}
} else {
float typeVolume = mStreamTypes[track->type()].volume;
float v = mMasterVolume * typeVolume;
float v_clamped = v * cblk->volume[0];
if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
left = int16_t(v_clamped);
v_clamped = v * cblk->volume[1];
if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
right = int16_t(v_clamped);
}
// XXX: these things DON'T need to be done each time
mAudioMixer->setBufferProvider(track);
mAudioMixer->enable(AudioMixer::MIXING);
int param = AudioMixer::VOLUME;
if (track->mFillingUpStatus == Track::FS_FILLED) {
// no ramp for the first volume setting
track->mFillingUpStatus = Track::FS_ACTIVE;
if (track->mState == TrackBase::RESUMING) {
track->mState = TrackBase::ACTIVE;
param = AudioMixer::RAMP_VOLUME;
}
} else if (cblk->server != 0) {
// If the track is stopped before the first frame was mixed,
// do not apply ramp
param = AudioMixer::RAMP_VOLUME;
}
mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
mAudioMixer->setParameter(
AudioMixer::TRACK,
AudioMixer::FORMAT, track->format());
mAudioMixer->setParameter(
AudioMixer::TRACK,
AudioMixer::CHANNEL_COUNT, track->channelCount());
mAudioMixer->setParameter(
AudioMixer::RESAMPLE,
AudioMixer::SAMPLE_RATE,
int(cblk->sampleRate));
// reset retry count
track->mRetryCount = kMaxTrackRetries;
enabledTracks++;
} else {
//LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
if (track->isStopped()) {
track->reset();
}
if (track->isTerminated() || track->isStopped() || track->isPaused()) {
// We have consumed all the buffers of this track.
// Remove it from the list of active tracks.
tracksToRemove->add(track);
mAudioMixer->disable(AudioMixer::MIXING);
} else {
// No buffers for this track. Give it a few chances to
// fill a buffer, then remove it from active list.
if (--(track->mRetryCount) <= 0) {
LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
tracksToRemove->add(track);
}
// For tracks using static shared memory buffer, make sure that we have
// written enough data to audio hardware before disabling the track
// NOTE: this condition with arrive before track->mRetryCount <= 0 so we
// don't care about code removing track from active list above.
if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
mAudioMixer->disable(AudioMixer::MIXING);
} else {
enabledTracks++;
}
}
}
}
// remove all the tracks that need to be...
count = tracksToRemove->size();
if (UNLIKELY(count)) {
for (size_t i=0 ; i<count ; i++) {
const sp<Track>& track = tracksToRemove->itemAt(i);
mActiveTracks.remove(track);
if (track->isTerminated()) {
mTracks.remove(track);
deleteTrackName_l(track->mName);
}
}
}
return enabledTracks;
}
void AudioFlinger::MixerThread::getTracks(
SortedVector < sp<Track> >& tracks,
SortedVector < wp<Track> >& activeTracks,
int streamType)
{
LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
Mutex::Autolock _l(mLock);
size_t size = mTracks.size();
for (size_t i = 0; i < size; i++) {
sp<Track> t = mTracks[i];
if (t->type() == streamType) {
tracks.add(t);
int j = mActiveTracks.indexOf(t);
if (j >= 0) {
t = mActiveTracks[j].promote();
if (t != NULL) {
activeTracks.add(t);
}
}
}
}
size = activeTracks.size();
for (size_t i = 0; i < size; i++) {
mActiveTracks.remove(activeTracks[i]);
}
size = tracks.size();
for (size_t i = 0; i < size; i++) {
sp<Track> t = tracks[i];
mTracks.remove(t);
deleteTrackName_l(t->name());
}
}
void AudioFlinger::MixerThread::putTracks(
SortedVector < sp<Track> >& tracks,
SortedVector < wp<Track> >& activeTracks)
{
LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
Mutex::Autolock _l(mLock);
size_t size = tracks.size();
for (size_t i = 0; i < size ; i++) {
sp<Track> t = tracks[i];
int name = getTrackName_l();
if (name < 0) return;
t->mName = name;
t->mThread = this;
mTracks.add(t);
int j = activeTracks.indexOf(t);
if (j >= 0) {
mActiveTracks.add(t);
// force buffer refilling and no ramp volume when the track is mixed for the first time
t->mFillingUpStatus = Track::FS_FILLING;
}
}
}
// getTrackName_l() must be called with ThreadBase::mLock held
int AudioFlinger::MixerThread::getTrackName_l()
{
return mAudioMixer->getTrackName();
}
// deleteTrackName_l() must be called with ThreadBase::mLock held
void AudioFlinger::MixerThread::deleteTrackName_l(int name)
{
mAudioMixer->deleteTrackName(name);
}
// checkForNewParameters_l() must be called with ThreadBase::mLock held
bool AudioFlinger::MixerThread::checkForNewParameters_l()
{
bool reconfig = false;
while (!mNewParameters.isEmpty()) {
status_t status = NO_ERROR;
String8 keyValuePair = mNewParameters[0];
AudioParameter param = AudioParameter(keyValuePair);
int value;
mNewParameters.removeAt(0);
if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
if (value != AudioSystem::PCM_16_BIT) {
status = BAD_VALUE;
} else {
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
if (value != AudioSystem::CHANNEL_OUT_STEREO) {
status = BAD_VALUE;
} else {
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
// do not accept frame count changes if tracks are open as the track buffer
// size depends on frame count and correct behavior would not be garantied
// if frame count is changed after track creation
if (!mTracks.isEmpty()) {
status = INVALID_OPERATION;
} else {
reconfig = true;
}
}
if (status == NO_ERROR) {
status = mOutput->setParameters(keyValuePair);
if (!mStandby && status == INVALID_OPERATION) {
mOutput->standby();
mStandby = true;
mBytesWritten = 0;
status = mOutput->setParameters(keyValuePair);
}
if (status == NO_ERROR && reconfig) {
delete mAudioMixer;
readOutputParameters();
mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
for (size_t i = 0; i < mTracks.size() ; i++) {
int name = getTrackName_l();
if (name < 0) break;
mTracks[i]->mName = name;
// limit track sample rate to 2 x new output sample rate
if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
}
}
sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
}
}
mParamStatus = status;
mParamCond.signal();
mWaitWorkCV.wait(mLock);
}
return reconfig;
}
status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
PlaybackThread::dumpInternals(fd, args);
snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
result.append(buffer);
write(fd, result.string(), result.size());
return NO_ERROR;
}
// ----------------------------------------------------------------------------
AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
: PlaybackThread(audioFlinger, output),
mLeftVolume (1.0), mRightVolume(1.0)
{
mType = PlaybackThread::DIRECT;
}
AudioFlinger::DirectOutputThread::~DirectOutputThread()
{
}
bool AudioFlinger::DirectOutputThread::threadLoop()
{
unsigned long sleepTime = 0;
sp<Track> trackToRemove;
sp<Track> activeTrack;
nsecs_t standbyTime = systemTime();
int8_t *curBuf;
size_t mixBufferSize = mFrameCount*mFrameSize;
while (!exitPending())
{
processConfigEvents();
{ // scope for the mLock
Mutex::Autolock _l(mLock);
if (checkForNewParameters_l()) {
mixBufferSize = mFrameCount*mFrameSize;
}
// put audio hardware into standby after short delay
if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
mSuspended) {
// wait until we have something to do...
if (!mStandby) {
LOGV("Audio hardware entering standby, mixer %p\n", this);
mOutput->standby();
mStandby = true;
mBytesWritten = 0;
}
if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
// we're about to wait, flush the binder command buffer
IPCThreadState::self()->flushCommands();
if (exitPending()) break;
LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
mWaitWorkCV.wait(mLock);
LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
if (mMasterMute == false) {
char value[PROPERTY_VALUE_MAX];
property_get("ro.audio.silent", value, "0");
if (atoi(value)) {
LOGD("Silence is golden");
setMasterMute(true);
}
}
standbyTime = systemTime() + kStandbyTimeInNsecs;
sleepTime = 0;
continue;
}
}
// find out which tracks need to be processed
if (mActiveTracks.size() != 0) {
sp<Track> t = mActiveTracks[0].promote();
if (t == 0) continue;
Track* const track = t.get();
audio_track_cblk_t* cblk = track->cblk();
// The first time a track is added we wait
// for all its buffers to be filled before processing it
if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
!track->isPaused())
{
//LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
// compute volume for this track
float left, right;
if (track->isMuted() || mMasterMute || track->isPausing() ||
mStreamTypes[track->type()].mute) {
left = right = 0;
if (track->isPausing()) {
track->setPaused();
}
} else {
float typeVolume = mStreamTypes[track->type()].volume;
float v = mMasterVolume * typeVolume;
float v_clamped = v * cblk->volume[0];
if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
left = v_clamped/MAX_GAIN;
v_clamped = v * cblk->volume[1];
if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
right = v_clamped/MAX_GAIN;
}
if (left != mLeftVolume || right != mRightVolume) {
mOutput->setVolume(left, right);
left = mLeftVolume;
right = mRightVolume;
}
if (track->mFillingUpStatus == Track::FS_FILLED) {
track->mFillingUpStatus = Track::FS_ACTIVE;
if (track->mState == TrackBase::RESUMING) {
track->mState = TrackBase::ACTIVE;
}
}
// reset retry count
track->mRetryCount = kMaxTrackRetries;
activeTrack = t;
} else {
//LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
if (track->isStopped()) {
track->reset();
}
if (track->isTerminated() || track->isStopped() || track->isPaused()) {
// We have consumed all the buffers of this track.
// Remove it from the list of active tracks.
trackToRemove = track;
} else {
// No buffers for this track. Give it a few chances to
// fill a buffer, then remove it from active list.
if (--(track->mRetryCount) <= 0) {
LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
trackToRemove = track;
}
// For tracks using static shared memry buffer, make sure that we have
// written enough data to audio hardware before disabling the track
// NOTE: this condition with arrive before track->mRetryCount <= 0 so we
// don't care about code removing track from active list above.
if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
activeTrack = t;
}
}
}
}
// remove all the tracks that need to be...
if (UNLIKELY(trackToRemove != 0)) {
mActiveTracks.remove(trackToRemove);
if (trackToRemove->isTerminated()) {
mTracks.remove(trackToRemove);
deleteTrackName_l(trackToRemove->mName);
}
}
}
// output audio to hardware
if (mSuspended) {
usleep(kMaxBufferRecoveryInUsecs);
} else {
if (activeTrack != 0) {
AudioBufferProvider::Buffer buffer;
size_t frameCount = mFrameCount;
curBuf = (int8_t *)mMixBuffer;
// output audio to hardware
while(frameCount) {
buffer.frameCount = frameCount;
activeTrack->getNextBuffer(&buffer);
if (UNLIKELY(buffer.raw == 0)) {
memset(curBuf, 0, frameCount * mFrameSize);
break;
}
memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
frameCount -= buffer.frameCount;
curBuf += buffer.frameCount * mFrameSize;
activeTrack->releaseBuffer(&buffer);
}
sleepTime = 0;
standbyTime = systemTime() + kStandbyTimeInNsecs;
} else {
sleepTime += kBufferRecoveryInUsecs;
if (mBytesWritten == 0 || !AudioSystem::isLinearPCM(mFormat) ||
sleepTime < kMaxBufferRecoveryInUsecs) {
usleep(kBufferRecoveryInUsecs);
} else {
memset (mMixBuffer, 0, mFrameCount * mFrameSize);
sleepTime = 0;
}
}
// sleepTime == 0 means PCM data were written to mMixBuffer[]
if (sleepTime == 0) {
mLastWriteTime = systemTime();
mInWrite = true;
int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
if (bytesWritten) mBytesWritten += bytesWritten;
mNumWrites++;
mInWrite = false;
mStandby = false;
}
}
// finally let go of removed track, without the lock held
// since we can't guarantee the destructors won't acquire that
// same lock.
trackToRemove.clear();
activeTrack.clear();
}
if (!mStandby) {
mOutput->standby();
}
LOGV("DirectOutputThread %p exiting", this);
return false;
}
// getTrackName_l() must be called with ThreadBase::mLock held
int AudioFlinger::DirectOutputThread::getTrackName_l()
{
return 0;
}
// deleteTrackName_l() must be called with ThreadBase::mLock held
void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
{
}
// checkForNewParameters_l() must be called with ThreadBase::mLock held
bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
{
bool reconfig = false;
while (!mNewParameters.isEmpty()) {
status_t status = NO_ERROR;
String8 keyValuePair = mNewParameters[0];
AudioParameter param = AudioParameter(keyValuePair);
int value;
mNewParameters.removeAt(0);
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
// do not accept frame count changes if tracks are open as the track buffer
// size depends on frame count and correct behavior would not be garantied
// if frame count is changed after track creation
if (!mTracks.isEmpty()) {
status = INVALID_OPERATION;
} else {
reconfig = true;
}
}
if (status == NO_ERROR) {
status = mOutput->setParameters(keyValuePair);
if (!mStandby && status == INVALID_OPERATION) {
mOutput->standby();
mStandby = true;
mBytesWritten = 0;
status = mOutput->setParameters(keyValuePair);
}
if (status == NO_ERROR && reconfig) {
readOutputParameters();
sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
}
}
mParamStatus = status;
mParamCond.signal();
mWaitWorkCV.wait(mLock);
}
return reconfig;
}
// ----------------------------------------------------------------------------
AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
: MixerThread(audioFlinger, mainThread->getOutput())
{
mType = PlaybackThread::DUPLICATING;
addOutputTrack(mainThread);
}
AudioFlinger::DuplicatingThread::~DuplicatingThread()
{
mOutputTracks.clear();
}
bool AudioFlinger::DuplicatingThread::threadLoop()
{
unsigned long sleepTime = kBufferRecoveryInUsecs;
int16_t* curBuf = mMixBuffer;
Vector< sp<Track> > tracksToRemove;
size_t enabledTracks = 0;
nsecs_t standbyTime = systemTime();
size_t mixBufferSize = mFrameCount*mFrameSize;
SortedVector< sp<OutputTrack> > outputTracks;
while (!exitPending())
{
processConfigEvents();
enabledTracks = 0;
{ // scope for the mLock
Mutex::Autolock _l(mLock);
if (checkForNewParameters_l()) {
mixBufferSize = mFrameCount*mFrameSize;
}
const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
for (size_t i = 0; i < mOutputTracks.size(); i++) {
outputTracks.add(mOutputTracks[i]);
}
// put audio hardware into standby after short delay
if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
mSuspended) {
if (!mStandby) {
for (size_t i = 0; i < outputTracks.size(); i++) {
outputTracks[i]->stop();
}
mStandby = true;
mBytesWritten = 0;
}
if (!activeTracks.size() && mConfigEvents.isEmpty()) {
// we're about to wait, flush the binder command buffer
IPCThreadState::self()->flushCommands();
outputTracks.clear();
if (exitPending()) break;
LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
mWaitWorkCV.wait(mLock);
LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
if (mMasterMute == false) {
char value[PROPERTY_VALUE_MAX];
property_get("ro.audio.silent", value, "0");
if (atoi(value)) {
LOGD("Silence is golden");
setMasterMute(true);
}
}
standbyTime = systemTime() + kStandbyTimeInNsecs;
sleepTime = kBufferRecoveryInUsecs;
continue;
}
}
enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
}
bool mustSleep = true;
if (LIKELY(enabledTracks)) {
// mix buffers...
mAudioMixer->process(curBuf);
if (!mSuspended) {
for (size_t i = 0; i < outputTracks.size(); i++) {
outputTracks[i]->write(curBuf, mFrameCount);
mustSleep = false;
}
mStandby = false;
mBytesWritten += mixBufferSize;
}
} else {
// flush remaining overflow buffers in output tracks
for (size_t i = 0; i < outputTracks.size(); i++) {
if (outputTracks[i]->isActive()) {
outputTracks[i]->write(curBuf, 0);
standbyTime = systemTime() + kStandbyTimeInNsecs;
mustSleep = false;
}
}
}
if (mustSleep) {
// LOGV("threadLoop() sleeping %d", sleepTime);
usleep(sleepTime);
if (sleepTime < kMaxBufferRecoveryInUsecs) {
sleepTime += kBufferRecoveryInUsecs;
}
} else {
sleepTime = kBufferRecoveryInUsecs;
}
// finally let go of all our tracks, without the lock held
// since we can't guarantee the destructors won't acquire that
// same lock.
tracksToRemove.clear();
outputTracks.clear();
}
{ // scope for the mLock
Mutex::Autolock _l(mLock);
if (!mStandby) {
LOGV("DuplicatingThread() exiting out of standby");
for (size_t i = 0; i < mOutputTracks.size(); i++) {
mOutputTracks[i]->destroy();
}
}
}
return false;
}
void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
{
int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
mSampleRate,
mFormat,
mChannelCount,
frameCount);
if (outputTrack->cblk() != NULL) {
thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
mOutputTracks.add(outputTrack);
LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
}
}
void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
{
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mOutputTracks.size(); i++) {
if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
mOutputTracks[i]->destroy();
mOutputTracks.removeAt(i);
return;
}
}
LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
}
// ----------------------------------------------------------------------------
// TrackBase constructor must be called with AudioFlinger::mLock held
AudioFlinger::ThreadBase::TrackBase::TrackBase(
const wp<ThreadBase>& thread,
const sp<Client>& client,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
const sp<IMemory>& sharedBuffer)
: RefBase(),
mThread(thread),
mClient(client),
mCblk(0),
mFrameCount(0),
mState(IDLE),
mClientTid(-1),
mFormat(format),
mFlags(flags & ~SYSTEM_FLAGS_MASK)
{
LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
// LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
size_t size = sizeof(audio_track_cblk_t);
size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
if (sharedBuffer == 0) {
size += bufferSize;
}
if (client != NULL) {
mCblkMemory = client->heap()->allocate(size);
if (mCblkMemory != 0) {
mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
if (mCblk) { // construct the shared structure in-place.
new(mCblk) audio_track_cblk_t();
// clear all buffers
mCblk->frameCount = frameCount;
mCblk->sampleRate = sampleRate;
mCblk->channels = (uint8_t)channelCount;
if (sharedBuffer == 0) {
mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
// Force underrun condition to avoid false underrun callback until first data is
// written to buffer
mCblk->flowControlFlag = 1;
} else {
mBuffer = sharedBuffer->pointer();
}
mBufferEnd = (uint8_t *)mBuffer + bufferSize;
}
} else {
LOGE("not enough memory for AudioTrack size=%u", size);
client->heap()->dump("AudioTrack");
return;
}
} else {
mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
if (mCblk) { // construct the shared structure in-place.
new(mCblk) audio_track_cblk_t();
// clear all buffers
mCblk->frameCount = frameCount;
mCblk->sampleRate = sampleRate;
mCblk->channels = (uint8_t)channelCount;
mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
// Force underrun condition to avoid false underrun callback until first data is
// written to buffer
mCblk->flowControlFlag = 1;
mBufferEnd = (uint8_t *)mBuffer + bufferSize;
}
}
}
AudioFlinger::ThreadBase::TrackBase::~TrackBase()
{
if (mCblk) {
mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
if (mClient == NULL) {
delete mCblk;
}
}
mCblkMemory.clear(); // and free the shared memory
mClient.clear();
}
void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
{
buffer->raw = 0;
mFrameCount = buffer->frameCount;
step();
buffer->frameCount = 0;
}
bool AudioFlinger::ThreadBase::TrackBase::step() {
bool result;
audio_track_cblk_t* cblk = this->cblk();
result = cblk->stepServer(mFrameCount);
if (!result) {
LOGV("stepServer failed acquiring cblk mutex");
mFlags |= STEPSERVER_FAILED;
}
return result;
}
void AudioFlinger::ThreadBase::TrackBase::reset() {
audio_track_cblk_t* cblk = this->cblk();
cblk->user = 0;
cblk->server = 0;
cblk->userBase = 0;
cblk->serverBase = 0;
mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
LOGV("TrackBase::reset");
}
sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
{
return mCblkMemory;
}
int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
return (int)mCblk->sampleRate;
}
int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
return (int)mCblk->channels;
}
void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
audio_track_cblk_t* cblk = this->cblk();
int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
// Check validity of returned pointer in case the track control block would have been corrupted.
if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
server %d, serverBase %d, user %d, userBase %d, channels %d",
bufferStart, bufferEnd, mBuffer, mBufferEnd,
cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
return 0;
}
return bufferStart;
}
// ----------------------------------------------------------------------------
// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
AudioFlinger::PlaybackThread::Track::Track(
const wp<ThreadBase>& thread,
const sp<Client>& client,
int streamType,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
const sp<IMemory>& sharedBuffer)
: TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
{
if (mCblk != NULL) {
sp<ThreadBase> baseThread = thread.promote();
if (baseThread != 0) {
PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
mName = playbackThread->getTrackName_l();
}
LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
if (mName < 0) {
LOGE("no more track names available");
}
mVolume[0] = 1.0f;
mVolume[1] = 1.0f;
mStreamType = streamType;
// NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
// 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
}
}
AudioFlinger::PlaybackThread::Track::~Track()
{
LOGV("PlaybackThread::Track destructor");
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
Mutex::Autolock _l(thread->mLock);
mState = TERMINATED;
}
}
void AudioFlinger::PlaybackThread::Track::destroy()
{
// NOTE: destroyTrack_l() can remove a strong reference to this Track
// by removing it from mTracks vector, so there is a risk that this Tracks's
// desctructor is called. As the destructor needs to lock mLock,
// we must acquire a strong reference on this Track before locking mLock
// here so that the destructor is called only when exiting this function.
// On the other hand, as long as Track::destroy() is only called by
// TrackHandle destructor, the TrackHandle still holds a strong ref on
// this Track with its member mTrack.
sp<Track> keep(this);
{ // scope for mLock
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
Mutex::Autolock _l(thread->mLock);
PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
playbackThread->destroyTrack_l(this);
}
}
}
void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
{
snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
mName - AudioMixer::TRACK0,
(mClient == NULL) ? getpid() : mClient->pid(),
mStreamType,
mFormat,
mCblk->channels,
mFrameCount,
mState,
mMute,
mFillingUpStatus,
mCblk->sampleRate,
mCblk->volume[0],
mCblk->volume[1],
mCblk->server,
mCblk->user);
}
status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
{
audio_track_cblk_t* cblk = this->cblk();
uint32_t framesReady;
uint32_t framesReq = buffer->frameCount;
// Check if last stepServer failed, try to step now
if (mFlags & TrackBase::STEPSERVER_FAILED) {
if (!step()) goto getNextBuffer_exit;
LOGV("stepServer recovered");
mFlags &= ~TrackBase::STEPSERVER_FAILED;
}
framesReady = cblk->framesReady();
if (LIKELY(framesReady)) {
uint32_t s = cblk->server;
uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
if (framesReq > framesReady) {
framesReq = framesReady;
}
if (s + framesReq > bufferEnd) {
framesReq = bufferEnd - s;
}
buffer->raw = getBuffer(s, framesReq);
if (buffer->raw == 0) goto getNextBuffer_exit;
buffer->frameCount = framesReq;
return NO_ERROR;
}
getNextBuffer_exit:
buffer->raw = 0;
buffer->frameCount = 0;
LOGV("getNextBuffer() no more data");
return NOT_ENOUGH_DATA;
}
bool AudioFlinger::PlaybackThread::Track::isReady() const {
if (mFillingUpStatus != FS_FILLING) return true;
if (mCblk->framesReady() >= mCblk->frameCount ||
mCblk->forceReady) {
mFillingUpStatus = FS_FILLED;
mCblk->forceReady = 0;
return true;
}
return false;
}
status_t AudioFlinger::PlaybackThread::Track::start()
{
LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
Mutex::Autolock _l(thread->mLock);
PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
playbackThread->addTrack_l(this);
}
return NO_ERROR;
}
void AudioFlinger::PlaybackThread::Track::stop()
{
LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
Mutex::Autolock _l(thread->mLock);
if (mState > STOPPED) {
mState = STOPPED;
// If the track is not active (PAUSED and buffers full), flush buffers
PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
if (playbackThread->mActiveTracks.indexOf(this) < 0) {
reset();
}
LOGV("(> STOPPED) => STOPPED (%d)", mName);
}
}
}
void AudioFlinger::PlaybackThread::Track::pause()
{
LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
Mutex::Autolock _l(thread->mLock);
if (mState == ACTIVE || mState == RESUMING) {
mState = PAUSING;
LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
}
}
}
void AudioFlinger::PlaybackThread::Track::flush()
{
LOGV("flush(%d)", mName);
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
Mutex::Autolock _l(thread->mLock);
if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
return;
}
// No point remaining in PAUSED state after a flush => go to
// STOPPED state
mState = STOPPED;
mCblk->lock.lock();
// NOTE: reset() will reset cblk->user and cblk->server with
// the risk that at the same time, the AudioMixer is trying to read
// data. In this case, getNextBuffer() would return a NULL pointer
// as audio buffer => the AudioMixer code MUST always test that pointer
// returned by getNextBuffer() is not NULL!
reset();
mCblk->lock.unlock();
}
}
void AudioFlinger::PlaybackThread::Track::reset()
{
// Do not reset twice to avoid discarding data written just after a flush and before
// the audioflinger thread detects the track is stopped.
if (!mResetDone) {
TrackBase::reset();
// Force underrun condition to avoid false underrun callback until first data is
// written to buffer
mCblk->flowControlFlag = 1;
mCblk->forceReady = 0;
mFillingUpStatus = FS_FILLING;
mResetDone = true;
}
}
void AudioFlinger::PlaybackThread::Track::mute(bool muted)
{
mMute = muted;
}
void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
{
mVolume[0] = left;
mVolume[1] = right;
}
// ----------------------------------------------------------------------------
// RecordTrack constructor must be called with AudioFlinger::mLock held
AudioFlinger::RecordThread::RecordTrack::RecordTrack(
const wp<ThreadBase>& thread,
const sp<Client>& client,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags)
: TrackBase(thread, client, sampleRate, format,
channelCount, frameCount, flags, 0),
mOverflow(false)
{
if (mCblk != NULL) {
LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
if (format == AudioSystem::PCM_16_BIT) {
mCblk->frameSize = channelCount * sizeof(int16_t);
} else if (format == AudioSystem::PCM_8_BIT) {
mCblk->frameSize = channelCount * sizeof(int8_t);
} else {
mCblk->frameSize = sizeof(int8_t);
}
}
}
AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
{
}
status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
{
audio_track_cblk_t* cblk = this->cblk();
uint32_t framesAvail;
uint32_t framesReq = buffer->frameCount;
// Check if last stepServer failed, try to step now
if (mFlags & TrackBase::STEPSERVER_FAILED) {
if (!step()) goto getNextBuffer_exit;
LOGV("stepServer recovered");
mFlags &= ~TrackBase::STEPSERVER_FAILED;
}
framesAvail = cblk->framesAvailable_l();
if (LIKELY(framesAvail)) {
uint32_t s = cblk->server;
uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
if (framesReq > framesAvail) {
framesReq = framesAvail;
}
if (s + framesReq > bufferEnd) {
framesReq = bufferEnd - s;
}
buffer->raw = getBuffer(s, framesReq);
if (buffer->raw == 0) goto getNextBuffer_exit;
buffer->frameCount = framesReq;
return NO_ERROR;
}
getNextBuffer_exit:
buffer->raw = 0;
buffer->frameCount = 0;
return NOT_ENOUGH_DATA;
}
status_t AudioFlinger::RecordThread::RecordTrack::start()
{
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
RecordThread *recordThread = (RecordThread *)thread.get();
return recordThread->start(this);
}
return NO_INIT;
}
void AudioFlinger::RecordThread::RecordTrack::stop()
{
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
RecordThread *recordThread = (RecordThread *)thread.get();
recordThread->stop(this);
TrackBase::reset();
// Force overerrun condition to avoid false overrun callback until first data is
// read from buffer
mCblk->flowControlFlag = 1;
}
}
// ----------------------------------------------------------------------------
AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
const wp<ThreadBase>& thread,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount)
: Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
mActive(false)
{
PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
if (mCblk != NULL) {
mCblk->out = 1;
mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
mCblk->volume[0] = mCblk->volume[1] = 0x1000;
mOutBuffer.frameCount = 0;
mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
playbackThread->mTracks.add(this);
LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
} else {
LOGW("Error creating output track on thread %p", playbackThread);
}
}
AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
{
clearBufferQueue();
}
status_t AudioFlinger::PlaybackThread::OutputTrack::start()
{
status_t status = Track::start();
if (status != NO_ERROR) {
return status;
}
mActive = true;
mRetryCount = 127;
return status;
}
void AudioFlinger::PlaybackThread::OutputTrack::stop()
{
Track::stop();
clearBufferQueue();
mOutBuffer.frameCount = 0;
mActive = false;
}
bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
{
Buffer *pInBuffer;
Buffer inBuffer;
uint32_t channels = mCblk->channels;
bool outputBufferFull = false;
inBuffer.frameCount = frames;
inBuffer.i16 = data;
uint32_t waitTimeLeftMs = mWaitTimeMs;
if (!mActive) {
start();
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
MixerThread *mixerThread = (MixerThread *)thread.get();
if (mCblk->frameCount > frames){
if (mBufferQueue.size() < kMaxOverFlowBuffers) {
uint32_t startFrames = (mCblk->frameCount - frames);
pInBuffer = new Buffer;
pInBuffer->mBuffer = new int16_t[startFrames * channels];
pInBuffer->frameCount = startFrames;
pInBuffer->i16 = pInBuffer->mBuffer;
memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
mBufferQueue.add(pInBuffer);
} else {
LOGW ("OutputTrack::write() %p no more buffers in queue", this);
}
}
}
}
while (waitTimeLeftMs) {
// First write pending buffers, then new data
if (mBufferQueue.size()) {
pInBuffer = mBufferQueue.itemAt(0);
} else {
pInBuffer = &inBuffer;
}
if (pInBuffer->frameCount == 0) {
break;
}
if (mOutBuffer.frameCount == 0) {
mOutBuffer.frameCount = pInBuffer->frameCount;
nsecs_t startTime = systemTime();
if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
LOGV ("OutputTrack::write() %p no more output buffers", this);
outputBufferFull = true;
break;
}
uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
if (waitTimeLeftMs >= waitTimeMs) {
waitTimeLeftMs -= waitTimeMs;
} else {
waitTimeLeftMs = 0;
}
}
uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
mCblk->stepUser(outFrames);
pInBuffer->frameCount -= outFrames;
pInBuffer->i16 += outFrames * channels;
mOutBuffer.frameCount -= outFrames;
mOutBuffer.i16 += outFrames * channels;
if (pInBuffer->frameCount == 0) {
if (mBufferQueue.size()) {
mBufferQueue.removeAt(0);
delete [] pInBuffer->mBuffer;
delete pInBuffer;
LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
} else {
break;
}
}
}
// If we could not write all frames, allocate a buffer and queue it for next time.
if (inBuffer.frameCount) {
if (mBufferQueue.size() < kMaxOverFlowBuffers) {
pInBuffer = new Buffer;
pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
pInBuffer->frameCount = inBuffer.frameCount;
pInBuffer->i16 = pInBuffer->mBuffer;
memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
mBufferQueue.add(pInBuffer);
LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
} else {
LOGW("OutputTrack::write() %p no more overflow buffers", this);
}
}
// Calling write() with a 0 length buffer, means that no more data will be written:
// If no more buffers are pending, fill output track buffer to make sure it is started
// by output mixer.
if (frames == 0 && mBufferQueue.size() == 0) {
if (mCblk->user < mCblk->frameCount) {
frames = mCblk->frameCount - mCblk->user;
pInBuffer = new Buffer;
pInBuffer->mBuffer = new int16_t[frames * channels];
pInBuffer->frameCount = frames;
pInBuffer->i16 = pInBuffer->mBuffer;
memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
mBufferQueue.add(pInBuffer);
} else {
stop();
}
}
return outputBufferFull;
}
status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
{
int active;
status_t result;
audio_track_cblk_t* cblk = mCblk;
uint32_t framesReq = buffer->frameCount;
// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
buffer->frameCount = 0;
uint32_t framesAvail = cblk->framesAvailable();
if (framesAvail == 0) {
Mutex::Autolock _l(cblk->lock);
goto start_loop_here;
while (framesAvail == 0) {
active = mActive;
if (UNLIKELY(!active)) {
LOGV("Not active and NO_MORE_BUFFERS");
return AudioTrack::NO_MORE_BUFFERS;
}
result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
if (result != NO_ERROR) {
return AudioTrack::NO_MORE_BUFFERS;
}
// read the server count again
start_loop_here:
framesAvail = cblk->framesAvailable_l();
}
}
// if (framesAvail < framesReq) {
// return AudioTrack::NO_MORE_BUFFERS;
// }
if (framesReq > framesAvail) {
framesReq = framesAvail;
}
uint32_t u = cblk->user;
uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
if (u + framesReq > bufferEnd) {
framesReq = bufferEnd - u;
}
buffer->frameCount = framesReq;
buffer->raw = (void *)cblk->buffer(u);
return NO_ERROR;
}
void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
{
size_t size = mBufferQueue.size();
Buffer *pBuffer;
for (size_t i = 0; i < size; i++) {
pBuffer = mBufferQueue.itemAt(i);
delete [] pBuffer->mBuffer;
delete pBuffer;
}
mBufferQueue.clear();
}
// ----------------------------------------------------------------------------
AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
: RefBase(),
mAudioFlinger(audioFlinger),
mMemoryDealer(new MemoryDealer(1024*1024)),
mPid(pid)
{
// 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
}
AudioFlinger::Client::~Client()
{
mAudioFlinger->removeClient(mPid);
}
const sp<MemoryDealer>& AudioFlinger::Client::heap() const
{
return mMemoryDealer;
}
// ----------------------------------------------------------------------------
AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
: BnAudioTrack(),
mTrack(track)
{
}
AudioFlinger::TrackHandle::~TrackHandle() {
// just stop the track on deletion, associated resources
// will be freed from the main thread once all pending buffers have
// been played. Unless it's not in the active track list, in which
// case we free everything now...
mTrack->destroy();
}
status_t AudioFlinger::TrackHandle::start() {
return mTrack->start();
}
void AudioFlinger::TrackHandle::stop() {
mTrack->stop();
}
void AudioFlinger::TrackHandle::flush() {
mTrack->flush();
}
void AudioFlinger::TrackHandle::mute(bool e) {
mTrack->mute(e);
}
void AudioFlinger::TrackHandle::pause() {
mTrack->pause();
}
void AudioFlinger::TrackHandle::setVolume(float left, float right) {
mTrack->setVolume(left, right);
}
sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
return mTrack->getCblk();
}
status_t AudioFlinger::TrackHandle::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
return BnAudioTrack::onTransact(code, data, reply, flags);
}
// ----------------------------------------------------------------------------
sp<IAudioRecord> AudioFlinger::openRecord(
pid_t pid,
int input,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
status_t *status)
{
sp<RecordThread::RecordTrack> recordTrack;
sp<RecordHandle> recordHandle;
sp<Client> client;
wp<Client> wclient;
status_t lStatus;
RecordThread *thread;
size_t inFrameCount;
// check calling permissions
if (!recordingAllowed()) {
lStatus = PERMISSION_DENIED;
goto Exit;
}
// add client to list
{ // scope for mLock
Mutex::Autolock _l(mLock);
thread = checkRecordThread_l(input);
if (thread == NULL) {
lStatus = BAD_VALUE;
goto Exit;
}
wclient = mClients.valueFor(pid);
if (wclient != NULL) {
client = wclient.promote();
} else {
client = new Client(this, pid);
mClients.add(pid, client);
}
// create new record track. The record track uses one track in mHardwareMixerThread by convention.
recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
format, channelCount, frameCount, flags);
}
if (recordTrack->getCblk() == NULL) {
recordTrack.clear();
lStatus = NO_MEMORY;
goto Exit;
}
// return to handle to client
recordHandle = new RecordHandle(recordTrack);
lStatus = NO_ERROR;
Exit:
if (status) {
*status = lStatus;
}
return recordHandle;
}
// ----------------------------------------------------------------------------
AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
: BnAudioRecord(),
mRecordTrack(recordTrack)
{
}
AudioFlinger::RecordHandle::~RecordHandle() {
stop();
}
status_t AudioFlinger::RecordHandle::start() {
LOGV("RecordHandle::start()");
return mRecordTrack->start();
}
void AudioFlinger::RecordHandle::stop() {
LOGV("RecordHandle::stop()");
mRecordTrack->stop();
}
sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
return mRecordTrack->getCblk();
}
status_t AudioFlinger::RecordHandle::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
return BnAudioRecord::onTransact(code, data, reply, flags);
}
// ----------------------------------------------------------------------------
AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
ThreadBase(audioFlinger),
mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
{
mReqChannelCount = AudioSystem::popCount(channels);
mReqSampleRate = sampleRate;
readInputParameters();
sendConfigEvent(AudioSystem::INPUT_OPENED);
}
AudioFlinger::RecordThread::~RecordThread()
{
delete[] mRsmpInBuffer;
if (mResampler != 0) {
delete mResampler;
delete[] mRsmpOutBuffer;
}
}
void AudioFlinger::RecordThread::onFirstRef()
{
const size_t SIZE = 256;
char buffer[SIZE];
snprintf(buffer, SIZE, "Record Thread %p", this);
run(buffer, PRIORITY_URGENT_AUDIO);
}
bool AudioFlinger::RecordThread::threadLoop()
{
AudioBufferProvider::Buffer buffer;
sp<RecordTrack> activeTrack;
// start recording
while (!exitPending()) {
processConfigEvents();
{ // scope for mLock
Mutex::Autolock _l(mLock);
checkForNewParameters_l();
if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
if (!mStandby) {
mInput->standby();
mStandby = true;
}
if (exitPending()) break;
LOGV("RecordThread: loop stopping");
// go to sleep
mWaitWorkCV.wait(mLock);
LOGV("RecordThread: loop starting");
continue;
}
if (mActiveTrack != 0) {
if (mActiveTrack->mState == TrackBase::PAUSING) {
mActiveTrack.clear();
mStartStopCond.broadcast();
} else if (mActiveTrack->mState == TrackBase::RESUMING) {
mRsmpInIndex = mFrameCount;
if (mReqChannelCount != mActiveTrack->channelCount()) {
mActiveTrack.clear();
} else {
mActiveTrack->mState = TrackBase::ACTIVE;
}
mStartStopCond.broadcast();
}
mStandby = false;
}
}
if (mActiveTrack != 0) {
buffer.frameCount = mFrameCount;
if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
size_t framesOut = buffer.frameCount;
if (mResampler == 0) {
// no resampling
while (framesOut) {
size_t framesIn = mFrameCount - mRsmpInIndex;
if (framesIn) {
int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
if (framesIn > framesOut)
framesIn = framesOut;
mRsmpInIndex += framesIn;
framesOut -= framesIn;
if (mChannelCount == mReqChannelCount ||
mFormat != AudioSystem::PCM_16_BIT) {
memcpy(dst, src, framesIn * mFrameSize);
} else {
int16_t *src16 = (int16_t *)src;
int16_t *dst16 = (int16_t *)dst;
if (mChannelCount == 1) {
while (framesIn--) {
*dst16++ = *src16;
*dst16++ = *src16++;
}
} else {
while (framesIn--) {
*dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
src16 += 2;
}
}
}
}
if (framesOut && mFrameCount == mRsmpInIndex) {
ssize_t bytesRead;
if (framesOut == mFrameCount &&
(mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
bytesRead = mInput->read(buffer.raw, mInputBytes);
framesOut = 0;
} else {
bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
mRsmpInIndex = 0;
}
if (bytesRead < 0) {
LOGE("Error reading audio input");
sleep(1);
mRsmpInIndex = mFrameCount;
framesOut = 0;
buffer.frameCount = 0;
}
}
}
} else {
// resampling
memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
// alter output frame count as if we were expecting stereo samples
if (mChannelCount == 1 && mReqChannelCount == 1) {
framesOut >>= 1;
}
mResampler->resample(mRsmpOutBuffer, framesOut, this);
// ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
// are 32 bit aligned which should be always true.
if (mChannelCount == 2 && mReqChannelCount == 1) {
AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
// the resampler always outputs stereo samples: do post stereo to mono conversion
int16_t *src = (int16_t *)mRsmpOutBuffer;
int16_t *dst = buffer.i16;
while (framesOut--) {
*dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
src += 2;
}
} else {
AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
}
}
mActiveTrack->releaseBuffer(&buffer);
mActiveTrack->overflow();
}
// client isn't retrieving buffers fast enough
else {
if (!mActiveTrack->setOverflow())
LOGW("RecordThread: buffer overflow");
// Release the processor for a while before asking for a new buffer.
// This will give the application more chance to read from the buffer and
// clear the overflow.
usleep(5000);
}
}
}
if (!mStandby) {
mInput->standby();
}
mActiveTrack.clear();
LOGV("RecordThread %p exiting", this);
return false;
}
status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
{
LOGV("RecordThread::start");
AutoMutex lock(&mLock);
if (mActiveTrack != 0) {
if (recordTrack != mActiveTrack.get()) return -EBUSY;
if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
return NO_ERROR;
}
mActiveTrack = recordTrack;
mActiveTrack->mState = TrackBase::RESUMING;
// signal thread to start
LOGV("Signal record thread");
mWaitWorkCV.signal();
mStartStopCond.wait(mLock);
if (mActiveTrack != 0) {
LOGV("Record started OK");
return NO_ERROR;
} else {
LOGV("Record failed to start");
return BAD_VALUE;
}
}
void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
LOGV("RecordThread::stop");
AutoMutex lock(&mLock);
if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
mActiveTrack->mState = TrackBase::PAUSING;
mStartStopCond.wait(mLock);
}
}
status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
pid_t pid = 0;
if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
result.append(buffer);
} else {
result.append("No record client\n");
}
write(fd, result.string(), result.size());
return NO_ERROR;
}
status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
{
size_t framesReq = buffer->frameCount;
size_t framesReady = mFrameCount - mRsmpInIndex;
int channelCount;
if (framesReady == 0) {
ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
if (bytesRead < 0) {
LOGE("RecordThread::getNextBuffer() Error reading audio input");
sleep(1);
buffer->raw = 0;
buffer->frameCount = 0;
return NOT_ENOUGH_DATA;
}
mRsmpInIndex = 0;
framesReady = mFrameCount;
}
if (framesReq > framesReady) {
framesReq = framesReady;
}
if (mChannelCount == 1 && mReqChannelCount == 2) {
channelCount = 1;
} else {
channelCount = 2;
}
buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
buffer->frameCount = framesReq;
return NO_ERROR;
}
void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
{
mRsmpInIndex += buffer->frameCount;
buffer->frameCount = 0;
}
bool AudioFlinger::RecordThread::checkForNewParameters_l()
{
bool reconfig = false;
while (!mNewParameters.isEmpty()) {
status_t status = NO_ERROR;
String8 keyValuePair = mNewParameters[0];
AudioParameter param = AudioParameter(keyValuePair);
int value;
int reqFormat = mFormat;
int reqSamplingRate = mReqSampleRate;
int reqChannelCount = mReqChannelCount;
mNewParameters.removeAt(0);
if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
reqSamplingRate = value;
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
reqFormat = value;
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
reqChannelCount = AudioSystem::popCount(value);
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
// do not accept frame count changes if tracks are open as the track buffer
// size depends on frame count and correct behavior would not be garantied
// if frame count is changed after track creation
if (mActiveTrack != 0) {
status = INVALID_OPERATION;
} else {
reconfig = true;
}
}
if (status == NO_ERROR) {
status = mInput->setParameters(keyValuePair);
if (status == INVALID_OPERATION) {
mInput->standby();
status = mInput->setParameters(keyValuePair);
}
if (reconfig) {
if (status == BAD_VALUE &&
reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
(AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
status = NO_ERROR;
}
if (status == NO_ERROR) {
readInputParameters();
sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
}
}
}
mParamStatus = status;
mParamCond.signal();
mWaitWorkCV.wait(mLock);
}
return reconfig;
}
String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
{
return mInput->getParameters(keys);
}
void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
AudioSystem::OutputDescriptor desc;
void *param2 = 0;
switch (event) {
case AudioSystem::INPUT_OPENED:
case AudioSystem::INPUT_CONFIG_CHANGED:
desc.channels = mChannelCount;
desc.samplingRate = mSampleRate;
desc.format = mFormat;
desc.frameCount = mFrameCount;
desc.latency = 0;
param2 = &desc;
break;
case AudioSystem::INPUT_CLOSED:
default:
break;
}
Mutex::Autolock _l(mAudioFlinger->mLock);
mAudioFlinger->audioConfigChanged_l(event, this, param2);
}
void AudioFlinger::RecordThread::readInputParameters()
{
if (mRsmpInBuffer) delete mRsmpInBuffer;
if (mRsmpOutBuffer) delete mRsmpOutBuffer;
if (mResampler) delete mResampler;
mResampler = 0;
mSampleRate = mInput->sampleRate();
mChannelCount = AudioSystem::popCount(mInput->channels());
mFormat = mInput->format();
mFrameSize = mInput->frameSize();
mInputBytes = mInput->bufferSize();
mFrameCount = mInputBytes / mFrameSize;
mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
{
int channelCount;
// optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
// stereo to mono post process as the resampler always outputs stereo.
if (mChannelCount == 1 && mReqChannelCount == 2) {
channelCount = 1;
} else {
channelCount = 2;
}
mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
mResampler->setSampleRate(mSampleRate);
mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
mRsmpOutBuffer = new int32_t[mFrameCount * 2];
// optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
if (mChannelCount == 1 && mReqChannelCount == 1) {
mFrameCount >>= 1;
}
}
mRsmpInIndex = mFrameCount;
}
// ----------------------------------------------------------------------------
int AudioFlinger::openOutput(uint32_t *pDevices,
uint32_t *pSamplingRate,
uint32_t *pFormat,
uint32_t *pChannels,
uint32_t *pLatencyMs,
uint32_t flags)
{
status_t status;
PlaybackThread *thread = NULL;
mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
uint32_t format = pFormat ? *pFormat : 0;
uint32_t channels = pChannels ? *pChannels : 0;
uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
pDevices ? *pDevices : 0,
samplingRate,
format,
channels,
flags);
if (pDevices == NULL || *pDevices == 0) {
return 0;
}
Mutex::Autolock _l(mLock);
AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
(int *)&format,
&channels,
&samplingRate,
&status);
LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
output,
samplingRate,
format,
channels,
status);
mHardwareStatus = AUDIO_HW_IDLE;
if (output != 0) {
if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
(format != AudioSystem::PCM_16_BIT) ||
(channels != AudioSystem::CHANNEL_OUT_STEREO)) {
thread = new DirectOutputThread(this, output);
LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
} else {
thread = new MixerThread(this, output);
LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
}
mPlaybackThreads.add(++mNextThreadId, thread);
if (pSamplingRate) *pSamplingRate = samplingRate;
if (pFormat) *pFormat = format;
if (pChannels) *pChannels = channels;
if (pLatencyMs) *pLatencyMs = thread->latency();
}
return mNextThreadId;
}
int AudioFlinger::openDuplicateOutput(int output1, int output2)
{
Mutex::Autolock _l(mLock);
MixerThread *thread1 = checkMixerThread_l(output1);
MixerThread *thread2 = checkMixerThread_l(output2);
if (thread1 == NULL || thread2 == NULL) {
LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
return 0;
}
DuplicatingThread *thread = new DuplicatingThread(this, thread1);
thread->addOutputTrack(thread2);
mPlaybackThreads.add(++mNextThreadId, thread);
return mNextThreadId;
}
status_t AudioFlinger::closeOutput(int output)
{
// keep strong reference on the playback thread so that
// it is not destroyed while exit() is executed
sp <PlaybackThread> thread;
{
Mutex::Autolock _l(mLock);
thread = checkPlaybackThread_l(output);
if (thread == NULL) {
return BAD_VALUE;
}
LOGV("closeOutput() %d", output);
if (thread->type() == PlaybackThread::MIXER) {
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
dupThread->removeOutputTrack((MixerThread *)thread.get());
}
}
}
void *param2 = 0;
audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, thread, param2);
mPlaybackThreads.removeItem(output);
}
thread->exit();
if (thread->type() != PlaybackThread::DUPLICATING) {
mAudioHardware->closeOutputStream(thread->getOutput());
}
return NO_ERROR;
}
status_t AudioFlinger::suspendOutput(int output)
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
return BAD_VALUE;
}
LOGV("suspendOutput() %d", output);
thread->suspend();
return NO_ERROR;
}
status_t AudioFlinger::restoreOutput(int output)
{
Mutex::Autolock _l(mLock);
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread == NULL) {
return BAD_VALUE;
}
LOGV("restoreOutput() %d", output);
thread->restore();
return NO_ERROR;
}
int AudioFlinger::openInput(uint32_t *pDevices,
uint32_t *pSamplingRate,
uint32_t *pFormat,
uint32_t *pChannels,
uint32_t acoustics)
{
status_t status;
RecordThread *thread = NULL;
uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
uint32_t format = pFormat ? *pFormat : 0;
uint32_t channels = pChannels ? *pChannels : 0;
uint32_t reqSamplingRate = samplingRate;
uint32_t reqFormat = format;
uint32_t reqChannels = channels;
if (pDevices == NULL || *pDevices == 0) {
return 0;
}
Mutex::Autolock _l(mLock);
AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
(int *)&format,
&channels,
&samplingRate,
&status,
(AudioSystem::audio_in_acoustics)acoustics);
LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
input,
samplingRate,
format,
channels,
acoustics,
status);
// If the input could not be opened with the requested parameters and we can handle the conversion internally,
// try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
// or stereo to mono conversions on 16 bit PCM inputs.
if (input == 0 && status == BAD_VALUE &&
reqFormat == format && format == AudioSystem::PCM_16_BIT &&
(samplingRate <= 2 * reqSamplingRate) &&
(AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
LOGV("openInput() reopening with proposed sampling rate and channels");
input = mAudioHardware->openInputStream(*pDevices,
(int *)&format,
&channels,
&samplingRate,
&status,
(AudioSystem::audio_in_acoustics)acoustics);
}
if (input != 0) {
// Start record thread
thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
mRecordThreads.add(++mNextThreadId, thread);
LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
if (pSamplingRate) *pSamplingRate = reqSamplingRate;
if (pFormat) *pFormat = format;
if (pChannels) *pChannels = reqChannels;
input->standby();
}
return mNextThreadId;
}
status_t AudioFlinger::closeInput(int input)
{
// keep strong reference on the record thread so that
// it is not destroyed while exit() is executed
sp <RecordThread> thread;
{
Mutex::Autolock _l(mLock);
thread = checkRecordThread_l(input);
if (thread == NULL) {
return BAD_VALUE;
}
LOGV("closeInput() %d", input);
void *param2 = 0;
audioConfigChanged_l(AudioSystem::INPUT_CLOSED, thread, param2);
mRecordThreads.removeItem(input);
}
thread->exit();
mAudioHardware->closeInputStream(thread->getInput());
return NO_ERROR;
}
status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
{
Mutex::Autolock _l(mLock);
MixerThread *dstThread = checkMixerThread_l(output);
if (dstThread == NULL) {
LOGW("setStreamOutput() bad output id %d", output);
return BAD_VALUE;
}
LOGV("setStreamOutput() stream %d to output %d", stream, output);
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
if (thread != dstThread &&
thread->type() != PlaybackThread::DIRECT) {
MixerThread *srcThread = (MixerThread *)thread;
SortedVector < sp<MixerThread::Track> > tracks;
SortedVector < wp<MixerThread::Track> > activeTracks;
srcThread->getTracks(tracks, activeTracks, stream);
if (tracks.size()) {
dstThread->putTracks(tracks, activeTracks);
}
}
}
dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
return NO_ERROR;
}
// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
{
PlaybackThread *thread = NULL;
if (mPlaybackThreads.indexOfKey(output) >= 0) {
thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
}
return thread;
}
// checkMixerThread_l() must be called with AudioFlinger::mLock held
AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
{
PlaybackThread *thread = checkPlaybackThread_l(output);
if (thread != NULL) {
if (thread->type() == PlaybackThread::DIRECT) {
thread = NULL;
}
}
return (MixerThread *)thread;
}
// checkRecordThread_l() must be called with AudioFlinger::mLock held
AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
{
RecordThread *thread = NULL;
if (mRecordThreads.indexOfKey(input) >= 0) {
thread = (RecordThread *)mRecordThreads.valueFor(input).get();
}
return thread;
}
// ----------------------------------------------------------------------------
status_t AudioFlinger::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
return BnAudioFlinger::onTransact(code, data, reply, flags);
}
// ----------------------------------------------------------------------------
void AudioFlinger::instantiate() {
defaultServiceManager()->addService(
String16("media.audio_flinger"), new AudioFlinger());
}
}; // namespace android
|