1 //----------------------------------------------------------------------------------
3 // Copyright (c) 2008 Waves Audio Ltd. All rights reserved.
5 //! \file WCMRPortAudioDeviceManager.cpp
7 //! WCMRPortAudioDeviceManager and related class declarations
9 //---------------------------------------------------------------------------------*/
10 #include "WCMRPortAudioDeviceManager.h"
11 #include "MiscUtils/safe_delete.h"
12 #include "UMicroseconds.h"
18 #include "IncludeWindows.h"
23 #define PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS 200
24 #define DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS 500
25 #define PROPERTY_CHANGE_TIMEOUT_SECONDS 2
26 #define PROPERTY_CHANGE_RETRIES 3
28 ///< Supported Sample rates
29 static const double gAllSampleRates[] =
31 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 -1 /* negative terminated list */
36 ///< Default Supported Buffer Sizes.
37 static const int gAllBufferSizes[] =
39 32, 64, 96, 128, 192, 256, 512, 1024, 2048
44 static const int DEFAULT_SR = 44100;
45 ///< The default buffer size.
46 static const int DEFAULT_BUFFERSIZE = 128;
48 static const int NONE_DEVICE_ID = -1;
50 ///< Number of stalls to wait before notifying user...
51 static const int NUM_STALLS_FOR_NOTIFICATION = 100; // 100 corresponds to 100 x 42 ms idle timer - about 4 seconds.
52 static const int CHANGE_CHECK_COUNTER_PERIOD = 100; // 120 corresponds to 120 x 42 ms idle timer - about 4 seconds.
54 #define HUNDRED_NANO_TO_MILLI_CONSTANT 10000
55 #define CONSUMPTION_CALCULATION_INTERVAL 500 // Milli Seconds
58 // This wrapper is used to adapt device DoIdle method as entry point for MS thread
59 DWORD WINAPI WCMRPortAudioDevice::__DoIdle__(LPVOID lpThreadParameter)
61 WCMRPortAudioDevice* pDevice = (WCMRPortAudioDevice*)lpThreadParameter;
66 //**********************************************************************************************
67 // WCMRPortAudioDevice::WCMRPortAudioDevice
69 //! Constructor for the audio device. Opens the PA device
70 //! and gets information about the device.
71 //! Starts the thread which will process requests to this device
72 //! such as determining supported sampling rates, buffer sizes, and channel counts.
74 //! \param *pManager : The audio device manager that's managing this device.
75 //! \param deviceID : The port audio device ID.
76 //! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true.
80 //**********************************************************************************************
81 WCMRPortAudioDevice::WCMRPortAudioDevice (WCMRPortAudioDeviceManager *pManager, unsigned int deviceID, bool useMultithreading, bool bNoCopy) :
82 WCMRNativeAudioDevice (pManager, useMultithreading, bNoCopy)
84 , m_BufferSizeChangeRequested (0)
85 , m_BufferSizeChangeReported (0)
86 , m_ResetRequested (0)
88 , m_ResyncRequested (0)
89 , m_ResyncReported (0)
92 , m_IgnoreThisDrop(true)
93 , m_hDeviceProcessingThread(NULL)
94 , m_DeviceProcessingThreadID(0)
95 , m_hUpdateDeviceInfoRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
96 , m_hUpdateDeviceInfoDone(CreateEvent(NULL, FALSE, FALSE, NULL))
97 , m_hActivateRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
98 , m_hActivationDone(CreateEvent(NULL, FALSE, FALSE, NULL))
99 , m_hDeActivateRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
100 , m_hDeActivationDone(CreateEvent(NULL, FALSE, FALSE, NULL))
101 , m_hStartStreamingRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
102 , m_hStartStreamingDone(CreateEvent(NULL, FALSE, FALSE, NULL))
103 , m_hStopStreamingRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
104 , m_hStopStreamingDone(CreateEvent(NULL, FALSE, FALSE, NULL))
105 , m_hResetRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
106 , m_hResetDone(CreateEvent(NULL, FALSE, FALSE, NULL))
107 , m_hResetFromDevRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
108 , m_hBufferSizeChangedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
109 , m_hSampleRateChangedEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
110 , m_hExitIdleThread(CreateEvent(NULL, FALSE, FALSE, NULL))
111 , m_hDeviceInitialized(CreateEvent(NULL, FALSE, FALSE, NULL))
116 //Set initial device info...
117 m_DeviceID = deviceID;
118 m_PortAudioStream = NULL;
119 m_CurrentSamplingRate = DEFAULT_SR;
120 m_CurrentBufferSize = DEFAULT_BUFFERSIZE;
121 m_StopRequested = true;
124 //initialize device processing thread
125 //the divice become alive and now is able to process requests
126 m_hDeviceProcessingThread = CreateThread( NULL, 0, __DoIdle__, (LPVOID)this, 0, &m_DeviceProcessingThreadID );
128 if (!m_hDeviceProcessingThread)
130 DEBUG_MSG("API::Device " << m_DeviceName << " cannot create processing thread");
134 WaitForSingleObject(m_hDeviceInitialized, INFINITE);
136 if (ConnectionStatus() == DeviceErrors)
143 void WCMRPortAudioDevice::initDevice()
145 // Initialize COM for this thread
146 std::cout << "API::Device " << m_DeviceID << " initializing COM" << std::endl;
148 if (S_OK == CoInitialize(NULL) )
155 //should use a valid current SR...
156 if (m_SamplingRates.size())
158 //see if the current sr is present in the sr list, if not, use the first one!
159 std::vector<int>::iterator intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), m_CurrentSamplingRate);
160 if (intIter == m_SamplingRates.end())
162 //not found... use the first one
163 m_CurrentSamplingRate = m_SamplingRates[0];
167 std::cout << "API::Device " << m_DeviceName << " Device does not support any sample rate of ours" << std::endl;
169 //should use a valid current buffer size
170 if (m_BufferSizes.size())
172 //see if the current sr is present in the buffersize list, if not, use the first one!
173 std::vector<int>::iterator intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), m_CurrentBufferSize);
174 if (intIter == m_BufferSizes.end())
176 //not found... use the first one
177 m_CurrentBufferSize = m_BufferSizes[0];
181 //build our input/output level lists
182 for (unsigned int currentChannel = 0; currentChannel < m_InputChannels.size(); currentChannel++)
184 m_InputLevels.push_back (0.0);
187 //build our input/output level lists
188 for (unsigned int currentChannel = 0; currentChannel < m_OutputChannels.size(); currentChannel++)
190 m_OutputLevels.push_back (0.0);
193 std::cout << "API::Device " << m_DeviceName << " Device has been initialized" << std::endl;
194 m_ConnectionStatus = DeviceDisconnected;
199 /*Replace with debug trace*/std::cout << "API::Device " << m_DeviceName << " cannot initialize COM" << std::endl;
200 DEBUG_MSG("Device " << m_DeviceName << " cannot initialize COM");
201 m_ConnectionStatus = DeviceErrors;
202 m_lastErr = eSomeThingNotInitailzed;
203 SetEvent(m_hExitIdleThread);
206 SetEvent(m_hDeviceInitialized);
209 void WCMRPortAudioDevice::terminateDevice()
211 std::cout << "API::Device " << m_DeviceName << " Terminating DEVICE" << std::endl;
213 //If device is streaming, need to stop it!
219 //If device is active (meaning stream is open) we need to close it.
225 std::cout << "API::Device " << m_DeviceName << " Terminating PA" << std::endl;
232 //**********************************************************************************************
233 // WCMRPortAudioDevice::~WCMRPortAudioDevice
235 //! Destructor for the audio device. The base release all the connections that were created, if
236 //! they have not been already destroyed! Here we simply stop streaming, and close device
237 //! handles if necessary.
243 //**********************************************************************************************
244 WCMRPortAudioDevice::~WCMRPortAudioDevice ()
248 std::cout << "API::Destroying Device Instance: " << DeviceName() << std::endl;
251 //Stop deviceprocessing thread
252 SignalObjectAndWait(m_hExitIdleThread, m_hDeviceProcessingThread, INFINITE, false);
254 std::cout << "API::Device " << m_DeviceName << " Processing Thread is stopped" << std::endl;
256 CloseHandle(m_hDeviceProcessingThread);
258 //Now it's safe to free all event handlers
259 CloseHandle(m_hUpdateDeviceInfoRequestedEvent);
260 CloseHandle(m_hUpdateDeviceInfoDone);
261 CloseHandle(m_hActivateRequestedEvent);
262 CloseHandle(m_hActivationDone);
263 CloseHandle(m_hDeActivateRequestedEvent);
264 CloseHandle(m_hDeActivationDone);
265 CloseHandle(m_hStartStreamingRequestedEvent);
266 CloseHandle(m_hStartStreamingDone);
267 CloseHandle(m_hStopStreamingRequestedEvent);
268 CloseHandle(m_hStopStreamingDone);
269 CloseHandle(m_hResetRequestedEvent);
270 CloseHandle(m_hResetDone);
271 CloseHandle(m_hResetFromDevRequestedEvent);
272 CloseHandle(m_hBufferSizeChangedEvent);
273 CloseHandle(m_hSampleRateChangedEvent);
274 CloseHandle(m_hExitIdleThread);
275 CloseHandle(m_hDeviceInitialized);
279 //destructors should absorb exceptions, no harm in logging though!!
280 DEBUG_MSG ("Exception during destructor");
285 WTErr WCMRPortAudioDevice::UpdateDeviceInfo ()
287 std::cout << "API::Device (ID:)" << m_DeviceID << " Updating device info" << std::endl;
289 SignalObjectAndWait(m_hUpdateDeviceInfoRequestedEvent, m_hUpdateDeviceInfoDone, INFINITE, false);
295 //**********************************************************************************************
296 // WCMRPortAudioDevice::updateDeviceInfo
298 //! Must be called be device processing thread
299 //! Updates Device Information about channels, sampling rates, buffer sizes.
303 //**********************************************************************************************
304 void WCMRPortAudioDevice::updateDeviceInfo (bool callerIsWaiting/*=false*/)
309 const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
312 m_DeviceName = pDeviceInfo->name;
314 //following parameters are needed opening test stream and for sample rates validation
315 PaStreamParameters inputParameters, outputParameters;
316 PaStreamParameters *pInS = NULL, *pOutS = NULL;
318 inputParameters.device = m_DeviceID;
319 inputParameters.channelCount = pDeviceInfo->maxInputChannels;
320 inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
321 inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
322 inputParameters.hostApiSpecificStreamInfo = 0;
324 if (inputParameters.channelCount)
325 pInS = &inputParameters;
327 outputParameters.device = m_DeviceID;
328 outputParameters.channelCount = pDeviceInfo->maxOutputChannels;
329 outputParameters.sampleFormat = paFloat32;
330 outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
331 outputParameters.hostApiSpecificStreamInfo = 0;
333 if (outputParameters.channelCount)
334 pOutS = &outputParameters;
336 ////////////////////////////////////////////////////////////////////////////////////
337 //update list of supported SRs...
338 m_SamplingRates.clear();
340 // now iterate through our standard SRs and check if they are supported by device
341 // store them for this device
342 for(int sr=0; gAllSampleRates[sr] > 0; sr++)
344 PaError err = Pa_IsFormatSupported(pInS, pOutS, gAllSampleRates[sr]);
345 if( err == paFormatIsSupported)
347 m_SamplingRates.push_back ((int)gAllSampleRates[sr]);
351 ///////////////////////////////////////////////////////////////////////////////////
352 //update buffer sizes
353 m_BufferSizes.clear();
354 bool useDefaultBuffers = true;
356 // In ASIO Windows, the buffer size is set from the sound device manufacturer's control panel
357 long minSize, maxSize, preferredSize, granularity;
358 PaError err = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);
360 if (err == paNoError)
362 std::cout << "API::Device " << m_DeviceName << " Buffers: " << minSize << " " << maxSize << " " << preferredSize << std::endl;
364 m_BufferSizes.push_back (preferredSize);
365 useDefaultBuffers = false;
369 std::cout << "API::Device" << m_DeviceName << " Preffered buffer size is not supported" << std::endl;
372 if (useDefaultBuffers)
374 std::cout << "API::Device" << m_DeviceName << " Using default buffer sizes " <<std::endl;
375 for(int bsize=0; bsize < (sizeof(gAllBufferSizes)/sizeof(gAllBufferSizes[0])); bsize++)
376 m_BufferSizes.push_back (gAllBufferSizes[bsize]);
379 /////////////////////////////////////////////////////////////////////////////////////////
380 //update channels info
382 int maxInputChannels = pDeviceInfo->maxInputChannels;
383 int maxOutputChannels = pDeviceInfo->maxOutputChannels;
385 //Update input channels
386 m_InputChannels.clear();
387 for (int channel = 0; channel < maxInputChannels; channel++)
389 const char* channelName[32]; // 32 is max leth declared by PortAudio for this operation
390 std::stringstream chNameStream;
392 PaError error = PaAsio_GetInputChannelName(m_DeviceID, channel, channelName);
394 chNameStream << (channel+1) << " - ";
396 if (error == paNoError)
398 chNameStream << *channelName;
402 chNameStream << "Input " << (channel+1);
405 m_InputChannels.push_back (chNameStream.str());
409 //Update output channels
410 m_OutputChannels.clear();
411 for (int channel = 0; channel < maxOutputChannels; channel++)
413 const char* channelName[32]; // 32 is max leth declared by PortAudio for this operation
414 std::stringstream chNameStream;
416 PaError error = PaAsio_GetOutputChannelName(m_DeviceID, channel, channelName);
418 chNameStream << (channel+1) << " - ";
420 if (error == paNoError)
422 chNameStream << *channelName;
426 chNameStream << "Output " << (channel+1);
429 m_OutputChannels.push_back (chNameStream.str());
433 std::cout << "API::Device" << m_DeviceName << " Device info update has been finished" << std::endl;
436 SetEvent(m_hUpdateDeviceInfoDone);
440 PaError WCMRPortAudioDevice::testStateValidness(int sampleRate, int bufferSize)
442 PaError paErr = paNoError;
445 const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
447 //following parameters are needed opening test stream and for sample rates validation
448 PaStreamParameters inputParameters, outputParameters;
449 PaStreamParameters *pInS = NULL, *pOutS = NULL;
451 inputParameters.device = m_DeviceID;
452 inputParameters.channelCount = pDeviceInfo->maxInputChannels;
453 inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
454 inputParameters.suggestedLatency = 0;
455 inputParameters.hostApiSpecificStreamInfo = 0;
457 if (inputParameters.channelCount)
458 pInS = &inputParameters;
460 outputParameters.device = m_DeviceID;
461 outputParameters.channelCount = pDeviceInfo->maxOutputChannels;
462 outputParameters.sampleFormat = paFloat32;
463 outputParameters.suggestedLatency = 0;
464 outputParameters.hostApiSpecificStreamInfo = 0;
466 if (outputParameters.channelCount)
467 pOutS = &outputParameters;
469 PaStream *portAudioStream = NULL;
471 //sometimes devices change buffer size if sample rate changes
472 //it updates buffer size during stream opening
473 //we need to find out how device would behave with current sample rate
474 //try opening test stream to load device driver for current sample rate and buffer size
475 paErr = Pa_OpenStream (&portAudioStream, pInS, pOutS, sampleRate, bufferSize, paDitherOff, NULL, NULL);
480 Pa_CloseStream (portAudioStream);
481 portAudioStream = NULL;
488 //**********************************************************************************************
489 // WCMRPortAudioDevice::CurrentSamplingRate
491 //! The device's current sampling rate. This may be overridden, if the device needs to
492 //! query the driver for the current rate.
496 //! \return The device's current sampling rate. -1 on error.
498 //**********************************************************************************************
499 int WCMRPortAudioDevice::CurrentSamplingRate ()
502 //ToDo: Perhaps for ASIO devices that are active, we should retrive the SR from the device...
504 return (m_CurrentSamplingRate);
508 WTErr WCMRPortAudioDevice::SetActive (bool newState)
510 if (newState == true)
512 std::cout << "API::Device " << m_DeviceName << " Activation requested" << std::endl;
513 SignalObjectAndWait(m_hActivateRequestedEvent, m_hActivationDone, INFINITE, false);
517 std::cout << "API::Device " << m_DeviceName << " Deactivation requested" << std::endl;
518 SignalObjectAndWait(m_hDeActivateRequestedEvent, m_hDeActivationDone, INFINITE, false);
521 if (newState == Active() )
528 WTErr WCMRPortAudioDevice::SetStreaming (bool newState)
530 if (newState == true)
532 std::cout << "API::Device " << m_DeviceName << " Stream start requested" << std::endl;
533 SignalObjectAndWait(m_hStartStreamingRequestedEvent, m_hStartStreamingDone, INFINITE, false);
537 std::cout << "API::Device " << m_DeviceName << " Stream stop requested" << std::endl;
538 SignalObjectAndWait(m_hStopStreamingRequestedEvent, m_hStopStreamingDone, INFINITE, false);
541 if (newState == Streaming() )
548 WTErr WCMRPortAudioDevice::ResetDevice()
550 std::cout << "API::Device: " << m_DeviceName << " Reseting device" << std::endl;
552 SignalObjectAndWait(m_hResetRequestedEvent, m_hResetDone, INFINITE, false);
554 if (ConnectionStatus() == DeviceErrors)
563 //**********************************************************************************************
564 // WCMRPortAudioDevice::SetCurrentSamplingRate
566 //! Change the sampling rate to be used by the device.
568 //! \param newRate : The rate to use (samples per sec).
570 //! \return eNoErr always. The derived classes may return error codes.
572 //**********************************************************************************************
573 WTErr WCMRPortAudioDevice::SetCurrentSamplingRate (int newRate)
576 std::vector<int>::iterator intIter;
577 WTErr retVal = eNoErr;
579 //changes the status.
580 int oldRate = CurrentSamplingRate();
581 bool oldActive = Active();
583 //no change, nothing to do
584 if (oldRate == newRate)
587 //see if this is one of our supported rates...
588 intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), newRate);
590 if (intIter == m_SamplingRates.end())
592 //Can't change, perhaps use an "invalid param" type of error
593 retVal = eCommandLineParameter;
599 //Can't change, perhaps use an "in use" type of error
600 retVal = eGenericErr;
605 m_CurrentSamplingRate = newRate;
606 PaError paErr = PaAsio_SetStreamSampleRate (m_PortAudioStream, m_CurrentSamplingRate);
607 Pa_Sleep(PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS); // sleep some time to make sure the change has place
609 if (paErr != paNoError)
611 std::cout << "Sample rate change failed: " << Pa_GetErrorText (paErr) << std::endl;
612 if (paErr == paUnanticipatedHostError)
613 std::cout << "Details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl;
615 retVal = eWrongObjectState;
622 //**********************************************************************************************
623 // WCMRPortAudioDevice::CurrentBufferSize
625 //! The device's current buffer size in use. This may be overridden, if the device needs to
626 //! query the driver for the current size.
630 //! \return The device's current buffer size. 0 on error.
632 //**********************************************************************************************
633 int WCMRPortAudioDevice::CurrentBufferSize ()
635 return m_CurrentBufferSize;
639 //**********************************************************************************************
640 // WCMRPortAudioDevice::SetCurrentBufferSize
642 //! Change the buffer size to be used by the device. This will most likely be overridden,
643 //! the base class simply updates the member variable.
645 //! \param newSize : The buffer size to use (in sample-frames)
647 //! \return eNoErr always. The derived classes may return error codes.
649 //**********************************************************************************************
650 WTErr WCMRPortAudioDevice::SetCurrentBufferSize (int newSize)
653 WTErr retVal = eNoErr;
654 std::vector<int>::iterator intIter;
656 //changes the status.
657 int oldSize = CurrentBufferSize();
658 bool oldActive = Active();
660 //same size, nothing to do.
661 if (oldSize == newSize)
666 //Can't change, perhaps use an "in use" type of error
667 retVal = eGenericErr;
671 std::cout << "Setting buffer: " << newSize << std::endl;
673 //see if this is one of our supported rates...
674 intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), newSize);
675 if (intIter == m_BufferSizes.end())
677 //Sample rate proposed by client is not supported any more
678 if (m_BufferSizes.size() == 1)
680 // we have only one aloved buffer size which is preffered by PA
681 // this is the only value which could be set
682 newSize = m_BufferSizes[0];
683 int bufferSize = newSize;
684 // notify client to update sample rate after us
685 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&bufferSize);
689 // more then one buffer size value is available
690 //Can't change, perhaps use an "invalid param" type of error
691 retVal = eCommandLineParameter;
698 //Deactivate it for the change...
703 m_CurrentBufferSize = newSize;
708 retVal = SetActive (true);
715 //**********************************************************************************************
716 // WCMRPortAudioDevice::ConnectionStatus
718 //! Retrieves the device's current connection status. This will most likely be overridden,
719 //! in case some driver communication is required to query the status.
723 //! \return A ConnectionStates value.
725 //**********************************************************************************************
726 WCMRPortAudioDevice::ConnectionStates WCMRPortAudioDevice::ConnectionStatus ()
729 //ToDo: May want to do something more to extract the actual status!
730 return (m_ConnectionStatus);
735 //**********************************************************************************************
736 // WCMRPortAudioDevice::activateDevice
738 //! IS CALLED BY PROCESS THREAD
739 //! Sets the device into "active" state. Essentially, opens the PA device.
740 //! If it's an ASIO device it may result in buffer size change in some cases.
742 //**********************************************************************************************
743 void WCMRPortAudioDevice::activateDevice (bool callerIsWaiting/*=false*/)
747 PaError paErr = paNoError;
749 // if device is not active activate it
752 std::list<long> buffersSizes;
753 buffersSizes.push_back(m_CurrentBufferSize);
755 long minSize, maxSize, preferredSize, granularity;
756 PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);
758 if (paErr == paNoError)
760 buffersSizes.push_front(preferredSize);
763 PaStreamParameters inputParameters, outputParameters;
764 PaStreamParameters *pInS = NULL, *pOutS = NULL;
766 const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
767 const PaHostApiInfo *pHostApiInfo = Pa_GetHostApiInfo(pDeviceInfo->hostApi);
769 inputParameters.device = m_DeviceID;
770 inputParameters.channelCount = (int)m_InputChannels.size();
771 inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
772 inputParameters.suggestedLatency = Pa_GetDeviceInfo(m_DeviceID)->defaultLowInputLatency;
773 inputParameters.hostApiSpecificStreamInfo = 0;
775 if (inputParameters.channelCount)
776 pInS = &inputParameters;
778 outputParameters.device = m_DeviceID;
779 outputParameters.channelCount = (int)m_OutputChannels.size();
780 outputParameters.sampleFormat = paFloat32;
781 outputParameters.suggestedLatency = Pa_GetDeviceInfo(m_DeviceID)->defaultLowOutputLatency;
782 outputParameters.hostApiSpecificStreamInfo = 0;
784 if (outputParameters.channelCount)
785 pOutS = &outputParameters;
787 // try opening stream with current buffer and the rest if not successful
788 std::list<long>::const_iterator bufferIter = buffersSizes.begin();
789 for (; bufferIter != buffersSizes.end(); ++bufferIter) {
791 std::cout << "API::Device" << m_DeviceName << " Opening device stream " << std::endl;
792 std::cout << "Sample rate: " << m_CurrentSamplingRate << " buffer size: " << *bufferIter << std::endl;
793 paErr = Pa_OpenStream(&m_PortAudioStream,
796 m_CurrentSamplingRate,
799 WCMRPortAudioDevice::TheCallback,
802 if(paErr == paNoError)
807 std::cout << "Cannot open streamm with buffer: "<< *bufferIter << " Error: " << Pa_GetErrorText (paErr) << std::endl;
809 if (paErr == paUnanticipatedHostError)
810 std::cout << "Error details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl;
813 if(paErr == paNoError)
815 long minSize, maxSize, preferredSize, granularity;
816 PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);
818 if (paErr == paNoError && m_CurrentBufferSize != preferredSize)
820 m_CurrentBufferSize = preferredSize;
821 m_BufferSizes.clear();
822 m_BufferSizes.push_back(preferredSize);
823 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&preferredSize);
828 m_IgnoreThisDrop = true;
830 if (pHostApiInfo->type == paASIO)
832 m_BufferSizeChangeRequested = 0;
833 m_BufferSizeChangeReported = 0;
834 m_ResetRequested = 0;
836 m_ResyncRequested = 0;
837 m_ResyncReported = 0;
838 PaAsio_SetMessageHook (StaticASIOMessageHook, this);
841 m_ConnectionStatus = DeviceAvailable;
846 //failed, do not update device state
847 std::cout << "Failed to open pa stream: " << Pa_GetErrorText (paErr) << std::endl;
848 DEBUG_MSG( "Failed to open pa stream: " << Pa_GetErrorText (paErr) );
849 m_ConnectionStatus = DeviceErrors;
850 m_lastErr = eAsioFailed;
857 SetEvent(m_hActivationDone);
861 //**********************************************************************************************
862 // WCMRPortAudioDevice::deactivateDevice
864 //! IS CALLED BY PROCESS THREAD
865 //! Sets the device into "inactive" state. Essentially, closes the PA device.
867 //**********************************************************************************************
868 void WCMRPortAudioDevice::deactivateDevice (bool callerIsWaiting/*=false*/)
872 PaError paErr = paNoError;
881 if (m_PortAudioStream)
883 //close the stream first
884 std::cout << "API::Device" << m_DeviceName << " Closing device stream" << std::endl;
885 paErr = Pa_CloseStream (m_PortAudioStream);
886 if(paErr == paNoError)
888 m_PortAudioStream = NULL;
891 m_IgnoreThisDrop = true;
892 m_BufferSizeChangeRequested = 0;
893 m_BufferSizeChangeReported = 0;
894 m_ResetRequested = 0;
896 m_ResyncRequested = 0;
897 m_ResyncReported = 0;
898 PaAsio_SetMessageHook (NULL, NULL);
900 //finaly set device state to "not active"
902 m_ConnectionStatus = DeviceDisconnected;
907 //failed, do not update device state
908 std::cout << "Failed to close pa stream stream " << Pa_GetErrorText (paErr) << std::endl;
909 DEBUG_MSG( "Failed to open pa stream stream " << Pa_GetErrorText (paErr) );
910 m_ConnectionStatus = DeviceErrors;
911 m_lastErr = eAsioFailed;
917 SetEvent(m_hDeActivationDone);
921 //**********************************************************************************************
922 // WCMRPortAudioDevice::startStreaming
924 //! Sets the devices into "streaming" state. Calls PA's Start stream routines.
925 //! This roughly corresponds to calling Start on the lower level interface.
927 //**********************************************************************************************
928 void WCMRPortAudioDevice::startStreaming (bool callerIsWaiting/*=false*/)
932 // proceed if the device is not streaming
935 PaError paErr = paNoError;
936 m_StopRequested = false;
939 std::cout << "API::Device" << m_DeviceName << " Starting device stream" << std::endl;
942 const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID);
944 unsigned int inChannelCount = pDeviceInfo->maxInputChannels;
945 unsigned int outChannelCount = pDeviceInfo->maxOutputChannels;
947 paErr = Pa_StartStream( m_PortAudioStream );
949 if(paErr == paNoError)
951 // if the stream was started successfully
952 m_IsStreaming = true;
953 std::cout << "API::Device" << m_DeviceName << " Device is streaming" << std::endl;
957 std::cout << "Failed to start PA stream: " << Pa_GetErrorText (paErr) << std::endl;
958 DEBUG_MSG( "Failed to start PA stream: " << Pa_GetErrorText (paErr) );
959 m_lastErr = eGenericErr;
964 SetEvent(m_hStartStreamingDone);
968 //**********************************************************************************************
969 // WCMRPortAudioDevice::stopStreaming
971 //! Sets the devices into "not streaming" state. Calls PA's Stop stream routines.
972 //! This roughly corresponds to calling Stop on the lower level interface.
974 //**********************************************************************************************
975 void WCMRPortAudioDevice::stopStreaming (bool callerIsWaiting/*=false*/)
979 // proceed if the device is streaming
982 PaError paErr = paNoError;
983 m_StopRequested = true;
985 std::cout << "API::Device " << m_DeviceName << " Stopping device stream" << std::endl;
986 paErr = Pa_StopStream( m_PortAudioStream );
988 if(paErr == paNoError)
990 // if the stream was stopped successfully
991 m_IsStreaming = false;
996 std::cout << "Failed to stop PA stream: " << Pa_GetErrorText (paErr) << std::endl;
997 DEBUG_MSG( "Failed to stop PA stream " << Pa_GetErrorText (paErr) );
998 m_lastErr = eGenericErr;
1002 if (callerIsWaiting)
1003 SetEvent(m_hStopStreamingDone);
1007 //**********************************************************************************************
1008 // WCMRPortAudioDevice::resetDevice
1010 //! Resets the device, updates device info. Importnat: does PA reinitialization calling
1011 //! Pa_terminate/Pa_initialize functions.
1017 //**********************************************************************************************
1018 void WCMRPortAudioDevice::resetDevice (bool callerIsWaiting /*=false*/ )
1020 std::cout << "API::Device" << m_DeviceName << "Reseting device" << std::endl;
1022 PaError paErr = paNoError;
1024 // Keep device sates
1025 bool wasStreaming = Streaming();
1026 bool wasActive = Active();
1032 // Cache device buffer size as it might be changed during reset
1033 int oldBufferSize = m_CurrentBufferSize;
1035 // Now, validate the state and update device info if required
1036 unsigned int retry = PROPERTY_CHANGE_RETRIES;
1043 std::cout << "Updating device state... " << std::endl;
1044 // update device info
1048 long minSize, maxSize, preferredSize, granularity;
1049 PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity);
1051 if (paErr != paNoError)
1055 m_CurrentBufferSize = preferredSize;
1057 paErr = testStateValidness(m_CurrentSamplingRate, m_CurrentBufferSize);
1058 if (paNoError == paErr)
1060 std::cout << "Device state is valid" << std::endl;
1064 std::cout << "Cannot start with current state: sr: " << m_CurrentSamplingRate << " bs:" << m_CurrentBufferSize \
1065 << "\nReason: " << Pa_GetErrorText (paErr) << std::endl;
1066 if (paErr == paUnanticipatedHostError)
1067 std::cout << "Details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl;
1069 std::cout << "Will try again in " << DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS << "msec" << std::endl;
1071 Pa_Sleep(DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS);
1074 if (paErr == paNoError)
1076 // Notify the Application about device setting changes
1077 if (oldBufferSize != m_CurrentBufferSize)
1079 std::cout << "API::Device" << m_DeviceName << " buffer size changed" << std::endl;
1080 int bufferSize = m_CurrentBufferSize;
1081 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&bufferSize);
1084 // Activate the device if it was active before
1088 // Resume streaming if the device was streaming before
1089 if(wasStreaming && m_lastErr == eNoErr && m_ConnectionStatus == DeviceAvailable)
1091 // Notify the Application to prepare for the stream start
1092 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStartsStreaming);
1096 m_ConnectionStatus = DeviceErrors;
1097 m_lastErr = eWrongObjectState;
1100 if (callerIsWaiting)
1101 SetEvent(m_hResetDone);
1105 #ifdef PLATFORM_WINDOWS
1107 long WCMRPortAudioDevice::StaticASIOMessageHook (void *pRefCon, long selector, long value, void* message, double* opt)
1111 return ((WCMRPortAudioDevice*)(pRefCon))->ASIOMessageHook (selector, value, message, opt);
1117 long WCMRPortAudioDevice::ASIOMessageHook (long selector, long WCUNUSEDPARAM(value), void* WCUNUSEDPARAM(message), double* WCUNUSEDPARAM(opt))
1121 case kAsioResyncRequest:
1122 m_ResyncRequested++;
1123 std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioResyncRequest" << std::endl;
1124 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
1127 case kAsioLatenciesChanged:
1128 m_BufferSizeChangeRequested++;
1129 std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioLatenciesChanged" << std::endl;
1130 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
1133 case kAsioBufferSizeChange:
1134 m_BufferSizeChangeRequested++;
1135 std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- m_BufferSizeChangeRequested" << std::endl;
1136 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
1139 case kAsioResetRequest:
1141 std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioResetRequest" << std::endl;
1142 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset);
1147 std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioOverload" << std::endl;
1148 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::Dropout);
1157 //**********************************************************************************************
1158 // WCMRPortAudioDevice::DoIdle
1160 //! A place for doing idle time processing. The other derived classes will probably do something
1165 //! \return eNoErr always.
1167 //**********************************************************************************************
1168 WTErr WCMRPortAudioDevice::DoIdle ()
1170 WTErr retVal = eNoErr;
1172 std::cout << "WCMRPortAudioDevice::DoIdle ()" << std::endl;
1175 m_hUpdateDeviceInfoRequestedEvent,
1176 m_hActivateRequestedEvent,
1177 m_hDeActivateRequestedEvent,
1178 m_hStartStreamingRequestedEvent,
1179 m_hStopStreamingRequestedEvent,
1180 m_hBufferSizeChangedEvent,
1181 m_hSampleRateChangedEvent,
1182 m_hResetRequestedEvent,
1183 m_hResetFromDevRequestedEvent,
1187 const size_t hEventsSize = sizeof(hEvents)/sizeof(hEvents[0]);
1193 DWORD result = WaitForMultipleObjects (hEventsSize, hEvents, FALSE, INFINITE);
1194 result = result - WAIT_OBJECT_0;
1196 if ((result < 0) || (result >= hEventsSize)) {
1197 std::cout << "\t\t\t\t\t\t\tWCMRPortAudioDevice::DoIdle () -> (result < 0) || (result >= hEventsSize):" << result << std::endl;
1198 retVal = eGenericErr;
1202 if (hEvents[result] == m_hExitIdleThread) {
1203 std::cout << "\t\t\t\t\t\t\tWCMRPortAudioDevice::DoIdle () -> m_hExitIdleThread" << result << std::endl;
1208 if (hEvents[result] == m_hUpdateDeviceInfoRequestedEvent) {
1209 std::cout << "\t\t\t\t\t\tupdate requested ..." << std::endl;
1210 updateDeviceInfo(true);
1213 if (hEvents[result] == m_hActivateRequestedEvent) {
1214 std::cout << "\t\t\t\t\t\tactivation requested ..." << std::endl;
1215 activateDevice(true);
1218 if (hEvents[result] == m_hDeActivateRequestedEvent) {
1219 std::cout << "\t\t\t\t\t\tdeactivation requested ..." << std::endl;
1220 deactivateDevice(true);
1223 if (hEvents[result] == m_hStartStreamingRequestedEvent) {
1224 std::cout << "\t\t\t\t\t\tStart stream requested ..." << std::endl;
1225 startStreaming(true);
1228 if (hEvents[result] == m_hStopStreamingRequestedEvent) {
1229 std::cout << "\t\t\t\t\t\tStop stream requested ..." << std::endl;
1230 stopStreaming(true);
1233 if (hEvents[result] == m_hResetRequestedEvent) {
1234 std::cout << "\t\t\t\t\t\treset requested ..." << std::endl;
1238 if (hEvents[result] == m_hResetFromDevRequestedEvent) {
1239 std::cout << "\t\t\t\t\t\treset requested from device..." << std::endl;
1243 if (hEvents[result] == m_hBufferSizeChangedEvent) {
1244 std::cout << "\t\t\t\t\t\tbuffer size changed from device..." << std::endl;
1245 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged);
1248 if (hEvents[result] == m_hSampleRateChangedEvent) {
1249 std::cout << "\t\t\t\t\t\tsample rate changed from device..." << std::endl;
1250 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged);
1260 //**********************************************************************************************
1261 // WCMRPortAudioDevice::SetMonitorChannels
1263 //! Used to set the channels to be used for monitoring.
1265 //! \param leftChannel : Left monitor channel index.
1266 //! \param rightChannel : Right monitor channel index.
1268 //! \return eNoErr always, the derived classes may return appropriate errors.
1270 //**********************************************************************************************
1271 WTErr WCMRPortAudioDevice::SetMonitorChannels (int leftChannel, int rightChannel)
1274 //This will most likely be overridden, the base class simply
1275 //changes the member.
1276 m_LeftMonitorChannel = leftChannel;
1277 m_RightMonitorChannel = rightChannel;
1283 //**********************************************************************************************
1284 // WCMRPortAudioDevice::SetMonitorGain
1286 //! Used to set monitor gain (or atten).
1288 //! \param newGain : The new gain or atten. value to use. Specified as a linear multiplier (not dB)
1290 //! \return eNoErr always, the derived classes may return appropriate errors.
1292 //**********************************************************************************************
1293 WTErr WCMRPortAudioDevice::SetMonitorGain (float newGain)
1296 //This will most likely be overridden, the base class simply
1297 //changes the member.
1299 m_MonitorGain = newGain;
1306 //**********************************************************************************************
1307 // WCMRPortAudioDevice::ShowConfigPanel
1309 //! Used to show device specific config/control panel. Some interfaces may not support it.
1310 //! Some interfaces may require the device to be active before it can display a panel.
1312 //! \param pParam : A device/interface specific parameter, should be the app window handle for ASIO.
1314 //! \return eNoErr always, the derived classes may return errors.
1316 //**********************************************************************************************
1317 WTErr WCMRPortAudioDevice::ShowConfigPanel (void *pParam)
1320 WTErr retVal = eNoErr;
1324 #ifdef PLATFORM_WINDOWS
1325 if(Pa_GetHostApiInfo(Pa_GetDeviceInfo(m_DeviceID)->hostApi)->type == paASIO)
1327 // stop and deactivate the device
1328 bool wasStreaming = Streaming();
1330 // show control panel for the device
1331 if (PaAsio_ShowControlPanel (m_DeviceID, pParam) != paNoError)
1332 retVal = eGenericErr;
1333 // reset device to pick up changes
1335 // restore previous state for the device
1349 //*****************************************************************************************************
1350 // WCMRPortAudioDevice::TheCallback
1352 //! The (static) Port Audio Callback function. This is a static member. It calls on the AudioCallback in the
1353 //! WCMRPortAudioDevice to do the real work.
1355 //! \param pInputBuffer: pointer to input buffer.
1356 //! \param pOutputBuffer: pointer to output buffer.
1357 //! \param framesPerBuffer: number of sample frames per buffer.
1358 //! \param pTimeInfo: time info for PaStream callback.
1359 //! \param statusFlags:
1360 //! \param pUserData: pointer to user data, in our case the WCMRPortAudioDevice object.
1362 //! \return true to stop streaming else returns false.
1363 //******************************************************************************************************
1364 int WCMRPortAudioDevice::TheCallback (const void *pInputBuffer, void *pOutputBuffer, unsigned long framesPerBuffer,
1365 const PaStreamCallbackTimeInfo* /*pTimeInfo*/, PaStreamCallbackFlags statusFlags, void *pUserData )
1367 WCMRPortAudioDevice *pMyDevice = (WCMRPortAudioDevice *)pUserData;
1369 return pMyDevice->AudioCallback ((float *)pInputBuffer, (float *)pOutputBuffer, framesPerBuffer,
1370 (statusFlags & (paInputOverflow | paOutputUnderflow)) != 0);
1378 //**********************************************************************************************
1379 // WCMRPortAudioDevice::AudoiCallback
1381 //! Here's where the actual audio processing happens. We call upon all the active connections'
1382 //! sinks to provide data to us which can be put/mixed in the output buffer! Also, we make the
1383 //! input data available to any sources that may call upon us during this time!
1385 //! \param *pInputBuffer : Points to a buffer with recorded data.
1386 //! \param *pOutputBuffer : Points to a buffer to receive playback data.
1387 //! \param framesPerBuffer : Number of sample frames in input and output buffers. Number of channels,
1388 //! which are interleaved, is fixed at Device Open (Active) time. In this implementation,
1389 //! the number of channels are fixed to use the maximum available.
1390 //! \param dropsDetected : True if dropouts were detected in input or output. Can be used to signal the GUI.
1394 //**********************************************************************************************
1395 int WCMRPortAudioDevice::AudioCallback( const float *pInputBuffer, float *pOutputBuffer, unsigned long framesPerBuffer, bool dropsDetected )
1397 UMicroseconds theStartTime;
1402 if (m_IgnoreThisDrop)
1403 m_IgnoreThisDrop = false; //We'll ignore once, just once!
1408 m_pInputData = pInputBuffer;
1410 // VKamyshniy: Is this a right place to call the client???:
1411 struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData =
1417 theStartTime.MicroSeconds()*1000
1420 m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData );
1422 //Don't try to access after this call returns!
1423 m_pInputData = NULL;
1425 m_SampleCounter += framesPerBuffer;
1427 return m_StopRequested;
1433 //**********************************************************************************************
1434 // WCMRPortAudioDeviceManager::WCMRPortAudioDeviceManager
1436 //! The constructuor, we initialize PA, and build the device list.
1438 //! \param *pTheClient : The manager's client object (which receives notifications).
1439 //! \param interfaceType : The PortAudio interface type to use for this manager - acts as a filter.
1440 //! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true.
1442 //! \return Nothing.
1444 //**********************************************************************************************
1445 WCMRPortAudioDeviceManager::WCMRPortAudioDeviceManager (WCMRAudioDeviceManagerClient *pTheClient,
1446 eAudioDeviceFilter eCurAudioDeviceFilter, bool useMultithreading, bool bNocopy)
1447 : WCMRAudioDeviceManager (pTheClient, eCurAudioDeviceFilter)
1449 , m_UseMultithreading(useMultithreading)
1450 , m_bNoCopyAudioBuffer(bNocopy)
1453 std::cout << "API::PortAudioDeviceManager::PA Device manager constructor" << std::endl;
1455 //Always create the None device first...
1456 m_NoneDevice = new WCMRNativeAudioNoneDevice(this);
1458 WTErr err = generateDeviceListImpl();
1463 timeBeginPeriod (1);
1467 //**********************************************************************************************
1468 // WCMRPortAudioDeviceManager::~WCMRPortAudioDeviceManager
1470 //! It clears the device list, releasing each of the device.
1474 //! \return Nothing.
1476 //**********************************************************************************************
1477 WCMRPortAudioDeviceManager::~WCMRPortAudioDeviceManager()
1481 std::cout << "API::Destroying PortAudioDeviceManager " << std::endl;
1485 delete m_NoneDevice;
1489 //destructors should absorb exceptions, no harm in logging though!!
1490 DEBUG_MSG ("Exception during destructor");
1497 WCMRAudioDevice* WCMRPortAudioDeviceManager::initNewCurrentDeviceImpl(const std::string & deviceName)
1499 destroyCurrentDeviceImpl();
1501 std::cout << "API::PortAudioDeviceManager::initNewCurrentDevice " << deviceName << std::endl;
1502 if (deviceName == m_NoneDevice->DeviceName() )
1504 m_CurrentDevice = m_NoneDevice;
1505 return m_CurrentDevice;
1509 WTErr err = GetDeviceInfoByName(deviceName, devInfo);
1515 std::cout << "API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName << std::endl;
1516 TRACE_MSG ("API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName);
1518 m_CurrentDevice = new WCMRPortAudioDevice (this, devInfo.m_DeviceId, m_UseMultithreading, m_bNoCopyAudioBuffer);
1522 std::cout << "Unabled to create PA Device: " << devInfo.m_DeviceId << std::endl;
1523 DEBUG_MSG ("Unabled to create PA Device: " << devInfo.m_DeviceId);
1527 return m_CurrentDevice;
1531 void WCMRPortAudioDeviceManager::destroyCurrentDeviceImpl()
1533 if (m_CurrentDevice != m_NoneDevice)
1534 delete m_CurrentDevice;
1536 m_CurrentDevice = 0;
1540 WTErr WCMRPortAudioDeviceManager::getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates)
1542 WTErr retVal = eNoErr;
1544 sampleRates.clear();
1545 const PaDeviceInfo *pPaDeviceInfo = Pa_GetDeviceInfo(deviceId);
1547 //now find supported sample rates
1548 //following parameters are needed for sample rates validation
1549 PaStreamParameters inputParameters, outputParameters;
1550 PaStreamParameters *pInS = NULL, *pOutS = NULL;
1552 inputParameters.device = deviceId;
1553 inputParameters.channelCount = std::min<int>(2, pPaDeviceInfo->maxInputChannels);
1554 inputParameters.sampleFormat = paFloat32 | paNonInterleaved;
1555 inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
1556 inputParameters.hostApiSpecificStreamInfo = 0;
1558 if (inputParameters.channelCount)
1559 pInS = &inputParameters;
1561 outputParameters.device = deviceId;
1562 outputParameters.channelCount = std::min<int>(2, pPaDeviceInfo->maxOutputChannels);
1563 outputParameters.sampleFormat = paFloat32;
1564 outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
1565 outputParameters.hostApiSpecificStreamInfo = 0;
1567 if (outputParameters.channelCount)
1568 pOutS = &outputParameters;
1570 for(int sr=0; gAllSampleRates[sr] > 0; sr++)
1572 if( paFormatIsSupported == Pa_IsFormatSupported(pInS, pOutS, gAllSampleRates[sr]) )
1574 sampleRates.push_back ((int)gAllSampleRates[sr]);
1582 WTErr WCMRPortAudioDeviceManager::generateDeviceListImpl()
1584 std::cout << "API::PortAudioDeviceManager::Generating device list" << std::endl;
1586 WTErr retVal = eNoErr;
1588 //Initialize PortAudio and ASIO first
1589 PaError paErr = Pa_Initialize();
1591 if (paErr != paNoError)
1593 //ToDo: throw an exception here!
1594 retVal = eSomeThingNotInitailzed;
1598 // lock DeviceInfoVec firts
1599 wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex);
1603 DeviceInfo *pDevInfo = new DeviceInfo(NONE_DEVICE_ID, m_NoneDevice->DeviceName() );
1604 pDevInfo->m_AvailableSampleRates = m_NoneDevice->SamplingRates();
1605 m_DeviceInfoVec.push_back(pDevInfo);
1608 //Get device count...
1609 int numDevices = Pa_GetDeviceCount();
1612 for (int thisDeviceID = 0; thisDeviceID < numDevices; thisDeviceID++)
1614 //if it's of the required type...
1615 const PaDeviceInfo *pPaDeviceInfo = Pa_GetDeviceInfo(thisDeviceID);
1617 if (Pa_GetHostApiInfo(pPaDeviceInfo->hostApi)->type == paASIO)
1619 //build a device object...
1622 std::cout << "API::PortAudioDeviceManager::DeviceID: " << thisDeviceID << ", Device Name: " << pPaDeviceInfo->name << std::endl;
1623 TRACE_MSG ("PA DeviceID: " << thisDeviceID << ", Device Name: " << pPaDeviceInfo->name);
1625 DeviceInfo *pDevInfo = new DeviceInfo(thisDeviceID, pPaDeviceInfo->name);
1628 std::vector<int> availableSampleRates;
1629 WTErr wErr = WCMRPortAudioDeviceManager::getDeviceAvailableSampleRates(thisDeviceID, availableSampleRates);
1633 DEBUG_MSG ("Failed to get device available sample rates. Device ID: " << m_DeviceID);
1635 continue; //proceed to the next device
1638 pDevInfo->m_AvailableSampleRates = availableSampleRates;
1639 pDevInfo->m_MaxInputChannels = pPaDeviceInfo->maxInputChannels;
1640 pDevInfo->m_MaxOutputChannels = pPaDeviceInfo->maxOutputChannels;
1642 //Now check if this device is acceptable according to current input/output settings
1643 bool bRejectDevice = false;
1644 switch(m_eAudioDeviceFilter)
1646 case eInputOnlyDevices:
1647 if (pDevInfo->m_MaxInputChannels != 0)
1649 m_DeviceInfoVec.push_back(pDevInfo);
1653 // Delete unnecesarry device
1654 bRejectDevice = true;
1657 case eOutputOnlyDevices:
1658 if (pDevInfo->m_MaxOutputChannels != 0)
1660 m_DeviceInfoVec.push_back(pDevInfo);
1664 // Delete unnecesarry device
1665 bRejectDevice = true;
1668 case eFullDuplexDevices:
1669 if (pDevInfo->m_MaxInputChannels != 0 && pDevInfo->m_MaxOutputChannels != 0)
1671 m_DeviceInfoVec.push_back(pDevInfo);
1675 // Delete unnecesarry device
1676 bRejectDevice = true;
1681 m_DeviceInfoVec.push_back(pDevInfo);
1687 TRACE_MSG ("API::PortAudioDeviceManager::Device " << pDevInfo->m_DeviceName << "Rejected. \
1688 In Channels = " << pDevInfo->m_MaxInputChannels << "Out Channels = " <<pDevInfo->m_MaxOutputChannels );
1695 std::cout << "API::PortAudioDeviceManager::Unabled to create PA Device: " << std::endl;
1696 DEBUG_MSG ("Unabled to create PA Device: " << thisDeviceID);
1701 //If no devices were found, that's not a good thing!
1702 if (m_DeviceInfoVec.empty() )
1704 std::cout << "API::PortAudioDeviceManager::No matching PortAudio devices were found, total PA devices = " << numDevices << std::endl;
1705 DEBUG_MSG ("No matching PortAudio devices were found, total PA devices = " << numDevices);
1708 //we don't need PA initialized right now
1715 WTErr WCMRPortAudioDeviceManager::getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const
1717 sampleRates.clear ();
1719 WTErr retVal = eNoErr;
1721 if (m_CurrentDevice && deviceName == m_CurrentDevice->DeviceName() )
1723 sampleRates.assign(m_CurrentDevice->SamplingRates().begin(), m_CurrentDevice->SamplingRates().end() );
1728 retVal = GetDeviceInfoByName(deviceName, devInfo);
1730 if (eNoErr == retVal)
1732 sampleRates.assign(devInfo.m_AvailableSampleRates.begin(), devInfo.m_AvailableSampleRates.end() );
1736 std::cout << "API::PortAudioDeviceManager::GetSampleRates: Device not found: "<< deviceName << std::endl;
1743 WTErr WCMRPortAudioDeviceManager::getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& buffers) const
1745 WTErr retVal = eNoErr;
1749 //first check if the request has been made for None device
1750 if (deviceName == m_NoneDevice->DeviceName() )
1752 buffers.assign(m_NoneDevice->BufferSizes().begin(), m_NoneDevice->BufferSizes().end() );
1756 if (m_CurrentDevice && deviceName == m_CurrentDevice->DeviceName() )
1758 buffers.assign(m_CurrentDevice->BufferSizes().begin(), m_CurrentDevice->BufferSizes().end() );
1765 retVal = GetDeviceInfoByName(deviceName, devInfo);
1767 if (eNoErr == retVal)
1769 //make PA request to get actual device buffer sizes
1770 long minSize, maxSize, preferredSize, granularity;
1771 PaError paErr = PaAsio_GetAvailableBufferSizes(devInfo.m_DeviceId, &minSize, &maxSize, &preferredSize, &granularity);
1773 //for Windows ASIO devices we always use prefferes buffer size ONLY
1774 if (paNoError == paErr )
1776 buffers.push_back(preferredSize);
1780 retVal = eAsioFailed;
1781 std::cout << "API::PortAudioDeviceManager::GetBufferSizes: error: " << Pa_GetErrorText (paErr) << " getting buffer sizes for device: "<< deviceName << std::endl;
1786 std::cout << "API::PortAudioDeviceManager::GetBufferSizes: Device not found: "<< deviceName << std::endl;