summaryrefslogtreecommitdiff
path: root/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.cpp
blob: c039b49c0b23c2eecb555fb7725dea9a2d73db6a (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
//----------------------------------------------------------------------------------
//
// Copyright (c) 2008 Waves Audio Ltd. All rights reserved.
//
//! \file	WCMRPortAudioDeviceManager.cpp
//!
//! WCMRPortAudioDeviceManager and related class declarations
//!
//---------------------------------------------------------------------------------*/
#include "WCMRPortAudioDeviceManager.h"
#include "MiscUtils/safe_delete.h"
#include "UMicroseconds.h"
#include <iostream>
#include <sstream>
#include <algorithm>
#include <list>
using namespace wvNS;
#include "IncludeWindows.h"
#include <mmsystem.h>
#include "pa_asio.h"
#include "asio.h"

#define PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS 200
#define DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS 500
#define PROPERTY_CHANGE_TIMEOUT_SECONDS 2
#define PROPERTY_CHANGE_RETRIES 3

///< 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
	};
	

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

static const int NONE_DEVICE_ID = -1;

///< Number of stalls to wait before notifying user...
static const int NUM_STALLS_FOR_NOTIFICATION = 100; // 100 corresponds to 100 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 HUNDRED_NANO_TO_MILLI_CONSTANT 10000
#define CONSUMPTION_CALCULATION_INTERVAL 500 // Milli Seconds


// This wrapper is used to adapt device DoIdle method as entry point for MS thread
DWORD WINAPI WCMRPortAudioDevice::__DoIdle__(LPVOID lpThreadParameter)
{
	WCMRPortAudioDevice* pDevice = (WCMRPortAudioDevice*)lpThreadParameter;
	pDevice->DoIdle();
	return 0;
}

//**********************************************************************************************
// WCMRPortAudioDevice::WCMRPortAudioDevice
//
//! Constructor for the audio device. Opens the PA device
//! and gets information about the device.
//! Starts the thread which will process requests to this 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.
//!
//**********************************************************************************************
WCMRPortAudioDevice::WCMRPortAudioDevice (WCMRPortAudioDeviceManager *pManager, unsigned int deviceID, bool useMultithreading, bool bNoCopy) :
	WCMRNativeAudioDevice (pManager, useMultithreading, bNoCopy)
	, m_SampleCounter(0)
	, m_BufferSizeChangeRequested (0)
	, m_BufferSizeChangeReported (0)
	, m_ResetRequested (0)
	, m_ResetReported (0)
	, m_ResyncRequested (0)
	, m_ResyncReported (0)
	, m_DropsDetected(0)
	, m_DropsReported(0)
	, m_IgnoreThisDrop(true)
	, m_hDeviceProcessingThread(NULL)
	, m_DeviceProcessingThreadID(0)
	, m_hUpdateDeviceInfoRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hUpdateDeviceInfoDone(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hActivateRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hActivationDone(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hDeActivateRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hDeActivationDone(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hStartStreamingRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hStartStreamingDone(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hStopStreamingRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hStopStreamingDone(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hResetRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hResetDone(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hResetFromDevRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hBufferSizeChangedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hSampleRateChangedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hExitIdleThread(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_hDeviceInitialized(CreateEvent(NULL, FALSE, FALSE, NULL))
	, m_lastErr(eNoErr)
{
    AUTO_FUNC_DEBUG;

	//Set initial device info...
	m_DeviceID = deviceID;
	m_PortAudioStream = NULL;
	m_CurrentSamplingRate = DEFAULT_SR;
	m_CurrentBufferSize = DEFAULT_BUFFERSIZE;
	m_StopRequested = true;
	m_pInputData = NULL;

	//initialize device processing thread
	//the divice become alive and now is able to process requests
	m_hDeviceProcessingThread = CreateThread( NULL, 0, __DoIdle__, (LPVOID)this, 0, &m_DeviceProcessingThreadID );

	if (!m_hDeviceProcessingThread)
	{
		DEBUG_MSG("API::Device " << m_DeviceName << " cannot create processing thread");
		throw eGenericErr;
	}

	WaitForSingleObject(m_hDeviceInitialized, INFINITE);

	if (ConnectionStatus() == DeviceErrors)
	{
		throw m_lastErr;
	}
}


void WCMRPortAudioDevice::initDevice()
{
	// Initialize COM for this thread
	std::cout << "API::Device " << m_DeviceID << " initializing COM" << std::endl;

	if (S_OK == CoInitialize(NULL) )
	{
		// Initialize PA
		Pa_Initialize();

		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];
			}
		}
		else
			std::cout << "API::Device " << m_DeviceName << " Device does not support any sample rate of ours" << std::endl;
	
		//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);
		}

		std::cout << "API::Device " << m_DeviceName << " Device has been initialized" << std::endl;
		m_ConnectionStatus = DeviceDisconnected;
		m_lastErr = eNoErr;
	}
	else
	{
		/*Replace with debug trace*/std::cout << "API::Device " << m_DeviceName << " cannot initialize COM" << std::endl;
		DEBUG_MSG("Device " << m_DeviceName << " cannot initialize COM");
		m_ConnectionStatus = DeviceErrors;
		m_lastErr = eSomeThingNotInitailzed;
		SetEvent(m_hExitIdleThread);
	}

	SetEvent(m_hDeviceInitialized);
}

void WCMRPortAudioDevice::terminateDevice()
{
	std::cout << "API::Device " << m_DeviceName << " Terminating DEVICE" << std::endl;

	//If device is streaming, need to stop it!
	if (Streaming())
	{
		stopStreaming();
	}
		
	//If device is active (meaning stream is open) we need to close it.
	if (Active())
	{
		deactivateDevice();
	}

	std::cout << "API::Device " << m_DeviceName << " Terminating PA" << std::endl;

	//Deinitialize PA
	Pa_Terminate();
}


//**********************************************************************************************
// WCMRPortAudioDevice::~WCMRPortAudioDevice
//
//! 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.
//!
//**********************************************************************************************
WCMRPortAudioDevice::~WCMRPortAudioDevice ()
{
    AUTO_FUNC_DEBUG;

	std::cout << "API::Destroying Device Instance: " << DeviceName() << std::endl;
	try
	{
		//Stop deviceprocessing thread
		SignalObjectAndWait(m_hExitIdleThread, m_hDeviceProcessingThread, INFINITE, false);

		std::cout << "API::Device " << m_DeviceName << " Processing Thread is stopped" << std::endl;

		CloseHandle(m_hDeviceProcessingThread);

		//Now it's safe to free all event handlers
		CloseHandle(m_hUpdateDeviceInfoRequestedEvent);
		CloseHandle(m_hUpdateDeviceInfoDone);
		CloseHandle(m_hActivateRequestedEvent);
		CloseHandle(m_hActivationDone);
		CloseHandle(m_hDeActivateRequestedEvent);
		CloseHandle(m_hDeActivationDone);
		CloseHandle(m_hStartStreamingRequestedEvent);
		CloseHandle(m_hStartStreamingDone);
		CloseHandle(m_hStopStreamingRequestedEvent);
		CloseHandle(m_hStopStreamingDone);
		CloseHandle(m_hResetRequestedEvent);
		CloseHandle(m_hResetDone);
		CloseHandle(m_hResetFromDevRequestedEvent);
		CloseHandle(m_hBufferSizeChangedEvent);
		CloseHandle(m_hSampleRateChangedEvent);
		CloseHandle(m_hExitIdleThread);
		CloseHandle(m_hDeviceInitialized);
	}
	catch (...)
	{
		//destructors should absorb exceptions, no harm in logging though!!
		DEBUG_MSG ("Exception during destructor");
	}
}


WTErr WCMRPortAudioDevice::UpdateDeviceInfo ()
{
	std::cout << "API::Device (ID:)" << m_DeviceID << " Updating device info" << std::endl;
	
	SignalObjectAndWait(m_hUpdateDeviceInfoRequestedEvent, m_hUpdateDeviceInfoDone, INFINITE, false);

	return eNoErr;
}


//**********************************************************************************************
// WCMRPortAudioDevice::updateDeviceInfo
//
//! Must be called be device processing thread
//! Updates Device Information about channels, sampling rates, buffer sizes.
//!
//! \return Nothing.
//!
//**********************************************************************************************
void WCMRPortAudioDevice::updateDeviceInfo (bool callerIsWaiting/*=false*/)
{
    AUTO_FUNC_DEBUG;

	//get device info
	const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
	
	//update name.
	m_DeviceName = pDeviceInfo->name;

	//following parameters are needed opening test stream and for sample rates validation
	PaStreamParameters inputParameters, outputParameters;
	PaStreamParameters *pInS = NULL, *pOutS = NULL;

	inputParameters.device = m_DeviceID;
	inputParameters.channelCount = pDeviceInfo->maxInputChannels;
	inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
	inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
	inputParameters.hostApiSpecificStreamInfo = 0;

	if (inputParameters.channelCount)
		pInS = &inputParameters;

	outputParameters.device = m_DeviceID;
	outputParameters.channelCount = pDeviceInfo->maxOutputChannels;
	outputParameters.sampleFormat = paFloat32;
	outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
	outputParameters.hostApiSpecificStreamInfo = 0;

	if (outputParameters.channelCount)
		pOutS = &outputParameters;

	////////////////////////////////////////////////////////////////////////////////////
	//update list of supported SRs...
	m_SamplingRates.clear();
		
	// now iterate through our standard SRs and check if they are supported by device
	// store them for this device
	for(int sr=0; gAllSampleRates[sr] > 0; sr++)
	{
		PaError err = Pa_IsFormatSupported(pInS, pOutS, gAllSampleRates[sr]);
		if( err == paFormatIsSupported)
		{
			m_SamplingRates.push_back ((int)gAllSampleRates[sr]);
		}
	}

	///////////////////////////////////////////////////////////////////////////////////
	//update buffer sizes
	m_BufferSizes.clear();
	bool useDefaultBuffers = true;

	// In ASIO Windows, the buffer size is set from the sound device manufacturer's control panel
	long minSize, maxSize, preferredSize, granularity;
	PaError err = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);
	
	if (err == paNoError)
	{
		std::cout << "API::Device " << m_DeviceName << " Buffers: " << minSize << " " << maxSize << " " << preferredSize << std::endl;
			
		m_BufferSizes.push_back (preferredSize);
		useDefaultBuffers = false;
	}
	else
	{
		std::cout << "API::Device" << m_DeviceName << " Preffered buffer size is not supported" << std::endl;
	}
	
	if (useDefaultBuffers)
	{
		std::cout << "API::Device" << m_DeviceName << " Using default buffer sizes " <<std::endl;
		for(int bsize=0; bsize < (sizeof(gAllBufferSizes)/sizeof(gAllBufferSizes[0])); bsize++)
			m_BufferSizes.push_back (gAllBufferSizes[bsize]);
	}

	/////////////////////////////////////////////////////////////////////////////////////////
	//update channels info
	{
		int maxInputChannels = pDeviceInfo->maxInputChannels;
		int maxOutputChannels = pDeviceInfo->maxOutputChannels;

		//Update input channels
		m_InputChannels.clear();
		for (int channel = 0; channel < maxInputChannels; channel++)
		{
			const char* channelName[32]; // 32 is max leth declared by PortAudio for this operation
			std::stringstream chNameStream;

			PaError error = PaAsio_GetInputChannelName(m_DeviceID, channel, channelName);

			chNameStream << (channel+1) << " - ";

			if (error == paNoError)
			{
				chNameStream << *channelName;
			}
			else
			{
				chNameStream << "Input " << (channel+1);
			}

			m_InputChannels.push_back (chNameStream.str());
		}
	
	
		//Update output channels
		m_OutputChannels.clear();
		for (int channel = 0; channel < maxOutputChannels; channel++)
		{
			const char* channelName[32]; // 32 is max leth declared by PortAudio for this operation
			std::stringstream chNameStream;
			
			PaError error = PaAsio_GetOutputChannelName(m_DeviceID, channel, channelName);
			
			chNameStream << (channel+1) << " - ";

			if (error == paNoError)
			{
				chNameStream << *channelName;
			}
			else
			{
				chNameStream << "Output " << (channel+1);
			}
			
			m_OutputChannels.push_back (chNameStream.str());
		}
	}

	std::cout << "API::Device" << m_DeviceName << " Device info update has been finished" << std::endl;

	if (callerIsWaiting)
		SetEvent(m_hUpdateDeviceInfoDone);
}


PaError WCMRPortAudioDevice::testStateValidness(int sampleRate, int bufferSize)
{
	PaError paErr = paNoError;

	//get device info
	const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);

	//following parameters are needed opening test stream and for sample rates validation
	PaStreamParameters inputParameters, outputParameters;
	PaStreamParameters *pInS = NULL, *pOutS = NULL;

	inputParameters.device = m_DeviceID;
	inputParameters.channelCount = pDeviceInfo->maxInputChannels;
	inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
	inputParameters.suggestedLatency = 0;
	inputParameters.hostApiSpecificStreamInfo = 0;

	if (inputParameters.channelCount)
		pInS = &inputParameters;

	outputParameters.device = m_DeviceID;
	outputParameters.channelCount = pDeviceInfo->maxOutputChannels;
	outputParameters.sampleFormat = paFloat32;
	outputParameters.suggestedLatency = 0;
	outputParameters.hostApiSpecificStreamInfo = 0;

	if (outputParameters.channelCount)
		pOutS = &outputParameters;

	PaStream *portAudioStream = NULL;
		
	//sometimes devices change buffer size if sample rate changes
	//it updates buffer size during stream opening
	//we need to find out how device would behave with current sample rate
	//try opening test stream to load device driver for current sample rate and buffer size
	paErr = Pa_OpenStream (&portAudioStream, pInS, pOutS, sampleRate, bufferSize, paDitherOff, NULL, NULL);
	
	if (portAudioStream)
	{
		// close test stream
		Pa_CloseStream (portAudioStream);
		portAudioStream = NULL;
	}

	return paErr;
}


//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::CurrentSamplingRate ()
{
    AUTO_FUNC_DEBUG;
	//ToDo: Perhaps for ASIO devices that are active, we should retrive the SR from the device...
	
	return (m_CurrentSamplingRate);
}


WTErr WCMRPortAudioDevice::SetActive (bool newState)
{
	if (newState == true)
	{
		std::cout << "API::Device " << m_DeviceName << " Activation requested" << std::endl;
		SignalObjectAndWait(m_hActivateRequestedEvent, m_hActivationDone, INFINITE, false);
	}
	else
	{
		std::cout << "API::Device " << m_DeviceName << " Deactivation requested" << std::endl;
		SignalObjectAndWait(m_hDeActivateRequestedEvent, m_hDeActivationDone, INFINITE, false);
	}

	if (newState == Active() )
		return eNoErr;
	else
		return eGenericErr;
}


WTErr WCMRPortAudioDevice::SetStreaming (bool newState)
{
	if (newState == true)
	{
		std::cout << "API::Device " << m_DeviceName << " Stream start requested" << std::endl;
		SignalObjectAndWait(m_hStartStreamingRequestedEvent, m_hStartStreamingDone, INFINITE, false);
	}
	else
	{
		std::cout << "API::Device " << m_DeviceName << " Stream stop requested" << std::endl;
		SignalObjectAndWait(m_hStopStreamingRequestedEvent, m_hStopStreamingDone, INFINITE, false);
	}

	if (newState == Streaming() )
		return eNoErr;
	else
		return eGenericErr;
}


WTErr WCMRPortAudioDevice::ResetDevice()
{
	std::cout << "API::Device: " << m_DeviceName << " Reseting device" << std::endl;
	
	SignalObjectAndWait(m_hResetRequestedEvent, m_hResetDone, INFINITE, false);

	if (ConnectionStatus() == DeviceErrors)
	{
		return m_lastErr;
	}

	return eNoErr;
}


//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::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)
		return (retVal);

	//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;
		return (retVal);
	}
	
	if (Streaming())
	{
		//Can't change, perhaps use an "in use" type of error
		retVal = eGenericErr;
		return (retVal);
	}
	
	//make the change...
	m_CurrentSamplingRate = newRate;
	PaError paErr = PaAsio_SetStreamSampleRate (m_PortAudioStream, m_CurrentSamplingRate);
	Pa_Sleep(PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS); // sleep some time to make sure the change has place

	if (paErr != paNoError)
	{
		std::cout << "Sample rate change failed: " <<  Pa_GetErrorText (paErr) << std::endl;
		if (paErr ==  paUnanticipatedHostError)
			std::cout << "Details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl;

		retVal = eWrongObjectState;
	}
	
	return (retVal);
}


//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::CurrentBufferSize ()
{
	return m_CurrentBufferSize;
}


//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::SetCurrentBufferSize (int newSize)
{
    AUTO_FUNC_DEBUG;
	WTErr retVal = eNoErr;
	std::vector<int>::iterator intIter;

	if (Streaming())
	{
		//Can't change, perhaps use an "in use" type of error
		retVal = eGenericErr;
		return (retVal);
	}

	// Buffer size for ASIO devices can be changed from the control panel only
	// We have driver driven logi here
	if (m_CurrentBufferSize != newSize )
	{
		// we have only one aloved buffer size which is preffered by PA
		// this is the only value which could be set
		newSize = m_BufferSizes[0];
		int bufferSize = newSize;
		// notify client to update buffer size
		m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&bufferSize);
		return retVal;
	}

	return (retVal);
}


//**********************************************************************************************
// WCMRPortAudioDevice::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.
//!
//**********************************************************************************************
WCMRPortAudioDevice::ConnectionStates WCMRPortAudioDevice::ConnectionStatus ()
{
    AUTO_FUNC_DEBUG;
	//ToDo: May want to do something more to extract the actual status!
	return (m_ConnectionStatus);
	
}


//**********************************************************************************************
// WCMRPortAudioDevice::activateDevice
//
//!	IS CALLED BY PROCESS THREAD
//! Sets the device into "active" state. Essentially, opens the PA device.
//!		If it's an ASIO device it may result in buffer size change in some cases.
//!
//**********************************************************************************************
void WCMRPortAudioDevice::activateDevice (bool callerIsWaiting/*=false*/)
{
	AUTO_FUNC_DEBUG;

	PaError paErr = paNoError;
	
	// if device is not active activate it
	if (!Active() )
	{
		PaStreamParameters inputParameters, outputParameters;
		PaStreamParameters *pInS = NULL, *pOutS = NULL;

		const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
		const PaHostApiInfo *pHostApiInfo = Pa_GetHostApiInfo(pDeviceInfo->hostApi);

		inputParameters.device = m_DeviceID;
		inputParameters.channelCount = (int)m_InputChannels.size();
		inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
		inputParameters.suggestedLatency = Pa_GetDeviceInfo(m_DeviceID)->defaultLowInputLatency;
		inputParameters.hostApiSpecificStreamInfo = 0;

		if (inputParameters.channelCount)
			pInS = &inputParameters;

		outputParameters.device = m_DeviceID;
		outputParameters.channelCount = (int)m_OutputChannels.size();
		outputParameters.sampleFormat = paFloat32;
		outputParameters.suggestedLatency = Pa_GetDeviceInfo(m_DeviceID)->defaultLowOutputLatency;
		outputParameters.hostApiSpecificStreamInfo = 0;

		if (outputParameters.channelCount)
			pOutS = &outputParameters;

		std::cout << "API::Device " << m_DeviceName << " Opening device stream " << std::endl;
		std::cout << "Sample rate: " << m_CurrentSamplingRate << " buffer size: " << m_CurrentBufferSize << std::endl;
		paErr = Pa_OpenStream(&m_PortAudioStream,
								pInS,
								pOutS,
								m_CurrentSamplingRate,
								m_CurrentBufferSize,
								paDitherOff,
								WCMRPortAudioDevice::TheCallback,
								this);
			
		if(paErr != paNoError)
		{
			std::cout << "Cannot open streamm with buffer: "<< m_CurrentBufferSize << " Error: " << Pa_GetErrorText (paErr) << std::endl;
			
			if (paErr ==  paUnanticipatedHostError)
				std::cout << "Error details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl;
		}

		if(paErr == paNoError)
		{
			std::cout << "Stream has been opened! "<< std::endl;

			// check for possible changes
			long minSize, maxSize, preferredSize, granularity;
			PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);

			std::cout << "Checked if buffer size changed "<< std::endl;
			if (paErr == paNoError && m_CurrentBufferSize != preferredSize)
			{
				std::cout << "Buffer size has changed "<< std::endl;
				m_CurrentBufferSize = preferredSize;
				m_BufferSizes.clear();
				m_BufferSizes.push_back(preferredSize);
				m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&preferredSize);
			}

			m_DropsDetected = 0;
			m_DropsReported = 0;
			m_IgnoreThisDrop = true;

			if (pHostApiInfo->type == paASIO)
			{
				m_BufferSizeChangeRequested = 0;
				m_BufferSizeChangeReported = 0;
				m_ResetRequested = 0;
				m_ResetReported = 0;
				m_ResyncRequested = 0;
				m_ResyncReported = 0;
				std::cout << "Installing new mesage hook "<< std::endl;
				PaAsio_SetMessageHook (StaticASIOMessageHook, this);
			}
			m_IsActive = true;
			m_ConnectionStatus = DeviceAvailable;
			m_lastErr = eNoErr;
		}
		else
		{
			//failed, do not update device state
			std::cout << "Failed to open pa stream: " <<  Pa_GetErrorText (paErr) << std::endl;
			DEBUG_MSG( "Failed to open pa stream: " << Pa_GetErrorText (paErr) );
			m_ConnectionStatus = DeviceErrors;
			m_lastErr = eAsioFailed;
		}

	
	}

	std::cout << "Activation is DONE "<< std::endl;

	if (callerIsWaiting)
		SetEvent(m_hActivationDone);
}


//**********************************************************************************************
// WCMRPortAudioDevice::deactivateDevice
//
//!	IS CALLED BY PROCESS THREAD
//! Sets the device into "inactive" state. Essentially, closes the PA device.
//!
//**********************************************************************************************
void WCMRPortAudioDevice::deactivateDevice (bool callerIsWaiting/*=false*/)
{
    AUTO_FUNC_DEBUG;

	PaError paErr = paNoError;
	
	if (Active() )
	{
		if (Streaming())
		{
			stopStreaming ();
		}
		
		if (m_PortAudioStream)
		{
			//close the stream first
			std::cout << "API::Device" << m_DeviceName << " Closing device stream" << std::endl;
			paErr = Pa_CloseStream (m_PortAudioStream);
			if(paErr == paNoError)
			{
				m_PortAudioStream = NULL;
				m_DropsDetected = 0;
				m_DropsReported = 0;
				m_IgnoreThisDrop = true;
				m_BufferSizeChangeRequested = 0;
				m_BufferSizeChangeReported = 0;
				m_ResetRequested = 0;
				m_ResetReported = 0;
				m_ResyncRequested = 0;
				m_ResyncReported = 0;
				PaAsio_SetMessageHook (NULL, NULL);

				//finaly set device state to "not active"
				m_IsActive = false;
				m_ConnectionStatus = DeviceDisconnected;
				m_lastErr = eNoErr;
			}
			else
			{
				//failed, do not update device state
				std::cout << "Failed to close pa stream stream " <<  Pa_GetErrorText (paErr) << std::endl;
				DEBUG_MSG( "Failed to open pa stream stream " << Pa_GetErrorText (paErr) );
				m_ConnectionStatus = DeviceErrors;
				m_lastErr = eAsioFailed;
			}
		}
	}

	if (callerIsWaiting)
		SetEvent(m_hDeActivationDone);
}


//**********************************************************************************************
// WCMRPortAudioDevice::startStreaming
//
//! Sets the devices into "streaming" state. Calls PA's Start stream routines.
//! This roughly corresponds to calling Start on the lower level interface.
//!
//**********************************************************************************************
void WCMRPortAudioDevice::startStreaming (bool callerIsWaiting/*=false*/)
{
    AUTO_FUNC_DEBUG;

	// proceed if the device is not streaming
	if (!Streaming () )
	{
		PaError paErr = paNoError;
		m_StopRequested = false;
		m_SampleCounter = 0;

		std::cout << "API::Device" << m_DeviceName << " Starting device stream" << std::endl;
		
		//get device info
		const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
	
		unsigned int inChannelCount = pDeviceInfo->maxInputChannels;
		unsigned int outChannelCount = pDeviceInfo->maxOutputChannels;
		
		// Prepare for streaming - tell Engine to do the initialization for process callback
		m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStartsStreaming);

		paErr = Pa_StartStream( m_PortAudioStream );

		if(paErr == paNoError)
		{
			// if the stream was started successfully
			m_IsStreaming = true;
			std::cout << "API::Device" << m_DeviceName << " Device is streaming" << std::endl;
		}
		else
		{
			std::cout << "Failed to start PA stream: " <<  Pa_GetErrorText (paErr) << std::endl;
			DEBUG_MSG( "Failed to start PA stream: " << Pa_GetErrorText (paErr) );
			m_lastErr = eGenericErr;
		}
	}
		
	if (callerIsWaiting)
		SetEvent(m_hStartStreamingDone);
}


//**********************************************************************************************
// WCMRPortAudioDevice::stopStreaming
//
//! Sets the devices into "not streaming" state. Calls PA's Stop stream routines.
//! This roughly corresponds to calling Stop on the lower level interface.
//!
//**********************************************************************************************
void WCMRPortAudioDevice::stopStreaming (bool callerIsWaiting/*=false*/)
{
    AUTO_FUNC_DEBUG;

	// proceed if the device is streaming
	if (Streaming () )
	{
		PaError paErr = paNoError;
		m_StopRequested = true;

		std::cout << "API::Device " << m_DeviceName << " Stopping device stream" << std::endl;
		paErr = Pa_StopStream( m_PortAudioStream );

		if(paErr == paNoError || paErr == paStreamIsStopped)
		{
			// if the stream was stopped successfully
			m_IsStreaming = false;
			m_pInputData = NULL;
		}
		else
		{
			std::cout << "Failed to stop PA stream normaly! Error:" <<  Pa_GetErrorText (paErr) << std::endl;
			DEBUG_MSG( "Failed to stop PA stream normaly! Error:" << Pa_GetErrorText (paErr) );
			m_lastErr = eGenericErr;
		}
	}

	if (callerIsWaiting)
		SetEvent(m_hStopStreamingDone);
}


//**********************************************************************************************
// WCMRPortAudioDevice::resetDevice
//
//! Resets the device, updates device info. Importnat: does PA reinitialization calling
//! Pa_terminate/Pa_initialize functions.
//!
//! \param none
//!
//! \return nothing
//!
//**********************************************************************************************
void WCMRPortAudioDevice::resetDevice (bool callerIsWaiting /*=false*/ )
{
	PaError paErr = paNoError;

	// Keep device sates
	bool wasStreaming = Streaming();
	bool wasActive = Active();

	// Reset the device
	stopStreaming();
	deactivateDevice();

	// Cache device buffer size as it might be changed during reset
	int oldBufferSize = m_CurrentBufferSize;

	// Now, validate the state and update device info if required
	unsigned int retry = PROPERTY_CHANGE_RETRIES;
	while (retry-- )
	{
		// Reinitialize PA
		Pa_Terminate();
		Pa_Initialize();
			
		std::cout << "Updating device state... " << std::endl;
		// update device info
		updateDeviceInfo();

		// take up buffers
		long minSize, maxSize, preferredSize, granularity;
		PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);

		if (paErr != paNoError)
		{
			continue;
		}
		m_CurrentBufferSize = preferredSize;

		paErr = testStateValidness(m_CurrentSamplingRate, m_CurrentBufferSize);
		if (paNoError ==  paErr)
		{
			std::cout << "Device state is valid" << std::endl;
			break;
		}

		std::cout << "Cannot start with current state: sr: " << m_CurrentSamplingRate << " bs:" << m_CurrentBufferSize \
					<< "\nReason: " <<  Pa_GetErrorText (paErr) << std::endl;
		if (paErr ==  paUnanticipatedHostError)
			std::cout << "Details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl;

		std::cout << "Will try again in " << DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS << "msec" << std::endl;

		Pa_Sleep(DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS);
	}

	if (paErr == paNoError)
	{
		// Notify the Application about device setting changes
		if (oldBufferSize != m_CurrentBufferSize)
		{
			std::cout << "API::Device" << m_DeviceName << " buffer size changed" << std::endl;
			int bufferSize = m_CurrentBufferSize;
			m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&bufferSize);
		}

		// Activate the device if it was active before
		if (wasActive)
			activateDevice();

		// Resume streaming if the device was streaming before
		if(wasStreaming && m_lastErr == eNoErr && m_ConnectionStatus == DeviceAvailable)
		{
			// start streaming
			startStreaming();
		}
	} else {
		m_ConnectionStatus = DeviceErrors;
		m_lastErr = eWrongObjectState;
	}

	if (callerIsWaiting)
		SetEvent(m_hResetDone);
}


#ifdef PLATFORM_WINDOWS

long WCMRPortAudioDevice::StaticASIOMessageHook (void *pRefCon, long selector, long value, void* message, double* opt)
{
	if (pRefCon)
	{
		return ((WCMRPortAudioDevice*)(pRefCon))->ASIOMessageHook (selector, value, message, opt);
	}
	else
		return -1;
}

long WCMRPortAudioDevice::ASIOMessageHook (long selector, long WCUNUSEDPARAM(value), void* WCUNUSEDPARAM(message), double* WCUNUSEDPARAM(opt))
{
	switch(selector)
	{
		case kAsioResyncRequest:
			m_ResyncRequested++;
			std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioResyncRequest" << std::endl;
			break;

		case kAsioLatenciesChanged:
			m_BufferSizeChangeRequested++;
			std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioLatenciesChanged" << std::endl;
			if (m_ResetRequested == 0) {
				m_ResetRequested++;
				m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
			}
			break;

		case kAsioBufferSizeChange:
			m_BufferSizeChangeRequested++;
			std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- m_BufferSizeChangeRequested" << std::endl;
			if (m_ResetRequested == 0) {
				m_ResetRequested++;
				m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
			}
			break;

		case kAsioResetRequest:
			std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioResetRequest" << std::endl;
			m_ResetRequested++;
			m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
			break;

        case kAsioOverload:
			m_DropsDetected++;
			std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioOverload" << std::endl;
			m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::Dropout);
            break;
	}
	return 0;
}

#endif


//**********************************************************************************************
// WCMRPortAudioDevice::DoIdle
//
//! A place for doing idle time processing. The other derived classes will probably do something
//!		meaningful.
//!
//! \param none
//!
//! \return eNoErr always.
//!
//**********************************************************************************************
WTErr WCMRPortAudioDevice::DoIdle ()
{
	WTErr retVal = eNoErr;

	std::cout << "WCMRPortAudioDevice::DoIdle ()" << std::endl;
	HANDLE hEvents[] =
	{
		m_hUpdateDeviceInfoRequestedEvent,
		m_hActivateRequestedEvent,
		m_hDeActivateRequestedEvent,
		m_hStartStreamingRequestedEvent,
		m_hStopStreamingRequestedEvent,
		m_hBufferSizeChangedEvent,
		m_hSampleRateChangedEvent,
		m_hResetRequestedEvent,
		m_hResetFromDevRequestedEvent,
		m_hExitIdleThread
	};

	const size_t hEventsSize = sizeof(hEvents)/sizeof(hEvents[0]);
	
	initDevice();

	for(;;)
	{
		DWORD result = WaitForMultipleObjects (hEventsSize, hEvents, FALSE, INFINITE);
		result = result - WAIT_OBJECT_0;

		if ((result < 0) || (result >= hEventsSize)) {
			std::cout << "\t\t\t\t\t\t\tWCMRPortAudioDevice::DoIdle () -> (result < 0) || (result >= hEventsSize):" << result << std::endl;
			retVal = eGenericErr;
			break;
		}

		if (hEvents[result] == m_hExitIdleThread) {
			std::cout << "\t\t\t\t\t\t\tWCMRPortAudioDevice::DoIdle () -> m_hExitIdleThread" << result << std::endl;
			retVal = eNoErr;
			break;
		}

		if (hEvents[result] == m_hUpdateDeviceInfoRequestedEvent) {
			std::cout << "\t\t\t\t\t\tupdate requested ..." << std::endl;
			updateDeviceInfo(true);
		}

		if (hEvents[result] == m_hActivateRequestedEvent) {
			std::cout << "\t\t\t\t\t\tactivation requested ..." << std::endl;
			activateDevice(true);
		}

		if (hEvents[result] == m_hDeActivateRequestedEvent) {
			std::cout << "\t\t\t\t\t\tdeactivation requested ..." << std::endl;
			deactivateDevice(true);
		}

		if (hEvents[result] == m_hStartStreamingRequestedEvent) {
			std::cout << "\t\t\t\t\t\tStart stream requested ..." << std::endl;
			startStreaming(true);
		}

		if (hEvents[result] == m_hStopStreamingRequestedEvent) {
			std::cout << "\t\t\t\t\t\tStop stream requested ..." << std::endl;
			stopStreaming(true);
		}

		if (hEvents[result] == m_hResetRequestedEvent) {
			std::cout << "\t\t\t\t\t\treset requested ..." << std::endl;
			resetDevice(true);
		}

		if (hEvents[result] == m_hResetFromDevRequestedEvent) {
			std::cout << "\t\t\t\t\t\treset requested from device..." << std::endl;
			resetDevice();
		}

		if (hEvents[result] == m_hBufferSizeChangedEvent) {
			std::cout << "\t\t\t\t\t\tbuffer size changed from device..." << std::endl;
			m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged);
		}

		if (hEvents[result] == m_hSampleRateChangedEvent) {
			std::cout << "\t\t\t\t\t\tsample rate changed from device..." << std::endl;
			m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged);
		}
	}

	terminateDevice();

	return retVal;
}


//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::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);
}



//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::SetMonitorGain (float newGain)
{
    AUTO_FUNC_DEBUG;
	//This will most likely be overridden, the base class simply
	//changes the member.
	
	m_MonitorGain = newGain;
	return (eNoErr);
}




//**********************************************************************************************
// WCMRPortAudioDevice::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 WCMRPortAudioDevice::ShowConfigPanel (void *pParam)
{
    AUTO_FUNC_DEBUG;
	WTErr retVal = eNoErr;
	
	if (Active() && !m_ResetRequested )
	{
#ifdef PLATFORM_WINDOWS
		if(Pa_GetHostApiInfo(Pa_GetDeviceInfo(m_DeviceID)->hostApi)->type == paASIO)
		{
			// stop and deactivate the device
			bool wasStreaming = Streaming();
			SetActive(false);

			// show control panel for the device
			if (PaAsio_ShowControlPanel (m_DeviceID, pParam) != paNoError)
				retVal = eGenericErr;
			
			// restore previous state for the device
			SetActive(true);
			if (wasStreaming)
				SetStreaming(true);


			// reset device to pick up changes
			if (!m_ResetRequested) {
				m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
			}
		}
#else
	pParam = pParam;
#endif //_windows		
	}
	
	return (retVal);
}


//*****************************************************************************************************
// WCMRPortAudioDevice::TheCallback
//
//! The (static) Port Audio Callback function. This is a static member. It calls on the AudioCallback in the
//!		WCMRPortAudioDevice to do the real work.
//!
//! \param pInputBuffer: pointer to input buffer.
//! \param pOutputBuffer: pointer to output buffer.
//! \param framesPerBuffer: number of sample frames per buffer.
//! \param pTimeInfo: time info for PaStream callback.
//! \param statusFlags:
//! \param pUserData: pointer to user data, in our case the WCMRPortAudioDevice object.
//!
//! \return true to stop streaming else returns false.
//******************************************************************************************************
int WCMRPortAudioDevice::TheCallback (const void *pInputBuffer, void *pOutputBuffer, unsigned long framesPerBuffer,
	const PaStreamCallbackTimeInfo* /*pTimeInfo*/, PaStreamCallbackFlags statusFlags, void *pUserData )
{
	WCMRPortAudioDevice *pMyDevice = (WCMRPortAudioDevice *)pUserData;
	if (pMyDevice)
		return pMyDevice->AudioCallback ((float *)pInputBuffer, (float *)pOutputBuffer, framesPerBuffer,
			(statusFlags & (paInputOverflow | paOutputUnderflow)) != 0);
	else
		return (true);
			
}



//**********************************************************************************************
// WCMRPortAudioDevice::AudoiCallback
//
//! 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 *pInputBuffer : Points to a buffer with recorded data.
//! \param *pOutputBuffer : Points to a buffer to receive playback data.
//! \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.
//!	\param dropsDetected : True if dropouts were detected in input or output. Can be used to signal the GUI.
//!
//! \return true
//!
//**********************************************************************************************
int WCMRPortAudioDevice::AudioCallback( const float *pInputBuffer, float *pOutputBuffer, unsigned long framesPerBuffer, bool dropsDetected )
{
	UMicroseconds theStartTime;

    // detect drops
	if (dropsDetected)
	{
		if (m_IgnoreThisDrop)
			m_IgnoreThisDrop = false; //We'll ignore once, just once!
		else
			m_DropsDetected++;
	}

	m_pInputData = pInputBuffer;

    // VKamyshniy: Is this a right place to call the client???:
    struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData =
    {
        m_pInputData,
        pOutputBuffer,
        framesPerBuffer,
		m_SampleCounter,
		theStartTime.MicroSeconds()*1000
    };

    m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData );

	//Don't try to 	access after this call returns!
	m_pInputData = NULL;

	m_SampleCounter += framesPerBuffer;	

	return m_StopRequested;
}




//**********************************************************************************************
// WCMRPortAudioDeviceManager::WCMRPortAudioDeviceManager
//
//! The constructuor, we initialize PA, and build the device list.
//!
//! \param *pTheClient : The manager's client object (which receives notifications).
//! \param interfaceType : The PortAudio interface type to use for this manager - acts as a filter.
//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true.
//!
//! \return Nothing.
//!
//**********************************************************************************************
WCMRPortAudioDeviceManager::WCMRPortAudioDeviceManager (WCMRAudioDeviceManagerClient *pTheClient,
														eAudioDeviceFilter eCurAudioDeviceFilter, bool useMultithreading, bool bNocopy)
	: WCMRAudioDeviceManager (pTheClient, eCurAudioDeviceFilter)
	, m_NoneDevice(0)
	, m_UseMultithreading(useMultithreading)
	, m_bNoCopyAudioBuffer(bNocopy)
{
    AUTO_FUNC_DEBUG;
	std::cout << "API::PortAudioDeviceManager::PA Device manager constructor" << std::endl;
	
	//Always create the None device first...
	m_NoneDevice = new WCMRNativeAudioNoneDevice(this);

	WTErr err = generateDeviceListImpl();

	if (eNoErr != err)
		throw err;

	timeBeginPeriod (1);
}


//**********************************************************************************************
// WCMRPortAudioDeviceManager::~WCMRPortAudioDeviceManager
//
//! It clears the device list, releasing each of the device.
//!
//! \param none
//!
//! \return Nothing.
//!
//**********************************************************************************************
WCMRPortAudioDeviceManager::~WCMRPortAudioDeviceManager()
{
    AUTO_FUNC_DEBUG;
	
	std::cout << "API::Destroying PortAudioDeviceManager " << std::endl;

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

	timeEndPeriod (1);
}


WCMRAudioDevice* WCMRPortAudioDeviceManager::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 WCMRPortAudioDevice (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 WCMRPortAudioDeviceManager::destroyCurrentDeviceImpl()
{
	if (m_CurrentDevice != m_NoneDevice)
		delete m_CurrentDevice;

	m_CurrentDevice = 0;
}


WTErr WCMRPortAudioDeviceManager::getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates)
{
	WTErr retVal = eNoErr;

	sampleRates.clear();
	const PaDeviceInfo *pPaDeviceInfo = Pa_GetDeviceInfo(deviceId);

	//now find supported sample rates
	//following parameters are needed for sample rates validation
	PaStreamParameters inputParameters, outputParameters;
	PaStreamParameters *pInS = NULL, *pOutS = NULL;

	inputParameters.device = deviceId;
	inputParameters.channelCount = std::min<int>(2, pPaDeviceInfo->maxInputChannels);
	inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
	inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
	inputParameters.hostApiSpecificStreamInfo = 0;

	if (inputParameters.channelCount)
		pInS = &inputParameters;

	outputParameters.device = deviceId;
	outputParameters.channelCount = std::min<int>(2, pPaDeviceInfo->maxOutputChannels);
	outputParameters.sampleFormat = paFloat32;
	outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
	outputParameters.hostApiSpecificStreamInfo = 0;

	if (outputParameters.channelCount)
		pOutS = &outputParameters;

	for(int sr=0; gAllSampleRates[sr] > 0; sr++)
	{
		if( paFormatIsSupported == Pa_IsFormatSupported(pInS, pOutS, gAllSampleRates[sr]) )
		{
			sampleRates.push_back ((int)gAllSampleRates[sr]);
		}
	}

	return retVal;
}


WTErr WCMRPortAudioDeviceManager::getDeviceAvailableBufferSizes(DeviceID deviceId, std::vector<int>& buffers)
{
	WTErr retVal = eNoErr;
	
	buffers.clear();

	//make PA request to get actual device buffer sizes
	long minSize, maxSize, preferredSize, granularity;

	PaError paErr = PaAsio_GetAvailableBufferSizes(deviceId, &minSize, &maxSize, &preferredSize, &granularity);

	//for Windows ASIO devices we always use prefferes buffer size ONLY
	if (paNoError == paErr )
	{
		buffers.push_back(preferredSize);
	}
	else
	{
		retVal = eAsioFailed;
		std::cout << "API::PortAudioDeviceManager::GetBufferSizes: error: " <<  Pa_GetErrorText (paErr) << " getting buffer sizes for device: "<< deviceId << std::endl;
	}

	return retVal;
}


WTErr WCMRPortAudioDeviceManager::generateDeviceListImpl()
{
	std::cout << "API::PortAudioDeviceManager::Generating device list" << std::endl;
	
	WTErr retVal = eNoErr;

	//Initialize PortAudio and ASIO first
	PaError paErr = Pa_Initialize();

	if (paErr != paNoError)
	{
		//ToDo: throw an exception here!
		retVal = eSomeThingNotInitailzed;
		return retVal;
	}

	// lock DeviceInfoVec firts
	wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex);

	if (m_NoneDevice)
	{
		DeviceInfo *pDevInfo = new DeviceInfo(NONE_DEVICE_ID, m_NoneDevice->DeviceName() );
		pDevInfo->m_AvailableSampleRates = m_NoneDevice->SamplingRates();
		m_DeviceInfoVec.push_back(pDevInfo);
	}

	//Get device count...
	int numDevices = Pa_GetDeviceCount();

	//for each device,
	for (int thisDeviceID = 0; thisDeviceID < numDevices; thisDeviceID++)
	{
		//if it's of the required type...
		const PaDeviceInfo *pPaDeviceInfo = Pa_GetDeviceInfo(thisDeviceID);
		
		if (Pa_GetHostApiInfo(pPaDeviceInfo->hostApi)->type == paASIO)
		{
			//build a device object...
			try
			{
				std::cout << "API::PortAudioDeviceManager::DeviceID: " << thisDeviceID << ", Device Name: " << pPaDeviceInfo->name << std::endl;
				TRACE_MSG ("PA DeviceID: " << thisDeviceID << ", Device Name: " << pPaDeviceInfo->name);

				DeviceInfo *pDevInfo = new DeviceInfo(thisDeviceID, pPaDeviceInfo->name);
				if (pDevInfo)
				{
					//Get available sample rates
					std::vector<int> availableSampleRates;
					WTErr wErr = WCMRPortAudioDeviceManager::getDeviceAvailableSampleRates(thisDeviceID, 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;
					pDevInfo->m_MaxInputChannels = pPaDeviceInfo->maxInputChannels;
					pDevInfo->m_MaxOutputChannels = pPaDeviceInfo->maxOutputChannels;

					//Get available buffer sizes
					std::vector<int> availableBuffers;
					wErr = getDeviceAvailableBufferSizes(thisDeviceID, availableBuffers);

					if (wErr != eNoErr)
					{
						DEBUG_MSG ("Failed to get device available buffer sizes. Device ID: " << m_DeviceID);
						delete pDevInfo;
						continue; //proceed to the next device
					}

					pDevInfo->m_AvailableBufferSizes = availableBuffers;

					//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)
					{
						TRACE_MSG ("API::PortAudioDeviceManager::Device " << pDevInfo->m_DeviceName << "Rejected. \
									In Channels = " << pDevInfo->m_MaxInputChannels << "Out Channels = " <<pDevInfo->m_MaxOutputChannels );
						delete pDevInfo;
					}
				}
			}
			catch (...)
			{
				std::cout << "API::PortAudioDeviceManager::Unabled to create PA Device: " << std::endl;
				DEBUG_MSG ("Unabled to create PA Device: " << thisDeviceID);
			}
		}
	}

	//If no devices were found, that's not a good thing!
	if (m_DeviceInfoVec.empty() )
	{
		std::cout << "API::PortAudioDeviceManager::No matching PortAudio devices were found, total PA devices = " << numDevices << std::endl;
		DEBUG_MSG ("No matching PortAudio devices were found, total PA devices = " << numDevices);
	}

	//we don't need PA initialized right now
	Pa_Terminate();

	return retVal;
}


WTErr WCMRPortAudioDeviceManager::getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const
{
    sampleRates.clear ();

    WTErr retVal = eNoErr;

	if (m_CurrentDevice && deviceName == m_CurrentDevice->DeviceName() )
	{
		sampleRates=m_CurrentDevice->SamplingRates();
		return retVal;
	}

    DeviceInfo devInfo;
	retVal = GetDeviceInfoByName(deviceName, devInfo);

	if (eNoErr == retVal)
	{
		sampleRates=devInfo.m_AvailableSampleRates;
	}
	else
	{
		std::cout << "API::PortAudioDeviceManager::GetSampleRates: Device not found: "<< deviceName << std::endl;
	}

	return retVal;
}


WTErr WCMRPortAudioDeviceManager::getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& buffers) const
{
	WTErr retVal = eNoErr;
	
	buffers.clear();

	//first check if the request has been made for None device
	if (deviceName == m_NoneDevice->DeviceName() )
	{
		buffers=m_NoneDevice->BufferSizes();
		return retVal;
	}
	
	if (m_CurrentDevice && deviceName == m_CurrentDevice->DeviceName() )
	{
		buffers=m_CurrentDevice->BufferSizes();
		return retVal;
	}

	DeviceInfo devInfo;
	retVal = GetDeviceInfoByName(deviceName, devInfo);

	if (eNoErr == retVal)
	{
		std::cout << "API::PortAudioDeviceManager::GetBufferSizes: got buffer :"<< devInfo.m_AvailableBufferSizes.front() << std::endl;
		buffers = devInfo.m_AvailableBufferSizes;
	}
	else
	{
		std::cout << "API::PortAudioDeviceManager::GetBufferSizes: Device not found: "<< deviceName << std::endl;
	}

	return retVal;
}