summaryrefslogtreecommitdiff
path: root/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.cpp
blob: f7f05d7f452658c688e153df60d1c17802b00b94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
//----------------------------------------------------------------------------------
//
// Copyright (c) 2008 Waves Audio Ltd. All rights reserved.
//
//! \file   WCMRCoreAudioDeviceManager.cpp
//!
//! WCMRCoreAudioDeviceManager and related class declarations
//!
//---------------------------------------------------------------------------------*/
#include "WCMRCoreAudioDeviceManager.h"
#include <CoreServices/CoreServices.h>
#include "MiscUtils/safe_delete.h"
#include <sstream>
#include <syslog.h>

// This flag is turned to 1, but it does not work with aggregated devices.
// due to problems with aggregated devices this flag is not functional there
#define ENABLE_DEVICE_CHANGE_LISTNER 1

#define PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS 10
#define PROPERTY_CHANGE_TIMEOUT_SECONDS 5 
#define USE_IOCYCLE_TIMES 1 ///< Set this to 0 to use individual thread cpu measurement

using namespace wvNS;
///< Supported Sample rates
static const double gAllSampleRates[] =
{
    44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, -1 /* negative terminated  list */
};


///< Default Supported Buffer Sizes.
static const int gAllBufferSizes[] =
{
    32, 64, 96, 128, 192, 256, 512, 1024, 2048, -1 /* negative terminated  list */
};
    

///< The default SR.
static const int DEFAULT_SR = 44100;
///< The default buffer size.
static const int DEFAULT_BUFFERSIZE = 1024;

static const int NONE_DEVICE_ID = -1;

///< Number of stalls to wait before notifying user...
static const int NUM_STALLS_FOR_NOTIFICATION = 2 * 50; // 2*50 corresponds to 2 * 50 x 42 ms idle timer - about 4 seconds.
static const int CHANGE_CHECK_COUNTER_PERIOD = 100; // 120 corresponds to 120 x 42 ms idle timer - about 4 seconds.

#define AUHAL_OUTPUT_ELEMENT 0  
#define AUHAL_INPUT_ELEMENT 1

#include <sys/sysctl.h>

static int getProcessorCount() 
{
    int     count = 1;
    size_t size = sizeof(count);

    if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0)) 
        return 1;

    //if something did not work, let's revert to a safe value...
    if (count == 0)
        count = 1;
        
    return count; 
}


//**********************************************************************************************
// WCMRCoreAudioDevice::WCMRCoreAudioDevice 
//
//! Constructor for the audio device. Opens the PA device and gets information about the device.
//!     such as determining supported sampling rates, buffer sizes, and channel counts.
//!
//! \param *pManager : The audio device manager that's managing this device.
//! \param deviceID : The port audio device ID.
//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true.
//! 
//! \return Nothing.
//! 
//**********************************************************************************************
WCMRCoreAudioDevice::WCMRCoreAudioDevice (WCMRCoreAudioDeviceManager *pManager, AudioDeviceID deviceID, bool useMultithreading, bool bNocopy) 
  : WCMRNativeAudioDevice (pManager, useMultithreading, bNocopy)
  , m_SampleCountAtLastIdle (0)
  , m_StalledSampleCounter(0)
  , m_SampleCounter(0)
  , m_BufferSizeChangeRequested (0)
  , m_BufferSizeChangeReported (0)
  , m_ResetRequested (0)
  , m_ResetReported (0)
  , m_ResyncRequested (0)
  , m_ResyncReported (0)
  , m_SRChangeRequested (0)
  , m_SRChangeReported (0)
  , m_ChangeCheckCounter(0)
  , m_IOProcThreadPort (0)
  , m_DropsDetected(0)
  , m_DropsReported(0)
  , m_IgnoreThisDrop(true)
  , m_LastCPULog(0)
#if WV_USE_TONE_GEN
  , m_pToneData(0)
  , m_ToneDataSamples (0)
  , m_NextSampleToUse (0)
#endif //WV_USE_TONE_GEN
{
    AUTO_FUNC_DEBUG;
    UInt32 propSize = 0;
    OSStatus err = kAudioHardwareNoError;

    //Update device info...
    m_DeviceID = deviceID;
    
    m_CurrentSamplingRate = DEFAULT_SR;
    m_CurrentBufferSize = DEFAULT_BUFFERSIZE;
    m_StopRequested = true;
    m_pInputData = NULL;
    
    m_CPUCount = getProcessorCount();
    m_LastCPULog = wvThread::now() - 10 * wvThread::ktdOneSecond;
    
    

    /*
      @constant       kAudioDevicePropertyNominalSampleRate
      A Float64 that indicates the current nominal sample rate of the AudioDevice.
    */
    Float64 currentNominalRate;
    propSize = sizeof (currentNominalRate);
    err = kAudioHardwareNoError;
    if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &currentNominalRate) != kAudioHardwareNoError)
        err = AudioDeviceGetProperty(m_DeviceID, 0, 1, kAudioDevicePropertyNominalSampleRate, &propSize, &currentNominalRate);
        
    if (err == kAudioHardwareNoError)
        m_CurrentSamplingRate = (int)currentNominalRate;
        
    /*
      @constant       kAudioDevicePropertyBufferFrameSize
      A UInt32 whose value indicates the number of frames in the IO buffers.
    */

    UInt32 bufferSize;
    propSize = sizeof (bufferSize);
    err = kAudioHardwareNoError;
    if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferSize) != kAudioHardwareNoError)
        err = AudioDeviceGetProperty(m_DeviceID, 0, 1, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferSize);
        
    if (err == kAudioHardwareNoError)
        m_CurrentBufferSize = (int)bufferSize;
    
    
    UpdateDeviceInfo();

    //should use a valid current SR...
    if (m_SamplingRates.size())
    {
        //see if the current sr is present in the sr list, if not, use the first one!
        std::vector<int>::iterator intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), m_CurrentSamplingRate);
        if (intIter == m_SamplingRates.end())
        {
            //not found... use the first one
            m_CurrentSamplingRate = m_SamplingRates[0];
        }
    }
    
    //should use a valid current buffer size
    if (m_BufferSizes.size())
    {
        //see if the current sr is present in the buffersize list, if not, use the first one!
        std::vector<int>::iterator intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), m_CurrentBufferSize);
        if (intIter == m_BufferSizes.end())
        {
            //not found... use the first one
            m_CurrentBufferSize = m_BufferSizes[0];
        }
    }
    
    //build our input/output level lists
    for (unsigned int currentChannel = 0; currentChannel < m_InputChannels.size(); currentChannel++)
    {
        m_InputLevels.push_back (0.0);
    }

    //build our input/output level lists
    for (unsigned int currentChannel = 0; currentChannel < m_OutputChannels.size(); currentChannel++)
    {
        m_OutputLevels.push_back (0.0);
    }
    
}



//**********************************************************************************************
// WCMRCoreAudioDevice::~WCMRCoreAudioDevice 
//
//! Destructor for the audio device. The base release all the connections that were created, if
//!     they have not been already destroyed! Here we simply stop streaming, and close device
//!     handles if necessary.
//!
//! \param none
//! 
//! \return Nothing.
//! 
//**********************************************************************************************
WCMRCoreAudioDevice::~WCMRCoreAudioDevice ()
{
    AUTO_FUNC_DEBUG;

    try
    {
        //If device is streaming, need to stop it!
        if (Streaming())
        {
            SetStreaming (false);
        }
        
        //If device is active (meaning stream is open) we need to close it.
        if (Active())
        {
            SetActive (false);
        }
        
    }
    catch (...)
    {
        //destructors should absorb exceptions, no harm in logging though!!
        DEBUG_MSG ("Exception during destructor");
    }

}


//**********************************************************************************************
// WCMRCoreAudioDevice::UpdateDeviceInfo 
//
//! Updates Device Information about channels, sampling rates, buffer sizes.
//! 
//! \return WTErr.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::UpdateDeviceInfo ()
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;  
    
    // Some devices change the ID during restart
    WTErr errId = UpdateDeviceId();
    
    // Update all devices parts regardless of errors
    WTErr errName = UpdateDeviceName();
    WTErr errIn =   UpdateDeviceInputs();
    WTErr errOut =  UpdateDeviceOutputs();
    WTErr errSR =   eNoErr; 
    WTErr errBS =   eNoErr; 
    
    errSR = UpdateDeviceSampleRates();
    errBS = UpdateDeviceBufferSizes();

    if(errId != eNoErr || errName != eNoErr || errIn != eNoErr || errOut != eNoErr || errSR != eNoErr || errBS != eNoErr)
    {
        retVal = eCoreAudioFailed;
    }
    
    return retVal;  
}


WTErr WCMRCoreAudioDevice::UpdateDeviceId()
{
    //Get device count...
    UInt32 propSize = 0;
    WTErr retVal = eNoErr;
    OSStatus osErr = AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &propSize, NULL);
    ASSERT_ERROR(osErr, "AudioHardwareGetProperty 1");
    if (WUIsError(osErr))
        throw osErr;
    
    size_t numDevices = propSize / sizeof (AudioDeviceID);
    AudioDeviceID* deviceIDs = new AudioDeviceID[numDevices];
    
    //retrieve the device IDs
    propSize = numDevices * sizeof (AudioDeviceID);
    osErr = AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &propSize, deviceIDs);
    ASSERT_ERROR(osErr, "Error while getting audio devices: AudioHardwareGetProperty 2");
    if (WUIsError(osErr))
        throw osErr;
    
    //now add the ones that are not there...
    for (size_t deviceIndex = 0; deviceIndex < numDevices; deviceIndex++)
    {
        DeviceInfo* pDevInfo = 0;
        
        //Get device name and create new DeviceInfo entry
        //Get property name size.
        osErr = AudioDeviceGetPropertyInfo(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL);
        if (osErr == kAudioHardwareNoError)
        {
            //Get property: name.
            char* deviceName = new char[propSize];
            osErr = AudioDeviceGetProperty(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, deviceName);
            if (osErr == kAudioHardwareNoError)
            {
                if ( (m_DeviceName == deviceName) &&
                     (m_DeviceID != deviceIDs[deviceIndex]) ) {
                    
                    m_DeviceID = deviceIDs[deviceIndex];
                    
                    m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Current device has changed it's id.");
                }
            }
            else
            {
                retVal = eCoreAudioFailed;
                DEBUG_MSG("Failed to get device name. Device ID: " << m_DeviceID);
            }
            
            delete [] deviceName;
        }
        else
        {
            retVal = eCoreAudioFailed;
            DEBUG_MSG("Failed to get device name prop Info. Device ID: " << m_DeviceID);
        }
    }
    
    delete [] deviceIDs;
	return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::UpdateDeviceName 
//
//! Updates Device name.
//!
//! Use 'kAudioDevicePropertyDeviceName'
//!
//! 1. Get property name size.
//! 2. Get property: name.
//! 
//! \return WTErr.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::UpdateDeviceName()
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;  
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    // Initiate name to unknown.
    m_DeviceName = "Unknown";
    
    //! 1. Get property name size.
    err = AudioDeviceGetPropertyInfo(m_DeviceID, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: name.
        char* deviceName = new char[propSize];
        err = AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyDeviceName, &propSize, deviceName);
        if (err == kAudioHardwareNoError)
        {
            m_DeviceName = deviceName;
        }
        else
        {
            retVal = eCoreAudioFailed;
            DEBUG_MSG("Failed to get device name. Device ID: " << m_DeviceID);
        }
        
        delete [] deviceName;
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device name property size. Device ID: " << m_DeviceID);
    }
    
    return retVal;
}

//**********************************************************************************************
// WCMRCoreAudioDevice::UpdateDeviceInputs 
//
//! Updates Device Inputs.
//!
//! Use 'kAudioDevicePropertyStreamConfiguration'
//! This property returns the stream configuration of the device in an
//! AudioBufferList (with the buffer pointers set to NULL) which describes the
//! list of streams and the number of channels in each stream. This corresponds
//! to what will be passed into the IOProc.
//!
//! 1. Get property cannels input size.
//! 2. Get property: cannels input.
//! 3. Update input channels
//! 
//! \return WTErr.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::UpdateDeviceInputs()
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;  
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    int maxInputChannels = 0;
    
    // 1. Get property cannels input size.
    err = AudioDeviceGetPropertyInfo (m_DeviceID, 0, 1/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels input.

        // Allocate size according to the property size. Note that this is a variable sized struct...
        AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize);
        
        if (pStreamBuffers)
        {
            memset (pStreamBuffers, 0, propSize);
        
            // Get the Input channels
            err = AudioDeviceGetProperty (m_DeviceID, 0, true/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers);
            if (err == kAudioHardwareNoError)
            {
                // Calculate the number of input channels
                for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++)
                {
                    maxInputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels;
                }
            }
            else
            {
                retVal = eCoreAudioFailed;
                DEBUG_MSG("Failed to get device Input channels. Device Name: " << m_DeviceName.c_str());
            }
            
            free (pStreamBuffers);
        }
        else
        {
            retVal = eMemOutOfMemory;
            DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str());
        }
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Input channels property size. Device Name: " << m_DeviceName.c_str());
    }
    
    // Update input channels
    m_InputChannels.clear();
    
    for (int channel = 0; channel < maxInputChannels; channel++)
    {
        CFStringRef cfName;
        std::stringstream chNameStream;
        UInt32 nameSize = 0;
        OSStatus error = kAudioHardwareNoError;
        
        error = AudioDeviceGetPropertyInfo (m_DeviceID,
                                            channel + 1,
                                            true /* Input */,
                                            kAudioDevicePropertyChannelNameCFString,
                                            &nameSize,
                                            NULL);
        
        if (error == kAudioHardwareNoError)
        {
            error = AudioDeviceGetProperty (m_DeviceID,
                                            channel + 1,
                                            true /* Input */,
                                            kAudioDevicePropertyChannelNameCFString,
                                            &nameSize,
                                            &cfName);
        }
  
        bool decoded = false;
        char* cstr_name = 0;
        if (error == kAudioHardwareNoError)
        {
            CFIndex length = CFStringGetLength(cfName);
            CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
            cstr_name = new char[maxSize];
            decoded = CFStringGetCString(cfName, cstr_name, maxSize, kCFStringEncodingUTF8);
        }
        
        chNameStream << (channel+1) << " - ";
        
        if (cstr_name && decoded && (0 != std::strlen(cstr_name) ) ) {
            chNameStream << cstr_name;
        }
        else
        {
            chNameStream << "Input " << (channel+1);
        }

        m_InputChannels.push_back (chNameStream.str());
        
        delete [] cstr_name;
    }
    
    return retVal;
}

//**********************************************************************************************
// WCMRCoreAudioDevice::UpdateDeviceOutputs 
//
//! Updates Device Outputs.
//!
//! Use 'kAudioDevicePropertyStreamConfiguration'
//! This property returns the stream configuration of the device in an
//! AudioBufferList (with the buffer pointers set to NULL) which describes the
//! list of streams and the number of channels in each stream. This corresponds
//! to what will be passed into the IOProc.
//!
//! 1. Get property cannels output size.
//! 2. Get property: cannels output.
//! 3. Update output channels
//! 
//! \return Nothing.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::UpdateDeviceOutputs()
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;  
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    int maxOutputChannels = 0;
    
    //! 1. Get property cannels output size.
    err = AudioDeviceGetPropertyInfo (m_DeviceID, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels output.
        
        // Allocate size according to the property size. Note that this is a variable sized struct...
        AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize);
        if (pStreamBuffers)
        {
            memset (pStreamBuffers, 0, propSize);
        
            // Get the Output channels
            err = AudioDeviceGetProperty (m_DeviceID, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers);
            if (err == kAudioHardwareNoError)
            {
                // Calculate the number of output channels
                for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++)
                {
                    maxOutputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels;
                }
            }
            else
            {
                retVal = eCoreAudioFailed;
                DEBUG_MSG("Failed to get device Output channels. Device Name: " << m_DeviceName.c_str());
            }
            free (pStreamBuffers);
        }
        else
        {
            retVal = eMemOutOfMemory;
            DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str());
        }
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Output channels property size. Device Name: " << m_DeviceName.c_str());
    }
    
    // Update output channels
    m_OutputChannels.clear();
    for (int channel = 0; channel < maxOutputChannels; channel++)
    {
        CFStringRef cfName;
        std::stringstream chNameStream;
        UInt32 nameSize = 0;
        OSStatus error = kAudioHardwareNoError;
        
        error = AudioDeviceGetPropertyInfo (m_DeviceID,
                                            channel + 1,
                                            false /* Output */,
                                            kAudioDevicePropertyChannelNameCFString,
                                            &nameSize,
                                            NULL);
        
        if (error == kAudioHardwareNoError)
        {
            error = AudioDeviceGetProperty (m_DeviceID,
                                                channel + 1,
                                                false /* Output */,
                                                kAudioDevicePropertyChannelNameCFString,
                                                &nameSize,
                                                &cfName);
        }
        
        bool decoded = false;
        char* cstr_name = 0;
        if (error == kAudioHardwareNoError )
        {
            CFIndex length = CFStringGetLength(cfName);
            CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
            cstr_name = new char[maxSize];
            decoded = CFStringGetCString(cfName, cstr_name, maxSize, kCFStringEncodingUTF8);
        }
        
        chNameStream << (channel+1) << " - ";
        
        if (cstr_name && decoded && (0 != std::strlen(cstr_name) ) ) {
            chNameStream << cstr_name;
        }
        else
        {
            chNameStream << "Output " << (channel+1);
        }
        
        m_OutputChannels.push_back (chNameStream.str());
        
        delete [] cstr_name;
    }
    
    return retVal;
}

//**********************************************************************************************
// WCMRCoreAudioDevice::UpdateDeviceSampleRates 
//
//! Updates Device Sample rates.
//!
//! Use 'kAudioDevicePropertyAvailableNominalSampleRates'
//!
//! 1. Get sample rate property size.
//! 2. Get property: sample rates.
//! 3. Update sample rates
//! 
//! \return Nothing.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::UpdateDeviceSampleRates()
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;  
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    m_SamplingRates.clear();
    
    //! 1. Get sample rate property size.
    err = AudioDeviceGetPropertyInfo(m_DeviceID, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels output.
        
        // Allocate size accrding to the number of audio values
        int numRates = propSize / sizeof(AudioValueRange);
        AudioValueRange* supportedRates = new AudioValueRange[numRates];
        
        // Get sampling rates from Audio device
        err = AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, supportedRates);
        if (err == kAudioHardwareNoError)
        {
            //! 3. Update sample rates
            
            // now iterate through our standard SRs
            for(int ourSR=0; gAllSampleRates[ourSR] > 0; ourSR++)
            {
                //check to see if our SR is in the supported rates...
                for (int deviceSR = 0; deviceSR < numRates; deviceSR++)
                {
                    if ((supportedRates[deviceSR].mMinimum <= gAllSampleRates[ourSR]) && 
                        (supportedRates[deviceSR].mMaximum >= gAllSampleRates[ourSR]))
                    {
                        m_SamplingRates.push_back ((int)gAllSampleRates[ourSR]);
                        break;
                    }
                }
            }
        }
        else
        {
            retVal = eCoreAudioFailed;
            DEBUG_MSG("Failed to get device Sample rates. Device Name: " << m_DeviceName.c_str());
        }
        
        delete [] supportedRates;
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Sample rates property size. Device Name: " << m_DeviceName.c_str());
    }
    
    return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::UpdateDeviceBufferSizes_Simple 
//
// Use kAudioDevicePropertyBufferFrameSizeRange
//
// in case of 'eMatchedDuplexDevices' and a matching device exists return common device name
// in all other cases retur base class function implementation
//
// 1. Get buffer size range
// 2. Run on all ranges and add them to the list
// 
// \return error code
// 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::UpdateDeviceBufferSizes ()
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    // Clear buffer sizes
    m_BufferSizes.clear();
    
    // 1. Get buffer size range
    AudioValueRange bufferSizesRange;
    propSize = sizeof (AudioValueRange);
    err = AudioDeviceGetProperty (m_DeviceID, 0, 0, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &bufferSizesRange);
    if(err == kAudioHardwareNoError)
    {
        // 2. Run on all ranges and add them to the list
        for(int bsize=0; gAllBufferSizes[bsize] > 0; bsize++)
        {
            if ((bufferSizesRange.mMinimum <= gAllBufferSizes[bsize]) && (bufferSizesRange.mMaximum >= gAllBufferSizes[bsize]))
            {
                m_BufferSizes.push_back (gAllBufferSizes[bsize]);
            }
        }
        
        //if we didn't get a single hit, let's simply add the min. and the max...
        if (m_BufferSizes.empty())
        {
            m_BufferSizes.push_back ((int)bufferSizesRange.mMinimum);
            m_BufferSizes.push_back ((int)bufferSizesRange.mMaximum);
        }
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device buffer sizes range. Device Name: " << m_DeviceName.c_str());
    }
    
    return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::DeviceName 
//
//! in case of 'eMatchedDuplexDevices' and a matching device exists return common device name
//! in all other cases retur base class function implementation
//!
//! \param none
//! 
//! \return current device name
//! 
//**********************************************************************************************
const std::string& WCMRCoreAudioDevice::DeviceName() const
{
    return WCMRAudioDevice::DeviceName();
}

//**********************************************************************************************
// WCMRCoreAudioDevice::InputChannels 
//
//! return base class function implementation
//!
//! \param none
//! 
//! \return base class function implementation
//! 
//**********************************************************************************************
const std::vector<std::string>& WCMRCoreAudioDevice::InputChannels()
{
    return WCMRAudioDevice::InputChannels();
}

//**********************************************************************************************
// WCMRCoreAudioDevice::OutputChannels 
//
//! in case of 'eMatchedDuplexDevices' return matching device output channel if there is one
//! in all other cases retur base class function implementation
//!
//! \param none
//! 
//! \return list of output channels of current device
//! 
//**********************************************************************************************
const std::vector<std::string>& WCMRCoreAudioDevice::OutputChannels()
{
    return WCMRAudioDevice::OutputChannels();
}


//**********************************************************************************************
// WCMRCoreAudioDevice::SamplingRates 
//
//! in case of 'eMatchedDuplexDevices' and a matching device exists return common sample rate
//! in all other cases retur base class function implementation
//!
//! \param none
//! 
//! \return current sample rate
//! 
//**********************************************************************************************
const std::vector<int>& WCMRCoreAudioDevice::SamplingRates()
{
    return WCMRAudioDevice::SamplingRates();
}

//**********************************************************************************************
// WCMRCoreAudioDevice::CurrentSamplingRate 
//
//! The device's current sampling rate. This may be overridden, if the device needs to 
//!     query the driver for the current rate.
//!
//! \param none
//! 
//! \return The device's current sampling rate. -1 on error.
//! 
//**********************************************************************************************
int WCMRCoreAudioDevice::CurrentSamplingRate ()
{
    AUTO_FUNC_DEBUG;
    //ToDo: Perhaps for ASIO devices that are active, we should retrive the SR from the device...
    UInt32 propSize = 0;
    OSStatus err = kAudioHardwareNoError;

    Float64 currentNominalRate;
    propSize = sizeof (currentNominalRate);
    err = kAudioHardwareNoError;
    if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &currentNominalRate) != kAudioHardwareNoError)
        err = AudioDeviceGetProperty(m_DeviceID, 0, 1, kAudioDevicePropertyNominalSampleRate, &propSize, &currentNominalRate);
        
    if (err == kAudioHardwareNoError)
        m_CurrentSamplingRate = (int)currentNominalRate;
    else
    {
        DEBUG_MSG("Unable to get sampling rate!");
    }

    return (m_CurrentSamplingRate);
}




//**********************************************************************************************
// WCMRCoreAudioDevice::SetCurrentSamplingRate 
//
//! Change the sampling rate to be used by the device. 
//!
//! \param newRate : The rate to use (samples per sec).
//! 
//! \return eNoErr always. The derived classes may return error codes.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetCurrentSamplingRate (int newRate)
{
    AUTO_FUNC_DEBUG;
    std::vector<int>::iterator intIter;
    WTErr retVal = eNoErr;

    //changes the status.
    int oldRate = CurrentSamplingRate();
    bool oldActive = Active();
    
    //no change, nothing to do
    if (oldRate == newRate)
        goto Exit;

    //see if this is one of our supported rates...
    intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), newRate);
    if (intIter == m_SamplingRates.end())
    {
        //Can't change, perhaps use an "invalid param" type of error
        retVal = eCommandLineParameter;
        goto Exit;
    }
    
    if (Streaming())
    {
        //Can't change, perhaps use an "in use" type of error
        retVal = eGenericErr;
        goto Exit;
    }

    if (oldActive)
    {
        //Deactivate it for the change...
        SetActive (false);
    }
    
    retVal = SetAndCheckCurrentSamplingRate (newRate);
    if(retVal == eNoErr)
    {
        retVal = UpdateDeviceInfo ();
    }

    //reactivate it.    
    if (oldActive)
    {
        retVal = SetActive (true);
    }
    
Exit:

    return (retVal);
        
}

//**********************************************************************************************
// WCMRCoreAudioDevice::SetAndCheckCurrentSamplingRate 
//
//! Change the sampling rate to be used by the device. 
//!
//! \param newRate : The rate to use (samples per sec).
//! 
//! \return eNoErr always. The derived classes may return error codes.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetAndCheckCurrentSamplingRate (int newRate)
{
    AUTO_FUNC_DEBUG;
    std::vector<int>::iterator intIter;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    // 1. Set new sampling rate
    Float64 newNominalRate = newRate;
    propSize = sizeof (Float64);
    err = AudioDeviceSetProperty(m_DeviceID, NULL, 0, 0, kAudioDevicePropertyNominalSampleRate, propSize, &newNominalRate);
    
    if (err != kAudioHardwareNoError)
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG ("Unable to set SR! Device name: " << m_DeviceName.c_str());
    }
    else
    {
        // 2. wait for the SR to actually change...
        
        // Set total time out time
        int tryAgain = ((PROPERTY_CHANGE_TIMEOUT_SECONDS * 1000) / PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS) ;
        int actualWait = 0;
        Float64 actualSamplingRate = 0.0;
        
        // Run as ling as time out is not finished
        while (tryAgain)
        {
            // Get current sampling rate
            err = AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &actualSamplingRate);
            if (err == kAudioHardwareNoError)
            {
                if (actualSamplingRate == newNominalRate)
                {
                    //success, let's get out!
                    break;
                }
            }
            else
            {
                //error reading rate, but let's not complain too much!
                m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Could not read Sampling Rate for verification.");
                DEBUG_MSG ("Unable to get SR. Device name: " << m_DeviceName.c_str());
            }
            
            // oh well...there's always another millisecond...
            wvThread::sleep_milliseconds (PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS);
            tryAgain--;
            actualWait++;
        }
        
        // If sample rate actually changed
        if (tryAgain != 0)
        {
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Changed the Sampling Rate.");
            
            // Update member with new rate
            m_CurrentSamplingRate = newRate;
            
            char debugMsg[128];
            snprintf (debugMsg, sizeof(debugMsg), "Actual Wait for SR Change was %d milliseconds", actualWait * PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS);
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)debugMsg);
        }
        // If sample rate did not change after time out
        else
        {
            // Check if current device sample rate is supported
            bool found = false;
            for(int i = 0; gAllSampleRates[i] > 0; i++)
            {
                if (fabs(gAllSampleRates[i] - actualSamplingRate) < 0.01) {
                    found = true;
                }
            }
            
            if (found) {
                // Update member with last read value
                m_CurrentSamplingRate = static_cast<int>(actualSamplingRate);
                
                char debugMsg[128];
                snprintf (debugMsg, sizeof(debugMsg), "Unable to change SR, even after waiting for %d milliseconds", actualWait * PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS);
                m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)debugMsg);
                
                float sample_rate_update = actualSamplingRate;
                m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged, (void *)&sample_rate_update);
            } else {
                retVal = eGenericErr;
            }
        }
    }
    
    return (retVal);
}


//**********************************************************************************************
// WCMRCoreAudioDevice::BufferSizes 
//
//! in case of 'eMatchedDuplexDevices' and a matching device exists return common buffer sizes
//! in all other cases retur base class function implementation
//!
//! \param none
//! 
//! \return current sample rate
//! 
//**********************************************************************************************
const std::vector<int>& WCMRCoreAudioDevice::BufferSizes()
{
    return WCMRAudioDevice::BufferSizes();
}


//**********************************************************************************************
// WCMRCoreAudioDevice::CurrentBufferSize
//
//! The device's current buffer size in use. This may be overridden, if the device needs to 
//!     query the driver for the current size.
//!
//! \param none
//! 
//! \return The device's current buffer size. 0 on error.
//! 
//**********************************************************************************************
int WCMRCoreAudioDevice::CurrentBufferSize ()
{
    AUTO_FUNC_DEBUG;

    return (m_CurrentBufferSize);
}



//**********************************************************************************************
// WCMRCoreAudioDevice::SetCurrentBufferSize
//
//! Change the buffer size to be used by the device. This will most likely be overridden, 
//!     the base class simply updates the member variable.
//!
//! \param newSize : The buffer size to use (in sample-frames)
//! 
//! \return eNoErr always. The derived classes may return error codes.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetCurrentBufferSize (int newSize)
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    std::vector<int>::iterator intIter;

    //changes the status.
    int oldSize = CurrentBufferSize();
    bool oldActive = Active();

    //same size, nothing to do.
    if (oldSize == newSize)
        goto Exit;
    
    if (Streaming())
    {
        //Can't change, perhaps use an "in use" type of error
        retVal = eGenericErr;
        goto Exit;
    }
    
    if (oldActive)
    {
        //Deactivate it for the change...
        SetActive (false);
    }
    
    // when audio device is inactive it is safe to set a working buffer size according to new buffer size
    // if 'newSize' is not a valid buffer size, another valid buffer size will be set
    retVal = SetWorkingBufferSize(newSize);
    if(retVal != eNoErr)
    {
        DEBUG_MSG("Unable to set a working buffer size. Device Name: " << DeviceName().c_str());
        goto Exit;
    }

    //reactivate it.    
    if (oldActive)
    {
        retVal = SetActive (true);
        if(retVal != eNoErr)
        {
            DEBUG_MSG("Unable to activate device. Device Name: " << DeviceName().c_str());
            goto Exit;
        }
    }
    
Exit:
    
    return (retVal);
}

WTErr WCMRCoreAudioDevice::SetWorkingBufferSize(int newSize)
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    
    // 1. Set new buffer size
    err = SetBufferSizesByIO(newSize);
    
    // If there's no error it means this buffer size is supported
    if(err == kAudioHardwareNoError)
    {
        m_CurrentBufferSize = newSize;
    }
    // If there was an error it means that this buffer size was not supported
    else
    {
        // In case the new buffer size could not be set, set another working buffer size

        // Run on all buffer sizes:
        
        // Try setting buffer sizes that are bigger then selected buffer size first,
        // Since bigger buffer sizes usually work safer 
        for(std::vector<int>::const_iterator iter = m_BufferSizes.begin();iter != m_BufferSizes.end();++iter)
        {
            int nCurBS = *iter;
            
            if(nCurBS > newSize)
            {
                // Try setting current buffer size
                err = SetBufferSizesByIO(nCurBS);
                
                // in case buffer size is valid
                if(err == kAudioHardwareNoError)
                {
                    // Set current buffer size
                    m_CurrentBufferSize = nCurBS;
                    break;
                }
            }
        }
        
        // If bigger buffer sizes failed, go to smaller buffer sizes
        if(err != kAudioHardwareNoError)
        {
            for(std::vector<int>::const_iterator iter = m_BufferSizes.begin();iter != m_BufferSizes.end();++iter)
            {
                int nCurBS = *iter;
                
                if(nCurBS < newSize)
                {
                    // Try setting current buffer size
                    err = SetBufferSizesByIO(*iter);
                    
                    // in case buffer size is valid
                    if(err == kAudioHardwareNoError)
                    {
                        // Set current buffer size
                        m_CurrentBufferSize = *iter;
                        break;
                    }
                }
            }
        }
        
        // Check if a valid buffer size was found
        if(err == kAudioHardwareNoError)
        {
            // Notify that a different sample rate is set
            char debugMsg[256];
            snprintf (debugMsg, sizeof(debugMsg), "Could not set buffer size: %d, Set buffer size to: %d.", newSize, m_CurrentBufferSize);
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)debugMsg);
        }
        // if there was no buffer size that could be set
        else
        {
            // Set the parameter buffer size by default, set a debug message
            m_CurrentBufferSize = newSize;
            DEBUG_MSG("Unable to set any buffer size. Device Name: " << m_DeviceName.c_str());
        }
    }
    
    return retVal;
}

OSStatus WCMRCoreAudioDevice::SetBufferSizesByIO(int newSize)
{
    OSStatus err = kAudioHardwareNoError;
    
    // 1. Set new buffer size
    UInt32 bufferSize = (UInt32)newSize;
    UInt32 propSize = sizeof (UInt32);
    
    // Set new buffer size to input
    if (!m_InputChannels.empty())
    {
        err = AudioDeviceSetProperty(m_DeviceID, NULL, 0, 1, kAudioDevicePropertyBufferFrameSize, propSize, &bufferSize);
    }
    else
    {
        err = AudioDeviceSetProperty(m_DeviceID, NULL, 0, 0, kAudioDevicePropertyBufferFrameSize, propSize, &bufferSize);
    }
    
    return err;
}

//**********************************************************************************************
// WCMRCoreAudioDevice::ConnectionStatus 
//
//! Retrieves the device's current connection status. This will most likely be overridden,
//!     in case some driver communication is required to query the status.
//!
//! \param none
//! 
//! \return A ConnectionStates value.
//! 
//**********************************************************************************************
WCMRCoreAudioDevice::ConnectionStates WCMRCoreAudioDevice::ConnectionStatus ()
{
    AUTO_FUNC_DEBUG;
    //ToDo: May want to do something more to extract the actual status!
    return (m_ConnectionStatus);
    
}


//**********************************************************************************************
// WCMRCoreAudioDevice::EnableAudioUnitIO
//
//! Sets up the AUHAL for IO, allowing changes to the devices to be used by the AudioUnit.
//!
//! \param none
//! 
//! \return eNoErr on success, an error code on failure.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::EnableAudioUnitIO()
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    
    UInt32 enableIO = 1;
    if (!m_InputChannels.empty())
    {
        ///////////////
        //ENABLE IO (INPUT)
        //You must enable the Audio Unit (AUHAL) for input 
        
        //Enable input on the AUHAL
        err =  AudioUnitSetProperty(m_AUHALAudioUnit, 
                                    kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input,
                                    AUHAL_INPUT_ELEMENT,
                                    &enableIO, sizeof(enableIO));

        if (err)
        {
            DEBUG_MSG("Couldn't Enable IO on input scope of input element, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
    }
    
    //disable Output on the AUHAL if there's no output
    if (m_OutputChannels.empty())
        enableIO = 0;
    else
        enableIO = 1;
        
    err = AudioUnitSetProperty(m_AUHALAudioUnit,
                               kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output,
                               AUHAL_OUTPUT_ELEMENT,
                               &enableIO, sizeof(enableIO));
        
    if (err)
    {
        DEBUG_MSG("Couldn't Enable/Disable IO on output scope of output element, error = " << err);
        retVal = eGenericErr;
        goto Exit;
    }

Exit:
    return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::EnableListeners
//
//! Sets up listeners to listen for Audio Device property changes, so that app can be notified.
//!
//! \param none
//! 
//! \return eNoErr on success, an error code on failure.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::EnableListeners()
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;

    //listner for SR change...
    err = AudioDeviceAddPropertyListener(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate,
                                         StaticPropertyChangeProc, this);
    
    if (err)
    {
        DEBUG_MSG("Couldn't Setup SR Property Listner, error = " << err);
        retVal = eGenericErr;
        goto Exit;
    }

#if ENABLE_DEVICE_CHANGE_LISTNER
    {
        //listner for device change...
        
        err = AudioDeviceAddPropertyListener (m_DeviceID,
                                              kAudioPropertyWildcardChannel,
                                              true,
                                              kAudioDevicePropertyDeviceHasChanged,
                                              StaticPropertyChangeProc,
                                              this);
                
        if (err)
        {
            DEBUG_MSG("Couldn't Setup device change Property Listner, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
    }
#endif //ENABLE_DEVICE_CHANGE_LISTNER   
    
    //listner for dropouts...
    err = AudioDeviceAddPropertyListener(m_DeviceID, 0, 0, kAudioDeviceProcessorOverload,
                                         StaticPropertyChangeProc, this);
        
    if (err)
    {
        DEBUG_MSG("Couldn't Setup Processor Overload Property Listner, error = " << err);
        retVal = eGenericErr;
        goto Exit;
    }
    

Exit:   
    return retVal;
}



//**********************************************************************************************
// WCMRCoreAudioDevice::DisableListeners
//
//! Undoes the work done by EnableListeners
//!
//! \param none
//! 
//! \return eNoErr on success, an error code on failure.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::DisableListeners()
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;

    //listner for SR change...
    err = AudioDeviceRemovePropertyListener(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate,
                                            StaticPropertyChangeProc);
        
    if (err)
    {
        DEBUG_MSG("Couldn't Cleanup SR Property Listner, error = " << err);
        //not sure if we need to report this...
    }

#if ENABLE_DEVICE_CHANGE_LISTNER    
    {
        err = AudioDeviceRemovePropertyListener (m_DeviceID,
                                                 kAudioPropertyWildcardChannel,
                                                 true/* Input */,
                                                 kAudioDevicePropertyDeviceHasChanged,
                                                 StaticPropertyChangeProc);
        
        if (err)
        {
            DEBUG_MSG("Couldn't Cleanup device input stream change Property Listner, error = " << err);
            //not sure if we need to report this...
        }
        
    }
#endif //ENABLE_DEVICE_CHANGE_LISTNER   

    err = AudioDeviceRemovePropertyListener(m_DeviceID, 0, 0, kAudioDeviceProcessorOverload,
                                            StaticPropertyChangeProc);
        
    if (err)
    {
        DEBUG_MSG("Couldn't Cleanup device change Property Listner, error = " << err);
        //not sure if we need to report this...
    }
    

    return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::StaticPropertyChangeProc
//
//! The property change function called (as a result of EnableListeners) when device properties change.
//!     It calls upon the non-static PropertyChangeProc to do the work.
//!
//! \param inDevice : The audio device in question.
//! \param inChannel : The channel on which the property has change.
//! \param isInput : If the change is for Input.
//! \param inPropertyID : The property that has changed.
//! \param inClientData: What was passed when listener was enabled, in our case teh WCMRCoreAudioDevice object.
//! 
//! \return 0 always.
//! 
//**********************************************************************************************
OSStatus WCMRCoreAudioDevice::StaticPropertyChangeProc (AudioDeviceID /*inDevice*/, UInt32 /*inChannel*/, Boolean /*isInput*/,
                                                        AudioDevicePropertyID inPropertyID, void *inClientData)
{
    if (inClientData)
    {
        WCMRCoreAudioDevice* pCoreDevice = (WCMRCoreAudioDevice *)inClientData;
        pCoreDevice->PropertyChangeProc (inPropertyID);
    }
        
    return 0;
}



//**********************************************************************************************
// WCMRCoreAudioDevice::PropertyChangeProc
//
//! The non-static property change proc. Gets called when properties change. Since this gets called
//!     on an arbitrary thread, we simply update the request counters and return.
//!
//! \param none
//! 
//! \return nothing.
//! 
//**********************************************************************************************
void WCMRCoreAudioDevice::PropertyChangeProc (AudioDevicePropertyID inPropertyID)
{
    switch (inPropertyID)
    {
    case kAudioDevicePropertyNominalSampleRate:
        m_SRChangeRequested++;
        break;
#if ENABLE_DEVICE_CHANGE_LISTNER    
    case kAudioDevicePropertyDeviceHasChanged:
        {
            m_ResetRequested++;
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
        }
        break;
#endif //ENABLE_DEVICE_CHANGE_LISTNER   
    case kAudioDeviceProcessorOverload:
        {
        if (m_IgnoreThisDrop)
            m_IgnoreThisDrop = false; //We'll ignore once, just once!
        else
            m_DropsDetected++;
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::Dropout );
        break;
        }
    default:
        break;
    }
}


//**********************************************************************************************
// WCMRCoreAudioDevice::SetupAUHAL
//
//! Sets up the AUHAL AudioUnit for device IO.
//!
//! \param none
//! 
//! \return eNoErr on success, an error code on failure.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetupAUHAL()
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    Component comp;
    ComponentDescription desc;
    AudioStreamBasicDescription streamFormatToUse, auhalStreamFormat;

    //There are several different types of Audio Units.
    //Some audio units serve as Outputs, Mixers, or DSP
    //units. See AUComponent.h for listing
    desc.componentType = kAudioUnitType_Output;
    
    //Every Component has a subType, which will give a clearer picture
    //of what this components function will be.
    desc.componentSubType = kAudioUnitSubType_HALOutput;
    
    //all Audio Units in AUComponent.h must use 
    //"kAudioUnitManufacturer_Apple" as the Manufacturer
    desc.componentManufacturer = kAudioUnitManufacturer_Apple;
    desc.componentFlags = 0;
    desc.componentFlagsMask = 0;
    
    //Finds a component that meets the desc spec's
    comp = FindNextComponent(NULL, &desc);
    if (comp == NULL)
    {
        DEBUG_MSG("Couldn't find AUHAL Component");
        retVal = eGenericErr;
        goto Exit;
    }
    
    //gains access to the services provided by the component
    OpenAComponent(comp, &m_AUHALAudioUnit);  

    
    retVal = EnableAudioUnitIO();
    if (retVal != eNoErr)
        goto Exit;

    //Now setup the device to use by the audio unit...
    
    //input
    if (!m_InputChannels.empty())
    {
        err = AudioUnitSetProperty(m_AUHALAudioUnit, kAudioOutputUnitProperty_CurrentDevice,
                                   kAudioUnitScope_Global, AUHAL_INPUT_ELEMENT,
                                   &m_DeviceID, sizeof(m_DeviceID));

        if (err)
        {
            DEBUG_MSG("Couldn't Set the audio device property for Input Element Global scope, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
    }

    //output
    if (!m_OutputChannels.empty())
    {
        err = AudioUnitSetProperty(m_AUHALAudioUnit, kAudioOutputUnitProperty_CurrentDevice,
                                   kAudioUnitScope_Global, AUHAL_OUTPUT_ELEMENT,
                                   &m_DeviceID, sizeof(m_DeviceID));

        if (err)
        {
            DEBUG_MSG("Couldn't Set the audio device property for Output Element Global scope, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
    }
    
    //also set Sample Rate...
    {
        retVal = SetAndCheckCurrentSamplingRate(m_CurrentSamplingRate);
        if(retVal != eNoErr)
        {
            DEBUG_MSG ("Unable to set SR, error = " << err);
            goto Exit;
        }
    }

    //now set the buffer size...
    {
        err = SetWorkingBufferSize(m_CurrentBufferSize);
        if (err)
        {
            DEBUG_MSG("Couldn't Set the buffer size property, error = " << err);
            //we don't really quit here..., just keep going even if this does not work,
            //the AUHAL is supposed to take care of this by way of slicing...
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Could not set buffer size.");
            
        }
    }
    
    //convertor quality
    {
        UInt32 quality = kAudioConverterQuality_Max;
        propSize = sizeof (quality);
        err = AudioUnitSetProperty(m_AUHALAudioUnit,
                                   kAudioUnitProperty_RenderQuality, kAudioUnitScope_Global,
                                   AUHAL_OUTPUT_ELEMENT,
                                   &quality, sizeof (quality));
            
        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to set Convertor Quality, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
    }
    
    memset (&auhalStreamFormat, 0, sizeof (auhalStreamFormat));
    propSize = sizeof (auhalStreamFormat);
    err = AudioUnitGetProperty(m_AUHALAudioUnit,
                               kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
                               AUHAL_INPUT_ELEMENT,
                               &auhalStreamFormat, &propSize);
    if (err != kAudioHardwareNoError)
    {
        DEBUG_MSG ("Unable to get Input format, error = " << err);
        retVal = eGenericErr;
        goto Exit;
    }
    
    if (auhalStreamFormat.mSampleRate != (Float64)m_CurrentSamplingRate)
    {
        TRACE_MSG ("AUHAL's Input SR differs from expected SR, expected = " << m_CurrentSamplingRate << ", AUHAL's = " << (UInt32)auhalStreamFormat.mSampleRate);
    }
    
    //format, and slice size...
    memset (&streamFormatToUse, 0, sizeof (streamFormatToUse));
    streamFormatToUse.mFormatID = kAudioFormatLinearPCM;
    streamFormatToUse.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
    streamFormatToUse.mFramesPerPacket = 1;
    streamFormatToUse.mBitsPerChannel = sizeof (float) * 8;
    streamFormatToUse.mSampleRate = auhalStreamFormat.mSampleRate;

    if (!m_InputChannels.empty())
    {
        streamFormatToUse.mChannelsPerFrame = m_InputChannels.size();
        streamFormatToUse.mBytesPerFrame = sizeof (float)*streamFormatToUse.mChannelsPerFrame;
        streamFormatToUse.mBytesPerPacket = streamFormatToUse.mBytesPerFrame;
        propSize = sizeof (streamFormatToUse);
        err = AudioUnitSetProperty(m_AUHALAudioUnit,
                                   kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
                                   AUHAL_INPUT_ELEMENT,
                                   &streamFormatToUse, sizeof (streamFormatToUse));

        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to set Input format, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
        
        UInt32 bufferSize = m_CurrentBufferSize;
        err = AudioUnitSetProperty(m_AUHALAudioUnit,
                                   kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Output,
                                   AUHAL_INPUT_ELEMENT,
                                   &bufferSize, sizeof (bufferSize));

        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to set Input frames, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
        
    }

    if (!m_OutputChannels.empty())
    {
        err = AudioUnitGetProperty(m_AUHALAudioUnit,
                                   kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
                                   AUHAL_OUTPUT_ELEMENT,
                                   &auhalStreamFormat, &propSize);
        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to get Output format, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
        
        if (auhalStreamFormat.mSampleRate != (Float64)m_CurrentSamplingRate)
        {
            TRACE_MSG ("AUHAL's Output SR differs from expected SR, expected = " << m_CurrentSamplingRate << ", AUHAL's = " << (UInt32)auhalStreamFormat.mSampleRate);
        }
        
        
        streamFormatToUse.mChannelsPerFrame = m_OutputChannels.size();
        streamFormatToUse.mBytesPerFrame = sizeof (float)*streamFormatToUse.mChannelsPerFrame;
        streamFormatToUse.mBytesPerPacket = streamFormatToUse.mBytesPerFrame;
        streamFormatToUse.mSampleRate = auhalStreamFormat.mSampleRate;
        propSize = sizeof (streamFormatToUse);
        err = AudioUnitSetProperty(m_AUHALAudioUnit,
                                   kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
                                   AUHAL_OUTPUT_ELEMENT,
                                   &streamFormatToUse, sizeof (streamFormatToUse));

        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to set Output format, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }

        UInt32 bufferSize = m_CurrentBufferSize;
        err = AudioUnitSetProperty(m_AUHALAudioUnit,
                                   kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Input,
                                   AUHAL_OUTPUT_ELEMENT,
                                   &bufferSize, sizeof (bufferSize));

        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to set Output frames, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }

    }
    
    //setup callback (IOProc)
    {
        AURenderCallbackStruct renderCallback;
        memset (&renderCallback, 0, sizeof (renderCallback));
        propSize = sizeof (renderCallback);
        renderCallback.inputProc = StaticAudioIOProc;
        renderCallback.inputProcRefCon = this;
        
        err = AudioUnitSetProperty(m_AUHALAudioUnit,
                                   (m_OutputChannels.empty() ? (AudioUnitPropertyID)kAudioOutputUnitProperty_SetInputCallback : (AudioUnitPropertyID)kAudioUnitProperty_SetRenderCallback),
                                   kAudioUnitScope_Output,
                                   m_OutputChannels.empty() ? AUHAL_INPUT_ELEMENT : AUHAL_OUTPUT_ELEMENT,
                                   &renderCallback, sizeof (renderCallback));
            
        if (err != kAudioHardwareNoError)
        {
            DEBUG_MSG ("Unable to set callback, error = " << err);
            retVal = eGenericErr;
            goto Exit;
        }
    }

    retVal = EnableListeners();
    if (retVal != eNoErr)
        goto Exit;
    
    //initialize the audio-unit now!
    err = AudioUnitInitialize(m_AUHALAudioUnit);
    if (err != kAudioHardwareNoError)
    {
        DEBUG_MSG ("Unable to Initialize AudioUnit = " << err);
        retVal = eGenericErr;
        goto Exit;
    }
    
Exit:
    if (retVal != eNoErr)
        TearDownAUHAL();
        
    return retVal;
}



//**********************************************************************************************
// WCMRCoreAudioDevice::TearDownAUHAL
//
//! Undoes the work done by SetupAUHAL
//!
//! \param none
//! 
//! \return eNoErr on success, an error code on failure.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::TearDownAUHAL()
{
    WTErr retVal = eNoErr;

    if (m_AUHALAudioUnit)
    {
        DisableListeners ();
        AudioUnitUninitialize(m_AUHALAudioUnit);
        CloseComponent(m_AUHALAudioUnit);
        m_AUHALAudioUnit = NULL;
    }

    return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::SetActive 
//
//! Sets the device's activation status. Essentially, opens or closes the PA device. 
//!     If it's an ASIO device it may result in buffer size change in some cases.
//!
//! \param newState : Should be true to activate, false to deactivate. This roughly corresponds
//!     to opening and closing the device handle/stream/audio unit.
//! 
//! \return eNoErr on success, an error code otherwise.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetActive (bool newState)
{
    AUTO_FUNC_DEBUG;

    WTErr retVal = eNoErr;
    
    if (Active() == newState)
        goto Exit;


    if (newState)
    {
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Setting up AUHAL.");
        retVal = SetupAUHAL();

        if (retVal != eNoErr)
            goto Exit;

        m_BufferSizeChangeRequested = 0;
        m_BufferSizeChangeReported = 0;
        m_ResetRequested = 0;
        m_ResetReported = 0;
        m_ResyncRequested = 0;
        m_ResyncReported = 0;
        m_SRChangeRequested = 0;
        m_SRChangeReported = 0;
        m_DropsDetected = 0;
        m_DropsReported = 0;
        m_IgnoreThisDrop = true;
    }
    else
    {
        if (Streaming())
        {
            SetStreaming (false);
        }

        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Tearing down AUHAL.");
        retVal = TearDownAUHAL();
        if (retVal != eNoErr)
            goto Exit;

        m_BufferSizeChangeRequested = 0;
        m_BufferSizeChangeReported = 0;
        m_ResetRequested = 0;
        m_ResetReported = 0;
        m_ResyncRequested = 0;
        m_ResyncReported = 0;
        m_SRChangeRequested = 0;
        m_SRChangeReported = 0;
        m_DropsDetected = 0;
        m_DropsReported = 0;
        m_IgnoreThisDrop = true;

        UpdateDeviceInfo();
    }
    
    m_IsActive = newState;
    
Exit:   
    return (retVal);
}


#if WV_USE_TONE_GEN
//**********************************************************************************************
// WCMRCoreAudioDevice::SetupToneGenerator
//
//! Sets up the Tone generator - only if a file /tmp/tonegen.txt is present. If the file is
//!     present, it reads the value in the file and uses that as the frequency for the tone. This
//!     code attempts to create an array of samples that would constitute an integral number of
//!     cycles - for the currently active sampling rate. If tonegen is active, then the input
//!     from the audio device is ignored, instead a data is supplied from the tone generator's
//!     array - for all channels. The array is in m_pToneData, the size of the array is in
//!     m_ToneDataSamples, and m_NextSampleToUse holds the index in the array from where
//!     the next sample is going to be taken.
//!
//!
//! \return : Nothing
//!
//**********************************************************************************************
void WCMRCoreAudioDevice::SetupToneGenerator ()
{
    safe_delete_array(m_pToneData);
    m_ToneDataSamples = 0;

    //if tonegen exists?
    FILE *toneGenHandle = fopen ("/tmp/tonegen.txt", "r");
    if (toneGenHandle)
    {
        int toneFreq = 0;
        fscanf(toneGenHandle, "%d", &toneFreq);
        if ((toneFreq <= 0) || (toneFreq > (m_CurrentSamplingRate/2)))
        {
            toneFreq = 1000;    
        }
        
        
        m_ToneDataSamples = m_CurrentSamplingRate / toneFreq;
        int toneDataSamplesFrac = m_CurrentSamplingRate % m_ToneDataSamples;
        int powerOfTen = 1;
        while (toneDataSamplesFrac)
        {
            m_ToneDataSamples = (uint32_t)((pow(10, powerOfTen) * m_CurrentSamplingRate) / toneFreq);
            toneDataSamplesFrac = m_CurrentSamplingRate % m_ToneDataSamples;
            powerOfTen++;
        }
        
        //allocate
        m_pToneData = new float_t[m_ToneDataSamples];
        
        //fill with a -6dB Sine Tone
        uint32_t numSamplesLeft = m_ToneDataSamples;
        float_t *pNextSample = m_pToneData;
        double phase = 0;
        double phaseIncrement = (M_PI * 2.0 * toneFreq ) / ((double)m_CurrentSamplingRate);
        while (numSamplesLeft)
        {
            *pNextSample = (float_t)(0.5 * sin(phase));
            phase += phaseIncrement;
            pNextSample++;
            numSamplesLeft--;
        }
        
        m_NextSampleToUse = 0;
        
        fclose(toneGenHandle);
    }
}
#endif //WV_USE_TONE_GEN


//**********************************************************************************************
// WCMRCoreAudioDevice::SetStreaming
//
//! Sets the device's streaming status. Calls PA's Start/Stop stream routines.
//!
//! \param newState : Should be true to start streaming, false to stop streaming. This roughly
//!     corresponds to calling Start/Stop on the lower level interface.
//! 
//! \return eNoErr always, the derived classes may return appropriate error code.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetStreaming (bool newState)
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    ComponentResult err = 0;

    if (Streaming () == newState)
        goto Exit;

    if (newState)
    {
#if WV_USE_TONE_GEN
        SetupToneGenerator ();
#endif //WV_USE_TONE_GEN

        m_SampleCountAtLastIdle = 0;
        m_StalledSampleCounter = 0;
        m_SampleCounter = 0;
        m_IOProcThreadPort = 0;
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Starting AUHAL.");
        
		// Prepare for streaming - tell Engine to do the initialization for process callback
		m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStartsStreaming);

        if (m_UseMultithreading)
        {
            //set thread constraints...
            unsigned int periodAndConstraintUS = (unsigned int)((1000000.0 * m_CurrentBufferSize) / m_CurrentSamplingRate);
            unsigned int computationUS = (unsigned int)(0.8 * periodAndConstraintUS); //assuming we may want to use up to 80% CPU
            //ErrandManager().SetRealTimeConstraintsForAllThreads (periodAndConstraintUS, computationUS, periodAndConstraintUS);
        }
        
        err = AudioOutputUnitStart (m_AUHALAudioUnit);
        
        m_StopRequested = false;
        
        if(err)
        {
            DEBUG_MSG( "Failed to start AudioUnit, err " << err );
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Failed to start AudioUnit.");
            retVal = eGenericErr;
            goto Exit;
        }
    }
    else
    {
        m_StopRequested = true;
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Stopping AUHAL.");
        err = AudioOutputUnitStop (m_AUHALAudioUnit);
        if (!err)
        {
            //if (!m_InputChannels.empty());
            {
                err = AudioUnitReset (m_AUHALAudioUnit, kAudioUnitScope_Global, AUHAL_INPUT_ELEMENT);
            }
            //if (!m_OutputChannels.empty());
            {
                err = AudioUnitReset (m_AUHALAudioUnit, kAudioUnitScope_Global, AUHAL_OUTPUT_ELEMENT);
            }
        }
        
        if(err)
        {
            DEBUG_MSG( "Failed to stop AudioUnit " << err );
            retVal = eGenericErr;
            goto Exit;
        }
        m_IOProcThreadPort = 0;
    }

    // After units restart, reset request for reset and SR change
    m_SRChangeReported = m_SRChangeRequested;
    m_ResetReported = m_ResetRequested;
    
    m_IsStreaming = newState;

Exit:   
    return (retVal);
}


//**********************************************************************************************
// WCMRCoreAudioDevice::DoIdle 
//
//! A place for doing idle time processing. The other derived classes will probably do something
//!     meaningful.
//!
//! \param none
//! 
//! \return eNoErr always.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::DoIdle ()
{
    /*
    if (m_BufferSizeChangeRequested != m_BufferSizeChangeReported)
    {
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged);
        m_BufferSizeChangeReported = m_BufferSizeChangeRequested;
    }

    if (m_ResetRequested != m_ResetReported)
    {
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
        m_ResetReported = m_ResetRequested;
    }


    if (m_ResyncRequested != m_ResyncReported)
    {
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestResync);
        m_ResyncReported = m_ResyncRequested;
    }
    
    if (m_SRChangeReported != m_SRChangeRequested)
    {
        m_SRChangeReported = m_SRChangeRequested;
        int newSR = CurrentSamplingRate();
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged, (void *)newSR);
    }

    if (m_DropsReported != m_DropsDetected)
    {
        m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDroppedSamples);
        m_DropsReported = m_DropsDetected;
    }

    
    //Perhaps add checks to make sure a stream counter is incrementing if
    //stream is supposed to be streaming!
    if (Streaming())
    {
        //latch the value
        int64_t currentSampleCount = m_SampleCounter;
        if (m_SampleCountAtLastIdle == currentSampleCount)
            m_StalledSampleCounter++;
        else
        {
            m_SampleCountAtLastIdle = (int)currentSampleCount;
            m_StalledSampleCounter = 0;
        }

        if (m_StalledSampleCounter > NUM_STALLS_FOR_NOTIFICATION)
        {
            m_StalledSampleCounter = 0;
            m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStoppedStreaming, (void *)currentSampleCount);
        }
    }*/

    
    return (eNoErr);
}





//**********************************************************************************************
// WCMRCoreAudioDevice::SetMonitorChannels 
//
//! Used to set the channels to be used for monitoring.
//!
//! \param leftChannel : Left monitor channel index.
//! \param rightChannel : Right monitor channel index.
//! 
//! \return eNoErr always, the derived classes may return appropriate errors.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetMonitorChannels (int leftChannel, int rightChannel)
{
    AUTO_FUNC_DEBUG;
    //This will most likely be overridden, the base class simply
    //changes the member.
    m_LeftMonitorChannel = leftChannel;
    m_RightMonitorChannel = rightChannel;
    return (eNoErr);
}



//**********************************************************************************************
// WCMRCoreAudioDevice::SetMonitorGain 
//
//! Used to set monitor gain (or atten).
//!
//! \param newGain : The new gain or atten. value to use. Specified as a linear multiplier (not dB) 
//! 
//! \return eNoErr always, the derived classes may return appropriate errors.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::SetMonitorGain (float newGain)
{
    AUTO_FUNC_DEBUG;
    //This will most likely be overridden, the base class simply
    //changes the member.
    
    
    m_MonitorGain = newGain;
    return (eNoErr);
}




//**********************************************************************************************
// WCMRCoreAudioDevice::ShowConfigPanel 
//
//! Used to show device specific config/control panel. Some interfaces may not support it.
//!     Some interfaces may require the device to be active before it can display a panel.
//!
//! \param pParam : A device/interface specific parameter, should be the app window handle for ASIO.
//! 
//! \return eNoErr always, the derived classes may return errors.
//! 
//**********************************************************************************************
WTErr WCMRCoreAudioDevice::ShowConfigPanel (void */*pParam*/)
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    
    CFStringRef configAP;
    UInt32 propSize = sizeof (configAP);
    /*
      @constant       kAudioDevicePropertyConfigurationApplication
      A CFString that contains the bundle ID for an application that provides a
      GUI for configuring the AudioDevice. By default, the value of this property
      is the bundle ID for Audio MIDI Setup. The caller is responsible for
      releasing the returned CFObject.
    */
    
    if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyConfigurationApplication, &propSize, &configAP) == kAudioHardwareNoError)
    {
        //  get the FSRef of the config app
        FSRef theAppFSRef;
        OSStatus theError = LSFindApplicationForInfo(kLSUnknownCreator, configAP, NULL, &theAppFSRef, NULL);
        if (!theError)
        {
            LSOpenFSRef(&theAppFSRef, NULL);
        }
        else
        {
            // open default AudioMIDISetup if device app is not found
            CFStringRef audiMidiSetupApp = CFStringCreateWithCString(kCFAllocatorDefault, "com.apple.audio.AudioMIDISetup", kCFStringEncodingMacRoman);
            theError = LSFindApplicationForInfo(kLSUnknownCreator, audiMidiSetupApp, NULL, &theAppFSRef, NULL);
            
            if (!theError)
            {
                LSOpenFSRef(&theAppFSRef, NULL);
            }
        }
        
        CFRelease (configAP);
    }
    
    return (retVal);
}


//**********************************************************************************************
// WCMRCoreAudioDevice::StaticAudioIOProc
//
//! The AudioIOProc that gets called when the AudioUnit is ready with recorded audio, and wants to get audio.
//!     This one simply calls the non-static member.
//!
//! \param inRefCon : What was passed when setting up the Callback (in our case a pointer to teh WCMRCoreAudioDevice object).
//! \param ioActionFlags : What actios has to be taken.
//! \param inTimeStamp: When the data will be played back.
//! \param inBusNumber : The AU element.
//! \param inNumberFrames: Number af Audio frames that are requested.
//! \param ioData : Where the playback data is to be placed.
//! 
//! \return 0 always
//! 
//**********************************************************************************************
OSStatus WCMRCoreAudioDevice::StaticAudioIOProc(void *inRefCon, AudioUnitRenderActionFlags *    ioActionFlags,
                                                const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames,
                                                AudioBufferList *ioData)
{
    WCMRCoreAudioDevice *pMyDevice = (WCMRCoreAudioDevice *)inRefCon;
    if (pMyDevice)
        return pMyDevice->AudioIOProc (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
    else
        return 0;
}




//**********************************************************************************************
// WCMRCoreAudioDevice::AudioIOProc
//
//! The non-static AudioIOProc that gets called when the AudioUnit is ready with recorded audio, and wants to get audio.
//!     We retrieve the recorded audio, and then do our processing, to generate audio to be played back.
//!
//! \param ioActionFlags : What actios has to be taken.
//! \param inTimeStamp: When the data will be played back.
//! \param inBusNumber : The AU element.
//! \param inNumberFrames: Number af Audio frames that are requested.
//! \param ioData : Where the playback data is to be placed.
//! 
//! \return 0 always
//! 
//**********************************************************************************************
OSStatus WCMRCoreAudioDevice::AudioIOProc(AudioUnitRenderActionFlags *  ioActionFlags,
                                          const AudioTimeStamp *inTimeStamp, UInt32 /*inBusNumber*/, UInt32 inNumberFrames,
                                          AudioBufferList *ioData)
{
    UInt64 theStartTime = AudioGetCurrentHostTime();

    OSStatus retVal = 0;
    
    if (m_StopRequested)
        return retVal;

    if (m_IOProcThreadPort == 0)
        m_IOProcThreadPort = mach_thread_self ();
    
    //cannot really deal with it unless the number of frames are the same as our buffer size!
    if (inNumberFrames != (UInt32)m_CurrentBufferSize)
        return retVal;
    
    //Retrieve the input data...
    if (!m_InputChannels.empty())
    {
        UInt32 expectedDataSize = m_InputChannels.size() * m_CurrentBufferSize * sizeof(float);
        AudioBufferList inputAudioBufferList;
        inputAudioBufferList.mNumberBuffers = 1;
        inputAudioBufferList.mBuffers[0].mNumberChannels = m_InputChannels.size();
        inputAudioBufferList.mBuffers[0].mDataByteSize = expectedDataSize;
        inputAudioBufferList.mBuffers[0].mData = NULL;//new float[expectedDataSize]; // we are going to get buffer from CoreAudio
        
        retVal = AudioUnitRender(m_AUHALAudioUnit, ioActionFlags, inTimeStamp, AUHAL_INPUT_ELEMENT, inNumberFrames, &inputAudioBufferList);
        
        if (retVal == kAudioHardwareNoError &&
            inputAudioBufferList.mBuffers[0].mNumberChannels == m_InputChannels.size() &&
            inputAudioBufferList.mBuffers[0].mDataByteSize == expectedDataSize )
        {
            m_pInputData = (float*)inputAudioBufferList.mBuffers[0].mData;
        }
        else
        {
            m_pInputData = NULL;
            return retVal;
        }
    }
    
    //is this an input only device?
    if (m_OutputChannels.empty())
        AudioCallback (NULL, inNumberFrames, (int64_t)inTimeStamp->mSampleTime, theStartTime);
    else if ((!m_OutputChannels.empty()) && (ioData->mBuffers[0].mNumberChannels == m_OutputChannels.size()))
        AudioCallback ((float *)ioData->mBuffers[0].mData, inNumberFrames, (int64_t)inTimeStamp->mSampleTime, theStartTime);
    
    return retVal;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::AudioCallback 
//
//! Here's where the actual audio processing happens. We call upon all the active connections' 
//!     sinks to provide data to us which can be put/mixed in the output buffer! Also, we make the 
//!     input data available to any sources that may call upon us during this time!
//!
//! \param *pOutputBuffer : Points to a buffer to receive playback data. For Input only devices, this will be NULL
//! \param framesPerBuffer : Number of sample frames in input and output buffers. Number of channels,
//!     which are interleaved, is fixed at Device Open (Active) time. In this implementation,
//!     the number of channels are fixed to use the maximum available.
//! 
//! \return true
//! 
//**********************************************************************************************
int WCMRCoreAudioDevice::AudioCallback (float *pOutputBuffer, unsigned long framesPerBuffer, int64_t inSampleTime, uint64_t inCycleStartTime)
{
    struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData =
    {
        m_pInputData,
        pOutputBuffer,
        framesPerBuffer,
        inSampleTime,
        AudioConvertHostTimeToNanos(inCycleStartTime)
    };
    
    m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData);
    
    m_SampleCounter += framesPerBuffer;
    return m_StopRequested;
}


//**********************************************************************************************
// WCMRCoreAudioDevice::GetLatency
//
//! Get Latency for device.
//!
//! Use 'kAudioDevicePropertyLatency' and 'kAudioDevicePropertySafetyOffset' + GetStreamLatencies
//!
//! \param isInput : Return latency for the input if isInput is true, otherwise the output latency
//!                  wiil be returned.
//! \return Latency in samples.
//!
//**********************************************************************************************
uint32_t WCMRCoreAudioDevice::GetLatency(bool isInput)
{
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;

    UInt32 propSize = sizeof(UInt32);
    UInt32 value1 = 0;
    UInt32 value2 = 0;
    
    UInt32 latency = 0;
    std::vector<int> streamLatencies;
    
    
    err = AudioDeviceGetProperty(m_DeviceID, 0, isInput, kAudioDevicePropertyLatency, &propSize, &value1);
    if (err != kAudioHardwareNoError)
    {
        DEBUG_MSG("GetLatency kAudioDevicePropertyLatency err = " << err);
    }

    err = AudioDeviceGetProperty(m_DeviceID, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &value2);
    if (err != kAudioHardwareNoError)
    {
        DEBUG_MSG("GetLatency kAudioDevicePropertySafetyOffset err = " << err);
    }

    latency = value1 + value2;

    err = GetStreamLatency(m_DeviceID, isInput, streamLatencies);
    if (err == kAudioHardwareNoError)
    {
        for ( int i = 0; i < streamLatencies.size(); i++) {
            latency += streamLatencies[i];
        }
    }
    
    return latency;
}

//**********************************************************************************************
// WCMRCoreAudioDevice::GetStreamLatency
//
//! Get stream latency for device.
//!
//! \param deviceID : The audio device ID.
//!
//! \param isInput : Return latency for the input if isInput is true, otherwise the output latency
//!                  wiil be returned.
//**********************************************************************************************
OSStatus WCMRCoreAudioDevice::GetStreamLatency(AudioDeviceID device, bool isInput, std::vector<int>& latencies)
{
    OSStatus err = kAudioHardwareNoError;
    UInt32 outSize1, outSize2, outSize3;
    Boolean	outWritable;
    
    err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, &outWritable);
    if (err == noErr) {
        int stream_count = outSize1 / sizeof(UInt32);
        AudioStreamID streamIDs[stream_count];
        AudioBufferList bufferList[stream_count];
        UInt32 streamLatency;
        outSize2 = sizeof(UInt32);
        
        err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, streamIDs);
        if (err != noErr) {
            DEBUG_MSG("GetStreamLatencies kAudioDevicePropertyStreams err = " << err);
            return err;
        }
        
        err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, &outWritable);
        if (err != noErr) {
            DEBUG_MSG("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = " << err);
            return err;
        }
        
        for (int i = 0; i < stream_count; i++) {
            err = AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &outSize2, &streamLatency);
            if (err != noErr) {
                DEBUG_MSG("GetStreamLatencies kAudioStreamPropertyLatency err = " << err);
                return err;
            }
            err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, bufferList);
            if (err != noErr) {
                DEBUG_MSG("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = " << err);
                return err;
            }
            latencies.push_back(streamLatency);
        }
    }
    return err;
}


//**********************************************************************************************
// WCMRCoreAudioDeviceManager::WCMRCoreAudioDeviceManager
//
//! The constructuor, we initialize PA, and build the device list.
//!
//! \param *pTheClient : The manager's client object (which receives notifications).
//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true.
//! 
//! \return Nothing.
//! 
//**********************************************************************************************
WCMRCoreAudioDeviceManager::WCMRCoreAudioDeviceManager(WCMRAudioDeviceManagerClient *pTheClient,
                            eAudioDeviceFilter eCurAudioDeviceFilter, bool useMultithreading, bool bNocopy)
  : WCMRAudioDeviceManager (pTheClient, eCurAudioDeviceFilter)
  , m_UseMultithreading (useMultithreading)
  , m_bNoCopyAudioBuffer(bNocopy)
{
    AUTO_FUNC_DEBUG;

    //first of all, tell HAL to use it's own run loop, not to wait for our runloop to do
    //it's dirty work...
    //Essentially, this makes the HAL on Snow Leopard behave like Leopard.
    //It's not yet (as of October 2009 documented), but the following discussion
    //has the information provided by Jeff Moore @ Apple:
    // http://lists.apple.com/archives/coreaudio-api/2009/Oct/msg00214.html
    //
    // As per Jeff's suggestion, opened an Apple Bug on this - ID# 7364011
    
    CFRunLoopRef nullRunLoop = 0;
    OSStatus err = AudioHardwareSetProperty (kAudioHardwarePropertyRunLoop, sizeof(CFRunLoopRef), &nullRunLoop);

    if (err != kAudioHardwareNoError)
    {
        syslog (LOG_NOTICE, "Unable to set RunLoop for Audio Hardware");
    }

    //add a listener to find out when devices change...
    AudioHardwareAddPropertyListener (kAudioHardwarePropertyDevices, HardwarePropertyChangeCallback, this);
    
    //Always add the None device first...
    m_NoneDevice = new WCMRNativeAudioNoneDevice(this);

    //prepare our initial list...
    generateDeviceListImpl();

    return;
}



//**********************************************************************************************
// WCMRCoreAudioDeviceManager::~WCMRCoreAudioDeviceManager
//
//! It clears the device list, releasing each of the device.
//!
//! \param none
//! 
//! \return Nothing.
//! 
//**********************************************************************************************
WCMRCoreAudioDeviceManager::~WCMRCoreAudioDeviceManager()
{
    AUTO_FUNC_DEBUG;

    try
    {
        delete m_NoneDevice;
    }
    catch (...)
    {
        //destructors should absorb exceptions, no harm in logging though!!
        DEBUG_MSG ("Exception during destructor");
    }

}


WCMRAudioDevice* WCMRCoreAudioDeviceManager::initNewCurrentDeviceImpl(const std::string & deviceName)
{
    destroyCurrentDeviceImpl();
    
    std::cout << "API::PortAudioDeviceManager::initNewCurrentDevice " << deviceName << std::endl;
	if (deviceName == m_NoneDevice->DeviceName() )
	{
		m_CurrentDevice = m_NoneDevice;
		return m_CurrentDevice;
	}
    
	DeviceInfo devInfo;
    WTErr err = GetDeviceInfoByName(deviceName, devInfo);
    
	if (eNoErr == err)
	{
		try
		{
			std::cout << "API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName << std::endl;
			TRACE_MSG ("API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName);
            
            m_CurrentDevice = new WCMRCoreAudioDevice (this, devInfo.m_DeviceId, m_UseMultithreading, m_bNoCopyAudioBuffer);
		}
		catch (...)
		{
			std::cout << "Unabled to create PA Device: " << devInfo.m_DeviceId << std::endl;
			DEBUG_MSG ("Unabled to create PA Device: " << devInfo.m_DeviceId);
		}
	}
    
	return m_CurrentDevice;
}


void WCMRCoreAudioDeviceManager::destroyCurrentDeviceImpl()
{
    if (m_CurrentDevice != m_NoneDevice)
        delete m_CurrentDevice;
    
    m_CurrentDevice = 0;
}
    
    
WTErr WCMRCoreAudioDeviceManager::getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates)
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    sampleRates.clear();
    
    //! 1. Get sample rate property size.
    err = AudioDeviceGetPropertyInfo(deviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels output.
        
        // Allocate size according to the number of audio values
        int numRates = propSize / sizeof(AudioValueRange);
        AudioValueRange* supportedRates = new AudioValueRange[numRates];
        
        // Get sampling rates from Audio device
        err = AudioDeviceGetProperty(deviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, supportedRates);
        if (err == kAudioHardwareNoError)
        {
            //! 3. Update sample rates
            
            // now iterate through our standard SRs
            for(int ourSR=0; gAllSampleRates[ourSR] > 0; ourSR++)
            {
                //check to see if our SR is in the supported rates...
                for (int deviceSR = 0; deviceSR < numRates; deviceSR++)
                {
                    if ((supportedRates[deviceSR].mMinimum <= gAllSampleRates[ourSR]) &&
                        (supportedRates[deviceSR].mMaximum >= gAllSampleRates[ourSR]))
                    {
                        sampleRates.push_back ((int)gAllSampleRates[ourSR]);
                        break;
                    }
                }
            }
        }
        else
        {
            retVal = eCoreAudioFailed;
            DEBUG_MSG("Failed to get device Sample rates. Device Name: " << m_DeviceName.c_str());
        }
        
        delete [] supportedRates;
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Sample rates property size. Device Name: " << m_DeviceName.c_str());
    }
    
    return retVal;
}

    
WTErr WCMRCoreAudioDeviceManager::getDeviceMaxInputChannels(DeviceID deviceId, unsigned int& inputChannels)
{
    AUTO_FUNC_DEBUG;
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    inputChannels = 0;

    // 1. Get property cannels input size.
    err = AudioDeviceGetPropertyInfo (deviceId, 0, 1/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels input.
        
        // Allocate size according to the property size. Note that this is a variable sized struct...
        AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize);
        
        if (pStreamBuffers)
        {
            memset (pStreamBuffers, 0, propSize);
            
            // Get the Input channels
            err = AudioDeviceGetProperty (deviceId, 0, 1/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers);
            if (err == kAudioHardwareNoError)
            {
                // Calculate the number of input channels
                for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++)
                {
                    inputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels;
                }
            }
            else
            {
                retVal = eCoreAudioFailed;
                DEBUG_MSG("Failed to get device Input channels. Device Name: " << m_DeviceName.c_str());
            }
            
            free (pStreamBuffers);
        }
        else
        {
            retVal = eMemOutOfMemory;
            DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str());
        }
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Input channels property size. Device Name: " << m_DeviceName.c_str());
    }
    
    return retVal;
}
    

WTErr WCMRCoreAudioDeviceManager::getDeviceMaxOutputChannels(DeviceID deviceId, unsigned int& outputChannels)
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    outputChannels = 0;

    //! 1. Get property cannels output size.
    err = AudioDeviceGetPropertyInfo (deviceId, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL);
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels output.
        
        // Allocate size according to the property size. Note that this is a variable sized struct...
        AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize);
        if (pStreamBuffers)
        {
            memset (pStreamBuffers, 0, propSize);
            
            // Get the Output channels
            err = AudioDeviceGetProperty (deviceId, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers);
            if (err == kAudioHardwareNoError)
            {
                // Calculate the number of output channels
                for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++)
                {
                    outputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels;
                }
            }
            else
            {
                retVal = eCoreAudioFailed;
                DEBUG_MSG("Failed to get device Output channels. Device Name: " << m_DeviceName.c_str());
            }
            free (pStreamBuffers);
        }
        else
        {
            retVal = eMemOutOfMemory;
            DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str());
        }
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Output channels property size. Device Name: " << m_DeviceName.c_str());
    }
 
    return retVal;
}
    
    
WTErr WCMRCoreAudioDeviceManager::generateDeviceListImpl()
{
    AUTO_FUNC_DEBUG;
    
    // lock the list first
    wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex);
    m_DeviceInfoVec.clear();
    
    //First, get info from None device which is always present
    if (m_NoneDevice)
    {
        DeviceInfo *pDevInfo = new DeviceInfo(NONE_DEVICE_ID, m_NoneDevice->DeviceName() );
        pDevInfo->m_AvailableSampleRates = m_NoneDevice->SamplingRates();
        m_DeviceInfoVec.push_back(pDevInfo);
    }
    
    WTErr retVal = eNoErr;
    OSStatus osErr = noErr;
    AudioDeviceID* deviceIDs = 0;
    
    openlog("WCMRCoreAudioDeviceManager", LOG_PID | LOG_CONS, LOG_USER);
    
    try
    {
        //Get device count...
        UInt32 propSize = 0;
        osErr = AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &propSize, NULL);
        ASSERT_ERROR(osErr, "AudioHardwareGetProperty 1");
        if (WUIsError(osErr))
            throw osErr;
        
        size_t numDevices = propSize / sizeof (AudioDeviceID);
        deviceIDs = new AudioDeviceID[numDevices];
        
        //retrieve the device IDs
        propSize = numDevices * sizeof (AudioDeviceID);
        osErr = AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &propSize, deviceIDs);
        ASSERT_ERROR(osErr, "Error while getting audio devices: AudioHardwareGetProperty 2");
        if (WUIsError(osErr))
            throw osErr;
        
        //now add the ones that are not there...
        for (size_t deviceIndex = 0; deviceIndex < numDevices; deviceIndex++)
        {
            DeviceInfo* pDevInfo = 0;
            
            //Get device name and create new DeviceInfo entry
            //Get property name size.
            osErr = AudioDeviceGetPropertyInfo(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL);
            if (osErr == kAudioHardwareNoError)
            {
                //Get property: name.
                char* deviceName = new char[propSize];
                osErr = AudioDeviceGetProperty(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, deviceName);
                if (osErr == kAudioHardwareNoError)
                {
                    pDevInfo = new DeviceInfo(deviceIDs[deviceIndex], deviceName);
                }
                else
                {
                    retVal = eCoreAudioFailed;
                    DEBUG_MSG("Failed to get device name. Device ID: " << m_DeviceID);
                }
                
                delete [] deviceName;
            }
            else
            {
                retVal = eCoreAudioFailed;
                DEBUG_MSG("Failed to get device name property size. Device ID: " << m_DeviceID);
            }
            
            if (pDevInfo)
            {
                //Retrieve all the information we need for the device
                WTErr wErr = eNoErr;
                
                //Get available sample rates for the device
                std::vector<int> availableSampleRates;
                wErr = getDeviceAvailableSampleRates(pDevInfo->m_DeviceId, availableSampleRates);
                
                if (wErr != eNoErr)
                {
                    DEBUG_MSG ("Failed to get device available sample rates. Device ID: " << m_DeviceID);
                    delete pDevInfo;
                    continue; //proceed to the next device
                }
                
                pDevInfo->m_AvailableSampleRates = availableSampleRates;
                
                //Get max input channels
                uint32_t maxInputChannels;
                wErr = getDeviceMaxInputChannels(pDevInfo->m_DeviceId, maxInputChannels);
                
                if (wErr != eNoErr)
                {
                    DEBUG_MSG ("Failed to get device max input channels count. Device ID: " << m_DeviceID);
                    delete pDevInfo;
                    continue; //proceed to the next device
                }
                
                pDevInfo->m_MaxInputChannels = maxInputChannels;
                
                //Get max output channels
                uint32_t maxOutputChannels;
                wErr = getDeviceMaxOutputChannels(pDevInfo->m_DeviceId, maxOutputChannels);
                
                if (wErr != eNoErr)
                {
                    DEBUG_MSG ("Failed to get device max output channels count. Device ID: " << m_DeviceID);
                    delete pDevInfo;
                    continue; //proceed to the next device
                }
                
                pDevInfo->m_MaxOutputChannels = maxOutputChannels;
                
                //Now check if this device is acceptable according to current input/output settings
                bool bRejectDevice = false;
                switch(m_eAudioDeviceFilter)
                {
                    case eInputOnlyDevices:
                        if (pDevInfo->m_MaxInputChannels != 0)
                        {
                            m_DeviceInfoVec.push_back(pDevInfo);
                        }
                        else
                        {
                            // Delete unnecesarry device
                            bRejectDevice = true;
                        }
                        break;
                    case eOutputOnlyDevices:
                        if (pDevInfo->m_MaxOutputChannels != 0)
                        {
                            m_DeviceInfoVec.push_back(pDevInfo);
                        }
                        else
                        {
                            // Delete unnecesarry device
                            bRejectDevice = true;
                        }
                        break;
                    case eFullDuplexDevices:
                        if (pDevInfo->m_MaxInputChannels != 0 && pDevInfo->m_MaxOutputChannels != 0)
                        {
                            m_DeviceInfoVec.push_back(pDevInfo);
                        }
                        else
                        {
                            // Delete unnecesarry device
                            bRejectDevice = true;
                        }
                        break;
                    case eAllDevices:
                    default:
                        m_DeviceInfoVec.push_back(pDevInfo);
                        break;
                }
                
                if(bRejectDevice)
                {
                    syslog (LOG_NOTICE, "%s rejected, In Channels = %d, Out Channels = %d\n",
                            pDevInfo->m_DeviceName.c_str(), pDevInfo->m_MaxInputChannels, pDevInfo->m_MaxOutputChannels);
                    // In case of Input and Output both channels being Zero, we will release memory; since we created CoreAudioDevice but we are Not adding it in list.
                    delete pDevInfo;
                }
            }
        }
        
        
        //If no devices were found, that's not a good thing!
        if (m_DeviceInfoVec.empty())
        {
            DEBUG_MSG ("No matching CoreAudio devices were found\n");
        }        
    }
    catch (...)
    {
        if (WUNoError(retVal))
            retVal = eCoreAudioFailed;
    }
    
    delete[] deviceIDs;
    closelog();
    
    return retVal;
}


WTErr WCMRCoreAudioDeviceManager::updateDeviceListImpl()
{
    wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex);
    WTErr err = generateDeviceListImpl();
    
    if (eNoErr != err)
    {
        std::cout << "API::PortAudioDeviceManager::updateDeviceListImpl: Device list update error: "<< err << std::endl;
    }
    
    if (m_CurrentDevice)
    {
        // if we have device initialized we should find out if this device is still connected
        DeviceInfo devInfo;
        WTErr deviceLookUpErr = GetDeviceInfoByName(m_CurrentDevice->DeviceName(), devInfo );
    
        if (eNoErr != deviceLookUpErr)
        {
            NotifyClient (WCMRAudioDeviceManagerClient::IODeviceDisconnected);
            return err;
        }
        
        WCMRCoreAudioDevice* current_device = dynamic_cast<WCMRCoreAudioDevice*>(m_CurrentDevice);
        
        if ( current_device &&
            (current_device->DeviceID() != devInfo.m_DeviceId ) )
        {
            NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
            return err;
        }
    }
    
    NotifyClient (WCMRAudioDeviceManagerClient::DeviceListChanged);
    
    return err;
}


WTErr WCMRCoreAudioDeviceManager::getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    sampleRates.clear();
    
    //first check if the request has been made for None device
	if (deviceName == m_NoneDevice->DeviceName() )
	{
		sampleRates = m_NoneDevice->SamplingRates();
		return retVal;
	}

    if (m_CurrentDevice && m_CurrentDevice->DeviceName () == deviceName) {
        sampleRates.assign(m_CurrentDevice->SamplingRates().begin(), m_CurrentDevice->SamplingRates().end() );
        return retVal;
    }
    
    DeviceInfo devInfo;
    retVal = GetDeviceInfoByName(deviceName, devInfo);
    
    //! 1. Get sample rate property size.
    err = AudioDeviceGetPropertyInfo(devInfo.m_DeviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, NULL);
    
    if (err == kAudioHardwareNoError)
    {
        //! 2. Get property: cannels output.
        
        // Allocate size accrding to the number of audio values
        int numRates = propSize / sizeof(AudioValueRange);
        AudioValueRange* supportedRates = new AudioValueRange[numRates];
        
        // Get sampling rates from Audio device
        err = AudioDeviceGetProperty(devInfo.m_DeviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, supportedRates);
        
        if (err == kAudioHardwareNoError)
        {
            //! 3. Update sample rates
            
            // now iterate through our standard SRs
            for(int ourSR=0; gAllSampleRates[ourSR] > 0; ourSR++)
            {
                //check to see if our SR is in the supported rates...
                for (int deviceSR = 0; deviceSR < numRates; deviceSR++)
                {
                    if ((supportedRates[deviceSR].mMinimum <= gAllSampleRates[ourSR]) &&
                        (supportedRates[deviceSR].mMaximum >= gAllSampleRates[ourSR]))
                    {
                        sampleRates.push_back ((int)gAllSampleRates[ourSR]);
                        break;
                    }
                }
            }
        }
        else
        {
            retVal = eCoreAudioFailed;
            DEBUG_MSG("Failed to get device Sample rates. Device Name: " << m_DeviceName.c_str());
        }
        
        delete [] supportedRates;
    }
    else
    {
        retVal = eCoreAudioFailed;
        DEBUG_MSG("Failed to get device Sample rates property size. Device Name: " << m_DeviceName.c_str());
    }

    devInfo.m_AvailableSampleRates.assign(sampleRates.begin(), sampleRates.end() );
    
    return retVal;
}


WTErr WCMRCoreAudioDeviceManager::getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& bufferSizes) const
{
    AUTO_FUNC_DEBUG;
    
    WTErr retVal = eNoErr;
    OSStatus err = kAudioHardwareNoError;
    UInt32 propSize = 0;
    
    bufferSizes.clear();
    
    //first check if the request has been made for None device
	if (deviceName == m_NoneDevice->DeviceName() )
	{
		bufferSizes = m_NoneDevice->BufferSizes();
		return retVal;
	}
    
    if (m_CurrentDevice && m_CurrentDevice->DeviceName () == deviceName) {
        bufferSizes.assign(m_CurrentDevice->BufferSizes().begin(), m_CurrentDevice->BufferSizes().end() );
        return retVal;
    }
    
    DeviceInfo devInfo;
    retVal = GetDeviceInfoByName(deviceName, devInfo);
    
    if (eNoErr == retVal)
    {
        // 1. Get buffer size range
        AudioValueRange bufferSizesRange;
        propSize = sizeof (AudioValueRange);
        err = AudioDeviceGetProperty (devInfo.m_DeviceId, 0, 0, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &bufferSizesRange);
        if(err == kAudioHardwareNoError)
        {
            // 2. Run on all ranges and add them to the list
            for(int bsize=0; gAllBufferSizes[bsize] > 0; bsize++)
            {
                if ((bufferSizesRange.mMinimum <= gAllBufferSizes[bsize]) && (bufferSizesRange.mMaximum >= gAllBufferSizes[bsize]))
                {
                    bufferSizes.push_back (gAllBufferSizes[bsize]);
                }
            }
            
            //if we didn't get a single hit, let's simply add the min. and the max...
            if (bufferSizes.empty())
            {
                bufferSizes.push_back ((int)bufferSizesRange.mMinimum);
                bufferSizes.push_back ((int)bufferSizesRange.mMaximum);
            }
        }
        else
        {
            retVal = eCoreAudioFailed;
            DEBUG_MSG("Failed to get device buffer sizes range. Device Name: " << m_DeviceName.c_str());
        }
    }
    else
	{
		retVal = eRMResNotFound;
		std::cout << "API::PortAudioDeviceManager::GetBufferSizes: Device not found: "<< deviceName << std::endl;
	}

    
    return retVal;
}


OSStatus WCMRCoreAudioDeviceManager::HardwarePropertyChangeCallback (AudioHardwarePropertyID inPropertyID, void* inClientData)
{
    switch (inPropertyID)
    {
        case kAudioHardwarePropertyDevices:
            {
                WCMRCoreAudioDeviceManager* pManager = (WCMRCoreAudioDeviceManager*)inClientData;
                if (pManager)
                    pManager->updateDeviceListImpl();
            }
            break;
            
        default:
            break;
    }
    
    return 0;
}