-/************************************************************************/\r
+/************************************************************************/\r
/*! \class RtAudio\r
\brief Realtime audio i/o C++ classes.\r
\r
RtAudio provides a common API (Application Programming Interface)\r
for realtime audio input/output across Linux (native ALSA, Jack,\r
and OSS), Macintosh OS X (CoreAudio and Jack), and Windows\r
- (DirectSound and ASIO) operating systems.\r
+ (DirectSound, ASIO and WASAPI) operating systems.\r
\r
RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/\r
\r
RtAudio: realtime audio i/o C++ classes\r
- Copyright (c) 2001-2012 Gary P. Scavone\r
+ Copyright (c) 2001-2016 Gary P. Scavone\r
\r
Permission is hereby granted, free of charge, to any person\r
obtaining a copy of this software and associated documentation files\r
*/\r
/************************************************************************/\r
\r
-// RtAudio: Version 4.0.11\r
+// RtAudio: Version 4.1.2\r
\r
#include "RtAudio.h"\r
#include <iostream>\r
#include <cstdlib>\r
#include <cstring>\r
#include <climits>\r
+#include <algorithm>\r
\r
// Static variable definitions.\r
const unsigned int RtApi::MAX_SAMPLE_RATES = 14;\r
32000, 44100, 48000, 88200, 96000, 176400, 192000\r
};\r
\r
-#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)\r
+#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)\r
#define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)\r
#define MUTEX_DESTROY(A) DeleteCriticalSection(A)\r
#define MUTEX_LOCK(A) EnterCriticalSection(A)\r
#define MUTEX_UNLOCK(A) LeaveCriticalSection(A)\r
-#elif defined(__LINUX_ALSA__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)\r
+\r
+ #include "tchar.h"\r
+\r
+ static std::string convertCharPointerToStdString(const char *text)\r
+ {\r
+ return std::string(text);\r
+ }\r
+\r
+ static std::string convertCharPointerToStdString(const wchar_t *text)\r
+ {\r
+ int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);\r
+ std::string s( length-1, '\0' );\r
+ WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);\r
+ return s;\r
+ }\r
+\r
+#elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)\r
// pthread API\r
#define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)\r
#define MUTEX_DESTROY(A) pthread_mutex_destroy(A)\r
//\r
// *************************************************** //\r
\r
+std::string RtAudio :: getVersion( void ) throw()\r
+{\r
+ return RTAUDIO_VERSION;\r
+}\r
+\r
void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) throw()\r
{\r
apis.clear();\r
#if defined(__LINUX_ALSA__)\r
apis.push_back( LINUX_ALSA );\r
#endif\r
+#if defined(__LINUX_PULSE__)\r
+ apis.push_back( LINUX_PULSE );\r
+#endif\r
#if defined(__LINUX_OSS__)\r
apis.push_back( LINUX_OSS );\r
#endif\r
#if defined(__WINDOWS_ASIO__)\r
apis.push_back( WINDOWS_ASIO );\r
#endif\r
+#if defined(__WINDOWS_WASAPI__)\r
+ apis.push_back( WINDOWS_WASAPI );\r
+#endif\r
#if defined(__WINDOWS_DS__)\r
apis.push_back( WINDOWS_DS );\r
#endif\r
\r
void RtAudio :: openRtApi( RtAudio::Api api )\r
{\r
- if (rtapi_)\r
+ if ( rtapi_ )\r
delete rtapi_;\r
rtapi_ = 0;\r
\r
if ( api == LINUX_ALSA )\r
rtapi_ = new RtApiAlsa();\r
#endif\r
+#if defined(__LINUX_PULSE__)\r
+ if ( api == LINUX_PULSE )\r
+ rtapi_ = new RtApiPulse();\r
+#endif\r
#if defined(__LINUX_OSS__)\r
if ( api == LINUX_OSS )\r
rtapi_ = new RtApiOss();\r
if ( api == WINDOWS_ASIO )\r
rtapi_ = new RtApiAsio();\r
#endif\r
+#if defined(__WINDOWS_WASAPI__)\r
+ if ( api == WINDOWS_WASAPI )\r
+ rtapi_ = new RtApiWasapi();\r
+#endif\r
#if defined(__WINDOWS_DS__)\r
if ( api == WINDOWS_DS )\r
rtapi_ = new RtApiDs();\r
#endif\r
}\r
\r
-RtAudio :: RtAudio( RtAudio::Api api ) throw()\r
+RtAudio :: RtAudio( RtAudio::Api api )\r
{\r
rtapi_ = 0;\r
\r
getCompiledApi( apis );\r
for ( unsigned int i=0; i<apis.size(); i++ ) {\r
openRtApi( apis[i] );\r
- if ( rtapi_->getDeviceCount() ) break;\r
+ if ( rtapi_ && rtapi_->getDeviceCount() ) break;\r
}\r
\r
if ( rtapi_ ) return;\r
// It should not be possible to get here because the preprocessor\r
// definition __RTAUDIO_DUMMY__ is automatically defined if no\r
// API-specific definitions are passed to the compiler. But just in\r
- // case something weird happens, we'll print out an error message.\r
- std::cerr << "\nRtAudio: no compiled API support found ... critical error!!\n\n";\r
+ // case something weird happens, we'll thow an error.\r
+ std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";\r
+ throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );\r
}\r
\r
RtAudio :: ~RtAudio() throw()\r
{\r
- delete rtapi_;\r
+ if ( rtapi_ )\r
+ delete rtapi_;\r
}\r
\r
void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,\r
RtAudioFormat format, unsigned int sampleRate,\r
unsigned int *bufferFrames,\r
RtAudioCallback callback, void *userData,\r
- RtAudio::StreamOptions *options )\r
+ RtAudio::StreamOptions *options,\r
+ RtAudioErrorCallback errorCallback )\r
{\r
return rtapi_->openStream( outputParameters, inputParameters, format,\r
sampleRate, bufferFrames, callback,\r
- userData, options );\r
+ userData, options, errorCallback );\r
}\r
\r
// *************************************************** //\r
stream_.userBuffer[1] = 0;\r
MUTEX_INITIALIZE( &stream_.mutex );\r
showWarnings_ = true;\r
+ firstErrorOccurred_ = false;\r
}\r
\r
RtApi :: ~RtApi()\r
RtAudioFormat format, unsigned int sampleRate,\r
unsigned int *bufferFrames,\r
RtAudioCallback callback, void *userData,\r
- RtAudio::StreamOptions *options )\r
+ RtAudio::StreamOptions *options,\r
+ RtAudioErrorCallback errorCallback )\r
{\r
if ( stream_.state != STREAM_CLOSED ) {\r
errorText_ = "RtApi::openStream: a stream is already open!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
\r
+ // Clear stream information potentially left from a previously open stream.\r
+ clearStreamInfo();\r
+\r
if ( oParams && oParams->nChannels < 1 ) {\r
errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
\r
if ( iParams && iParams->nChannels < 1 ) {\r
errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
\r
if ( oParams == NULL && iParams == NULL ) {\r
errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
\r
if ( formatBytes(format) == 0 ) {\r
errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
\r
unsigned int nDevices = getDeviceCount();\r
oChannels = oParams->nChannels;\r
if ( oParams->deviceId >= nDevices ) {\r
errorText_ = "RtApi::openStream: output device parameter value is invalid.";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
}\r
\r
iChannels = iParams->nChannels;\r
if ( iParams->deviceId >= nDevices ) {\r
errorText_ = "RtApi::openStream: input device parameter value is invalid.";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
}\r
}\r
\r
- clearStreamInfo();\r
bool result;\r
\r
if ( oChannels > 0 ) {\r
\r
result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,\r
sampleRate, format, bufferFrames, options );\r
- if ( result == false ) error( RtError::SYSTEM_ERROR );\r
+ if ( result == false ) {\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
}\r
\r
if ( iChannels > 0 ) {\r
sampleRate, format, bufferFrames, options );\r
if ( result == false ) {\r
if ( oChannels > 0 ) closeStream();\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
}\r
}\r
\r
stream_.callbackInfo.callback = (void *) callback;\r
stream_.callbackInfo.userData = userData;\r
+ stream_.callbackInfo.errorCallback = (void *) errorCallback;\r
\r
if ( options ) options->numberOfBuffers = stream_.nBuffers;\r
stream_.state = STREAM_STOPPED;\r
return;\r
}\r
\r
-bool RtApi :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
- unsigned int firstChannel, unsigned int sampleRate,\r
- RtAudioFormat format, unsigned int *bufferSize,\r
- RtAudio::StreamOptions *options )\r
+bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,\r
+ unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,\r
+ RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,\r
+ RtAudio::StreamOptions * /*options*/ )\r
{\r
// MUST be implemented in subclasses!\r
return FAILURE;\r
#endif\r
}\r
\r
+void RtApi :: setStreamTime( double time )\r
+{\r
+ verifyStream();\r
+\r
+ if ( time >= 0.0 )\r
+ stream_.streamTime = time;\r
+}\r
+\r
unsigned int RtApi :: getStreamSampleRate( void )\r
{\r
verifyStream();\r
:deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }\r
};\r
\r
-ThreadHandle threadId;\r
-\r
RtApiCore:: RtApiCore()\r
{\r
#if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )\r
OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
}\r
#endif\r
}\r
OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
if ( id == deviceList[i] ) return i;\r
\r
errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
if ( id == deviceList[i] ) return i;\r
\r
errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
unsigned int nDevices = getDeviceCount();\r
if ( nDevices == 0 ) {\r
errorText_ = "RtApiCore::getDeviceInfo: no devices found!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
if ( device >= nDevices ) {\r
errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
AudioDeviceID deviceList[ nDevices ];\r
0, NULL, &dataSize, (void *) &deviceList );\r
if ( result != noErr ) {\r
errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( result != noErr ) {\r
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
//const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );\r
int length = CFStringGetLength(cfname);\r
char *mname = (char *)malloc(length * 3 + 1);\r
+#if defined( UNICODE ) || defined( _UNICODE )\r
+ CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);\r
+#else\r
CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());\r
+#endif\r
info.name.append( (const char *)mname, strlen(mname) );\r
info.name.append( ": " );\r
CFRelease( cfname );\r
if ( result != noErr ) {\r
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
//const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );\r
length = CFStringGetLength(cfname);\r
char *name = (char *)malloc(length * 3 + 1);\r
+#if defined( UNICODE ) || defined( _UNICODE )\r
+ CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);\r
+#else\r
CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());\r
+#endif\r
info.name.append( (const char *)name, strlen(name) );\r
CFRelease( cfname );\r
free(name);\r
if ( result != noErr || dataSize == 0 ) {\r
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
bufferList = (AudioBufferList *) malloc( dataSize );\r
if ( bufferList == NULL ) {\r
errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
free( bufferList );\r
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( result != noErr || dataSize == 0 ) {\r
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
bufferList = (AudioBufferList *) malloc( dataSize );\r
if ( bufferList == NULL ) {\r
errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
free( bufferList );\r
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( result != kAudioHardwareNoError || dataSize == 0 ) {\r
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( result != kAudioHardwareNoError ) {\r
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
- Float64 minimumRate = 100000000.0, maximumRate = 0.0;\r
+ // The sample rate reporting mechanism is a bit of a mystery. It\r
+ // seems that it can either return individual rates or a range of\r
+ // rates. I assume that if the min / max range values are the same,\r
+ // then that represents a single supported rate and if the min / max\r
+ // range values are different, the device supports an arbitrary\r
+ // range of values (though there might be multiple ranges, so we'll\r
+ // use the most conservative range).\r
+ Float64 minimumRate = 1.0, maximumRate = 10000000000.0;\r
+ bool haveValueRange = false;\r
+ info.sampleRates.clear();\r
for ( UInt32 i=0; i<nRanges; i++ ) {\r
- if ( rangeList[i].mMinimum < minimumRate ) minimumRate = rangeList[i].mMinimum;\r
- if ( rangeList[i].mMaximum > maximumRate ) maximumRate = rangeList[i].mMaximum;\r
+ if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {\r
+ unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;\r
+ info.sampleRates.push_back( tmpSr );\r
+\r
+ if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = tmpSr;\r
+\r
+ } else {\r
+ haveValueRange = true;\r
+ if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;\r
+ if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;\r
+ }\r
}\r
\r
- info.sampleRates.clear();\r
- for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
- if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate )\r
- info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+ if ( haveValueRange ) {\r
+ for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
+ if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {\r
+ info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+ if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = SAMPLE_RATES[k];\r
+ }\r
+ }\r
}\r
\r
+ // Sort and remove any redundant values\r
+ std::sort( info.sampleRates.begin(), info.sampleRates.end() );\r
+ info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );\r
+\r
if ( info.sampleRates.size() == 0 ) {\r
errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
return info;\r
}\r
\r
-OSStatus callbackHandler( AudioDeviceID inDevice,\r
- const AudioTimeStamp* inNow,\r
- const AudioBufferList* inInputData,\r
- const AudioTimeStamp* inInputTime,\r
- AudioBufferList* outOutputData,\r
- const AudioTimeStamp* inOutputTime, \r
- void* infoPointer )\r
+static OSStatus callbackHandler( AudioDeviceID inDevice,\r
+ const AudioTimeStamp* /*inNow*/,\r
+ const AudioBufferList* inInputData,\r
+ const AudioTimeStamp* /*inInputTime*/,\r
+ AudioBufferList* outOutputData,\r
+ const AudioTimeStamp* /*inOutputTime*/,\r
+ void* infoPointer )\r
{\r
CallbackInfo *info = (CallbackInfo *) infoPointer;\r
\r
return kAudioHardwareNoError;\r
}\r
\r
-OSStatus xrunListener( AudioObjectID inDevice,\r
- UInt32 nAddresses,\r
- const AudioObjectPropertyAddress properties[],\r
- void* handlePointer )\r
+static OSStatus xrunListener( AudioObjectID /*inDevice*/,\r
+ UInt32 nAddresses,\r
+ const AudioObjectPropertyAddress properties[],\r
+ void* handlePointer )\r
{\r
CoreHandle *handle = (CoreHandle *) handlePointer;\r
for ( UInt32 i=0; i<nAddresses; i++ ) {\r
return kAudioHardwareNoError;\r
}\r
\r
-OSStatus rateListener( AudioObjectID inDevice,\r
- UInt32 nAddresses,\r
- const AudioObjectPropertyAddress properties[],\r
- void* ratePointer )\r
+static OSStatus rateListener( AudioObjectID inDevice,\r
+ UInt32 /*nAddresses*/,\r
+ const AudioObjectPropertyAddress /*properties*/[],\r
+ void* ratePointer )\r
{\r
-\r
Float64 *rate = (Float64 *) ratePointer;\r
UInt32 dataSize = sizeof( Float64 );\r
AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,\r
\r
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );\r
if (result != noErr || dataSize == 0) {\r
+ free( bufferList );\r
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
return FAILURE;\r
dataSize = sizeof( Float64 );\r
property.mSelector = kAudioDevicePropertyNominalSampleRate;\r
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );\r
-\r
if ( result != noErr ) {\r
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";\r
errorText_ = errorStream_.str();\r
\r
nominalRate = (Float64) sampleRate;\r
result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );\r
-\r
if ( result != noErr ) {\r
+ AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );\r
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
return FAILURE;\r
else {\r
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
}\r
}\r
\r
\r
// Setup the device property listener for over/underload.\r
property.mSelector = kAudioDeviceProcessorOverload;\r
+ property.mScope = kAudioObjectPropertyScopeGlobal;\r
result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );\r
\r
return SUCCESS;\r
stream_.deviceBuffer = 0;\r
}\r
\r
+ stream_.state = STREAM_CLOSED;\r
return FAILURE;\r
}\r
\r
{\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiCore::closeStream(): no open stream to close!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ if (handle) {\r
+ AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+ kAudioObjectPropertyScopeGlobal,\r
+ kAudioObjectPropertyElementMaster };\r
+\r
+ property.mSelector = kAudioDeviceProcessorOverload;\r
+ property.mScope = kAudioObjectPropertyScopeGlobal;\r
+ if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {\r
+ errorText_ = "RtApiCore::closeStream(): error removing property listener!";\r
+ error( RtAudioError::WARNING );\r
+ }\r
+ }\r
if ( stream_.state == STREAM_RUNNING )\r
AudioDeviceStop( handle->id[0], callbackHandler );\r
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
}\r
\r
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
+ if (handle) {\r
+ AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+ kAudioObjectPropertyScopeGlobal,\r
+ kAudioObjectPropertyElementMaster };\r
+\r
+ property.mSelector = kAudioDeviceProcessorOverload;\r
+ property.mScope = kAudioObjectPropertyScopeGlobal;\r
+ if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {\r
+ errorText_ = "RtApiCore::closeStream(): error removing property listener!";\r
+ error( RtAudioError::WARNING );\r
+ }\r
+ }\r
if ( stream_.state == STREAM_RUNNING )\r
AudioDeviceStop( handle->id[1], callbackHandler );\r
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
verifyStream();\r
if ( stream_.state == STREAM_RUNNING ) {\r
errorText_ = "RtApiCore::startStream(): the stream is already running!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
- //MUTEX_LOCK( &stream_.mutex );\r
-\r
OSStatus result = noErr;\r
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
stream_.state = STREAM_RUNNING;\r
\r
unlock:\r
- //MUTEX_UNLOCK( &stream_.mutex );\r
-\r
if ( result == noErr ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiCore :: stopStream( void )\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
-\r
- /*\r
- MUTEX_LOCK( &stream_.mutex );\r
-\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
- */\r
\r
OSStatus result = noErr;\r
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled\r
}\r
\r
- //MUTEX_UNLOCK( &stream_.mutex );\r
result = AudioDeviceStop( handle->id[0], callbackHandler );\r
- //MUTEX_LOCK( &stream_.mutex );\r
if ( result != noErr ) {\r
errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";\r
errorText_ = errorStream_.str();\r
\r
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
\r
- //MUTEX_UNLOCK( &stream_.mutex );\r
result = AudioDeviceStop( handle->id[1], callbackHandler );\r
- //MUTEX_LOCK( &stream_.mutex );\r
if ( result != noErr ) {\r
errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";\r
errorText_ = errorStream_.str();\r
stream_.state = STREAM_STOPPED;\r
\r
unlock:\r
- //MUTEX_UNLOCK( &stream_.mutex );\r
-\r
if ( result == noErr ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiCore :: abortStream( void )\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
// aborted. It is better to handle it this way because the\r
// callbackEvent() function probably should return before the AudioDeviceStop()\r
// function is called.\r
-extern "C" void *coreStopStream( void *ptr )\r
+static void *coreStopStream( void *ptr )\r
{\r
CallbackInfo *info = (CallbackInfo *) ptr;\r
RtApiCore *object = (RtApiCore *) info->object;\r
\r
object->stopStream();\r
-\r
pthread_exit( NULL );\r
}\r
\r
if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return FAILURE;\r
}\r
\r
\r
// Check if we were draining the stream and signal is finished.\r
if ( handle->drainCounter > 3 ) {\r
+ ThreadHandle threadId;\r
\r
- if ( handle->internalDrain == true ) {\r
- stream_.state = STREAM_STOPPING;\r
+ stream_.state = STREAM_STOPPING;\r
+ if ( handle->internalDrain == true )\r
pthread_create( &threadId, NULL, coreStopStream, info );\r
- //stopStream();\r
- }\r
else // external call to stopStream()\r
pthread_cond_signal( &handle->condition );\r
return SUCCESS;\r
}\r
\r
- /*\r
- MUTEX_LOCK( &stream_.mutex );\r
-\r
- // The state might change while waiting on a mutex.\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- return SUCCESS;\r
- }\r
- */\r
-\r
AudioDeviceID outputDevice = handle->id[0];\r
\r
// Invoke user callback to get fresh output data UNLESS we are\r
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
stream_.bufferSize, streamTime, status, info->userData );\r
if ( cbReturnValue == 2 ) {\r
- //MUTEX_UNLOCK( &stream_.mutex );\r
+ stream_.state = STREAM_STOPPING;\r
handle->drainCounter = 2;\r
abortStream();\r
return SUCCESS;\r
}\r
}\r
}\r
+ }\r
\r
- if ( handle->drainCounter ) {\r
- handle->drainCounter++;\r
- goto unlock;\r
- }\r
+ // Don't bother draining input\r
+ if ( handle->drainCounter ) {\r
+ handle->drainCounter++;\r
+ goto unlock;\r
}\r
\r
AudioDeviceID inputDevice;\r
:client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }\r
};\r
\r
-ThreadHandle threadId;\r
-void jackSilentError( const char * ) {};\r
+static void jackSilentError( const char * ) {};\r
\r
RtApiJack :: RtApiJack()\r
{\r
jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );\r
if ( client == 0 ) {\r
errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( device >= nDevices ) {\r
jack_client_close( client );\r
errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
// Get the current jack server sample rate.\r
info.sampleRates.clear();\r
- info.sampleRates.push_back( jack_get_sample_rate( client ) );\r
+\r
+ info.preferredSampleRate = jack_get_sample_rate( client );\r
+ info.sampleRates.push_back( info.preferredSampleRate );\r
\r
// Count the available ports containing the client name as device\r
// channels. Jack "input ports" equal RtAudio output channels.\r
if ( info.outputChannels == 0 && info.inputChannels == 0 ) {\r
jack_client_close(client);\r
errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
return info;\r
}\r
\r
-int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )\r
+static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )\r
{\r
CallbackInfo *info = (CallbackInfo *) infoPointer;\r
\r
// server signals that it is shutting down. It is necessary to handle\r
// it this way because the jackShutdown() function must return before\r
// the jack_deactivate() function (in closeStream()) will return.\r
-extern "C" void *jackCloseStream( void *ptr )\r
+static void *jackCloseStream( void *ptr )\r
{\r
CallbackInfo *info = (CallbackInfo *) ptr;\r
RtApiJack *object = (RtApiJack *) info->object;\r
\r
pthread_exit( NULL );\r
}\r
-void jackShutdown( void *infoPointer )\r
+static void jackShutdown( void *infoPointer )\r
{\r
CallbackInfo *info = (CallbackInfo *) infoPointer;\r
RtApiJack *object = (RtApiJack *) info->object;\r
// other problem occurred and we should close the stream.\r
if ( object->isStreamRunning() == false ) return;\r
\r
+ ThreadHandle threadId;\r
pthread_create( &threadId, NULL, jackCloseStream, info );\r
std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;\r
}\r
\r
-int jackXrun( void *infoPointer )\r
+static int jackXrun( void *infoPointer )\r
{\r
JackHandle *handle = (JackHandle *) infoPointer;\r
\r
client = jack_client_open( "RtApiJack", jackoptions, status );\r
if ( client == 0 ) {\r
errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return FAILURE;\r
}\r
}\r
\r
// Get the latency of the JACK port.\r
ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );\r
- if ( ports[ firstChannel ] )\r
- stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );\r
+ if ( ports[ firstChannel ] ) {\r
+ // Added by Ge Wang\r
+ jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);\r
+ // the range (usually the min and max are equal)\r
+ jack_latency_range_t latrange; latrange.min = latrange.max = 0;\r
+ // get the latency range\r
+ jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );\r
+ // be optimistic, use the min!\r
+ stream_.latency[mode] = latrange.min;\r
+ //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );\r
+ }\r
free( ports );\r
\r
// The jack server always uses 32-bit floating-point data.\r
{\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiJack::closeStream(): no open stream to close!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
verifyStream();\r
if ( stream_.state == STREAM_RUNNING ) {\r
errorText_ = "RtApiJack::startStream(): the stream is already running!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
- MUTEX_LOCK(&stream_.mutex);\r
-\r
JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
int result = jack_activate( handle->client );\r
if ( result ) {\r
stream_.state = STREAM_RUNNING;\r
\r
unlock:\r
- MUTEX_UNLOCK(&stream_.mutex);\r
-\r
if ( result == 0 ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiJack :: stopStream( void )\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
-\r
- MUTEX_LOCK( &stream_.mutex );\r
-\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
\r
jack_deactivate( handle->client );\r
stream_.state = STREAM_STOPPED;\r
-\r
- MUTEX_UNLOCK( &stream_.mutex );\r
}\r
\r
void RtApiJack :: abortStream( void )\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
// aborted. It is necessary to handle it this way because the\r
// callbackEvent() function must return before the jack_deactivate()\r
// function will return.\r
-extern "C" void *jackStopStream( void *ptr )\r
+static void *jackStopStream( void *ptr )\r
{\r
CallbackInfo *info = (CallbackInfo *) ptr;\r
RtApiJack *object = (RtApiJack *) info->object;\r
\r
object->stopStream();\r
-\r
pthread_exit( NULL );\r
}\r
\r
bool RtApiJack :: callbackEvent( unsigned long nframes )\r
{\r
- if ( stream_.state == STREAM_STOPPED ) return SUCCESS;\r
+ if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return FAILURE;\r
}\r
if ( stream_.bufferSize != nframes ) {\r
errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return FAILURE;\r
}\r
\r
\r
// Check if we were draining the stream and signal is finished.\r
if ( handle->drainCounter > 3 ) {\r
+ ThreadHandle threadId;\r
+\r
+ stream_.state = STREAM_STOPPING;\r
if ( handle->internalDrain == true )\r
pthread_create( &threadId, NULL, jackStopStream, info );\r
else\r
return SUCCESS;\r
}\r
\r
- MUTEX_LOCK( &stream_.mutex );\r
-\r
- // The state might change while waiting on a mutex.\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- return SUCCESS;\r
- }\r
-\r
// Invoke user callback first, to get fresh output data.\r
if ( handle->drainCounter == 0 ) {\r
RtAudioCallback callback = (RtAudioCallback) info->callback;\r
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
stream_.bufferSize, streamTime, status, info->userData );\r
if ( cbReturnValue == 2 ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- ThreadHandle id;\r
+ stream_.state = STREAM_STOPPING;\r
handle->drainCounter = 2;\r
+ ThreadHandle id;\r
pthread_create( &id, NULL, jackStopStream, info );\r
return SUCCESS;\r
}\r
memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );\r
}\r
}\r
+ }\r
\r
- if ( handle->drainCounter ) {\r
- handle->drainCounter++;\r
- goto unlock;\r
- }\r
+ // Don't bother draining input\r
+ if ( handle->drainCounter ) {\r
+ handle->drainCounter++;\r
+ goto unlock;\r
}\r
\r
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
}\r
\r
unlock:\r
- MUTEX_UNLOCK(&stream_.mutex);\r
-\r
RtApi::tickStreamTime();\r
return SUCCESS;\r
}\r
#include "asiodrivers.h"\r
#include <cmath>\r
\r
-AsioDrivers drivers;\r
-ASIOCallbacks asioCallbacks;\r
-ASIODriverInfo driverInfo;\r
-CallbackInfo *asioCallbackInfo;\r
-bool asioXRun;\r
+static AsioDrivers drivers;\r
+static ASIOCallbacks asioCallbacks;\r
+static ASIODriverInfo driverInfo;\r
+static CallbackInfo *asioCallbackInfo;\r
+static bool asioXRun;\r
\r
struct AsioHandle {\r
int drainCounter; // Tracks callback counts when draining\r
\r
// Function declarations (definitions at end of section)\r
static const char* getAsioErrorString( ASIOError result );\r
-void sampleRateChanged( ASIOSampleRate sRate );\r
-long asioMessages( long selector, long value, void* message, double* opt );\r
+static void sampleRateChanged( ASIOSampleRate sRate );\r
+static long asioMessages( long selector, long value, void* message, double* opt );\r
\r
RtApiAsio :: RtApiAsio()\r
{\r
HRESULT hr = CoInitialize( NULL ); \r
if ( FAILED(hr) ) {\r
errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
}\r
coInitialized_ = true;\r
\r
unsigned int nDevices = getDeviceCount();\r
if ( nDevices == 0 ) {\r
errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
if ( device >= nDevices ) {\r
errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
// If a stream is already open, we cannot probe other devices. Thus, use the saved results.\r
if ( stream_.state != STREAM_CLOSED ) {\r
if ( device >= devices_.size() ) {\r
errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
return devices_[ device ];\r
if ( result != ASE_OK ) {\r
errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( !drivers.loadDriver( driverName ) ) {\r
errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( result != ASE_OK ) {\r
errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
info.sampleRates.clear();\r
for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );\r
- if ( result == ASE_OK )\r
+ if ( result == ASE_OK ) {\r
info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+\r
+ if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = SAMPLE_RATES[i];\r
+ }\r
}\r
\r
// Determine supported data types ... just check first channel and assume rest are the same.\r
drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
info.nativeFormats |= RTAUDIO_FLOAT32;\r
else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )\r
info.nativeFormats |= RTAUDIO_FLOAT64;\r
+ else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )\r
+ info.nativeFormats |= RTAUDIO_SINT24;\r
\r
if ( info.outputChannels > 0 )\r
if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;\r
return info;\r
}\r
\r
-void bufferSwitch( long index, ASIOBool processNow )\r
+static void bufferSwitch( long index, ASIOBool /*processNow*/ )\r
{\r
RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;\r
object->callbackEvent( index );\r
unsigned int firstChannel, unsigned int sampleRate,\r
RtAudioFormat format, unsigned int *bufferSize,\r
RtAudio::StreamOptions *options )\r
-{\r
+{////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r
+\r
+ bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;\r
+\r
// For ASIO, a duplex stream MUST use the same driver.\r
- if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {\r
+ if ( isDuplexInput && stream_.device[0] != device ) {\r
errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";\r
return FAILURE;\r
}\r
}\r
\r
// Only load the driver once for duplex stream.\r
- if ( mode != INPUT || stream_.mode != OUTPUT ) {\r
+ if ( !isDuplexInput ) {\r
// The getDeviceInfo() function will not work when a stream is open\r
// because ASIO does not allow multiple devices to run at the same\r
// time. Thus, we'll probe the system before opening a stream and\r
}\r
}\r
\r
+ // keep them before any "goto error", they are used for error cleanup + goto device boundary checks\r
+ bool buffersAllocated = false;\r
+ AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+ unsigned int nChannels;\r
+\r
+\r
// Check the device channel count.\r
long inputChannels, outputChannels;\r
result = ASIOGetChannels( &inputChannels, &outputChannels );\r
if ( result != ASE_OK ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
\r
if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||\r
( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
stream_.nDeviceChannels[mode] = channels;\r
stream_.nUserChannels[mode] = channels;\r
// Verify the sample rate is supported.\r
result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );\r
if ( result != ASE_OK ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
\r
// Get the current sample rate\r
ASIOSampleRate currentRate;\r
result = ASIOGetSampleRate( ¤tRate );\r
if ( result != ASE_OK ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
\r
// Set the sample rate only if necessary\r
if ( currentRate != sampleRate ) {\r
result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );\r
if ( result != ASE_OK ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
}\r
\r
else channelInfo.isInput = true;\r
result = ASIOGetChannelInfo( &channelInfo );\r
if ( result != ASE_OK ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
\r
// Assuming WINDOWS host is always little-endian.\r
stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;\r
if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;\r
}\r
+ else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+ if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;\r
+ }\r
\r
if ( stream_.deviceFormat[mode] == 0 ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
\r
// Set the buffer size. For a duplex stream, this will end up\r
long minSize, maxSize, preferSize, granularity;\r
result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );\r
if ( result != ASE_OK ) {\r
- drivers.removeCurrentDriver();\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto error;\r
}\r
\r
- if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
- else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
- else if ( granularity == -1 ) {\r
- // Make sure bufferSize is a power of two.\r
- int log2_of_min_size = 0;\r
- int log2_of_max_size = 0;\r
+ if ( isDuplexInput ) {\r
+ // When this is the duplex input (output was opened before), then we have to use the same\r
+ // buffersize as the output, because it might use the preferred buffer size, which most\r
+ // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,\r
+ // So instead of throwing an error, make them equal. The caller uses the reference\r
+ // to the "bufferSize" param as usual to set up processing buffers.\r
\r
- for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {\r
- if ( minSize & ((long)1 << i) ) log2_of_min_size = i;\r
- if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;\r
- }\r
+ *bufferSize = stream_.bufferSize;\r
+\r
+ } else {\r
+ if ( *bufferSize == 0 ) *bufferSize = preferSize;\r
+ else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
+ else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
+ else if ( granularity == -1 ) {\r
+ // Make sure bufferSize is a power of two.\r
+ int log2_of_min_size = 0;\r
+ int log2_of_max_size = 0;\r
+\r
+ for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {\r
+ if ( minSize & ((long)1 << i) ) log2_of_min_size = i;\r
+ if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;\r
+ }\r
\r
- long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );\r
- int min_delta_num = log2_of_min_size;\r
+ long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );\r
+ int min_delta_num = log2_of_min_size;\r
\r
- for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {\r
- long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );\r
- if (current_delta < min_delta) {\r
- min_delta = current_delta;\r
- min_delta_num = i;\r
+ for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {\r
+ long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );\r
+ if (current_delta < min_delta) {\r
+ min_delta = current_delta;\r
+ min_delta_num = i;\r
+ }\r
}\r
- }\r
\r
- *bufferSize = ( (unsigned int)1 << min_delta_num );\r
- if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
- else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
- }\r
- else if ( granularity != 0 ) {\r
- // Set to an even multiple of granularity, rounding up.\r
- *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;\r
+ *bufferSize = ( (unsigned int)1 << min_delta_num );\r
+ if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
+ else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
+ }\r
+ else if ( granularity != 0 ) {\r
+ // Set to an even multiple of granularity, rounding up.\r
+ *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;\r
+ }\r
}\r
\r
- if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize ) {\r
- drivers.removeCurrentDriver();\r
+ /*\r
+ // we don't use it anymore, see above!\r
+ // Just left it here for the case...\r
+ if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {\r
errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";\r
- return FAILURE;\r
+ goto error;\r
}\r
+ */\r
\r
stream_.bufferSize = *bufferSize;\r
stream_.nBuffers = 2;\r
stream_.deviceInterleaved[mode] = false;\r
\r
// Allocate, if necessary, our AsioHandle structure for the stream.\r
- AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
if ( handle == 0 ) {\r
try {\r
handle = new AsioHandle;\r
}\r
catch ( std::bad_alloc& ) {\r
- //if ( handle == NULL ) { \r
- drivers.removeCurrentDriver();\r
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";\r
- return FAILURE;\r
+ goto error;\r
}\r
handle->bufferInfos = 0;\r
\r
// Create the ASIO internal buffers. Since RtAudio sets up input\r
// and output separately, we'll have to dispose of previously\r
// created output buffers for a duplex stream.\r
- long inputLatency, outputLatency;\r
if ( mode == INPUT && stream_.mode == OUTPUT ) {\r
ASIODisposeBuffers();\r
if ( handle->bufferInfos ) free( handle->bufferInfos );\r
}\r
\r
// Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.\r
- bool buffersAllocated = false;\r
- unsigned int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];\r
+ unsigned int i;\r
+ nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];\r
handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );\r
if ( handle->bufferInfos == NULL ) {\r
errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";\r
infos->buffers[0] = infos->buffers[1] = 0;\r
}\r
\r
+ // prepare for callbacks\r
+ stream_.sampleRate = sampleRate;\r
+ stream_.device[mode] = device;\r
+ stream_.mode = isDuplexInput ? DUPLEX : mode;\r
+\r
+ // store this class instance before registering callbacks, that are going to use it\r
+ asioCallbackInfo = &stream_.callbackInfo;\r
+ stream_.callbackInfo.object = (void *) this;\r
+\r
// Set up the ASIO callback structure and create the ASIO data buffers.\r
asioCallbacks.bufferSwitch = &bufferSwitch;\r
asioCallbacks.sampleRateDidChange = &sampleRateChanged;\r
asioCallbacks.asioMessage = &asioMessages;\r
asioCallbacks.bufferSwitchTimeInfo = NULL;\r
result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );\r
+ if ( result != ASE_OK ) {\r
+ // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges\r
+ // but only accept the preferred buffer size as parameter for ASIOCreateBuffers. eg. Creatives ASIO driver\r
+ // in that case, let's be naïve and try that instead\r
+ *bufferSize = preferSize;\r
+ stream_.bufferSize = *bufferSize;\r
+ result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );\r
+ }\r
+\r
if ( result != ASE_OK ) {\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";\r
errorText_ = errorStream_.str();\r
goto error;\r
}\r
- buffersAllocated = true;\r
+ buffersAllocated = true; \r
+ stream_.state = STREAM_STOPPED;\r
\r
// Set flags for buffer conversion.\r
stream_.doConvertBuffer[mode] = false;\r
\r
bool makeBuffer = true;\r
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
- if ( mode == INPUT ) {\r
- if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
- unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
- if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
- }\r
+ if ( isDuplexInput && stream_.deviceBuffer ) {\r
+ unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+ if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
}\r
\r
if ( makeBuffer ) {\r
}\r
}\r
\r
- stream_.sampleRate = sampleRate;\r
- stream_.device[mode] = device;\r
- stream_.state = STREAM_STOPPED;\r
- asioCallbackInfo = &stream_.callbackInfo;\r
- stream_.callbackInfo.object = (void *) this;\r
- if ( stream_.mode == OUTPUT && mode == INPUT )\r
- // We had already set up an output stream.\r
- stream_.mode = DUPLEX;\r
- else\r
- stream_.mode = mode;\r
-\r
// Determine device latencies\r
+ long inputLatency, outputLatency;\r
result = ASIOGetLatencies( &inputLatency, &outputLatency );\r
if ( result != ASE_OK ) {\r
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING); // warn but don't fail\r
+ error( RtAudioError::WARNING); // warn but don't fail\r
}\r
else {\r
stream_.latency[0] = outputLatency;\r
return SUCCESS;\r
\r
error:\r
- if ( buffersAllocated )\r
- ASIODisposeBuffers();\r
- drivers.removeCurrentDriver();\r
+ if ( !isDuplexInput ) {\r
+ // the cleanup for error in the duplex input, is done by RtApi::openStream\r
+ // So we clean up for single channel only\r
\r
- if ( handle ) {\r
- CloseHandle( handle->condition );\r
- if ( handle->bufferInfos )\r
- free( handle->bufferInfos );\r
- delete handle;\r
- stream_.apiHandle = 0;\r
- }\r
+ if ( buffersAllocated )\r
+ ASIODisposeBuffers();\r
\r
- for ( int i=0; i<2; i++ ) {\r
- if ( stream_.userBuffer[i] ) {\r
- free( stream_.userBuffer[i] );\r
- stream_.userBuffer[i] = 0;\r
+ drivers.removeCurrentDriver();\r
+\r
+ if ( handle ) {\r
+ CloseHandle( handle->condition );\r
+ if ( handle->bufferInfos )\r
+ free( handle->bufferInfos );\r
+\r
+ delete handle;\r
+ stream_.apiHandle = 0;\r
}\r
- }\r
\r
- if ( stream_.deviceBuffer ) {\r
- free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = 0;\r
+\r
+ if ( stream_.userBuffer[mode] ) {\r
+ free( stream_.userBuffer[mode] );\r
+ stream_.userBuffer[mode] = 0;\r
+ }\r
+\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
+ }\r
}\r
\r
return FAILURE;\r
-}\r
+}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r
\r
void RtApiAsio :: closeStream()\r
{\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiAsio::closeStream(): no open stream to close!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
verifyStream();\r
if ( stream_.state == STREAM_RUNNING ) {\r
errorText_ = "RtApiAsio::startStream(): the stream is already running!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
- //MUTEX_LOCK( &stream_.mutex );\r
-\r
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
ASIOError result = ASIOStart();\r
if ( result != ASE_OK ) {\r
asioXRun = false;\r
\r
unlock:\r
- //MUTEX_UNLOCK( &stream_.mutex );\r
-\r
stopThreadCalled = false;\r
\r
if ( result == ASE_OK ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiAsio :: stopStream()\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
- /*\r
- MUTEX_LOCK( &stream_.mutex );\r
-\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- return;\r
- }\r
- */\r
-\r
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
if ( handle->drainCounter == 0 ) {\r
handle->drainCounter = 2;\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
WaitForSingleObject( handle->condition, INFINITE ); // block until signaled\r
- //ResetEvent( handle->condition );\r
- // MUTEX_LOCK( &stream_.mutex );\r
}\r
}\r
\r
errorText_ = errorStream_.str();\r
}\r
\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
-\r
if ( result == ASE_OK ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiAsio :: abortStream()\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
// aborted. It is necessary to handle it this way because the\r
// callbackEvent() function must return before the ASIOStop()\r
// function will return.\r
-extern "C" unsigned __stdcall asioStopStream( void *ptr )\r
+static unsigned __stdcall asioStopStream( void *ptr )\r
{\r
CallbackInfo *info = (CallbackInfo *) ptr;\r
RtApiAsio *object = (RtApiAsio *) info->object;\r
\r
object->stopStream();\r
-\r
_endthreadex( 0 );\r
return 0;\r
}\r
\r
bool RtApiAsio :: callbackEvent( long bufferIndex )\r
{\r
- if ( stream_.state == STREAM_STOPPED ) return SUCCESS;\r
- if ( stopThreadCalled ) return SUCCESS;\r
+ if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return FAILURE;\r
}\r
\r
\r
// Check if we were draining the stream and signal if finished.\r
if ( handle->drainCounter > 3 ) {\r
+\r
+ stream_.state = STREAM_STOPPING;\r
if ( handle->internalDrain == false )\r
SetEvent( handle->condition );\r
else { // spawn a thread to stop the stream\r
unsigned threadId;\r
- stopThreadCalled = true;\r
stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,\r
&stream_.callbackInfo, 0, &threadId );\r
}\r
return SUCCESS;\r
}\r
\r
- /*MUTEX_LOCK( &stream_.mutex );\r
-\r
- // The state might change while waiting on a mutex.\r
- if ( stream_.state == STREAM_STOPPED ) goto unlock; */\r
-\r
// Invoke user callback to get fresh output data UNLESS we are\r
// draining stream.\r
if ( handle->drainCounter == 0 ) {\r
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
stream_.bufferSize, streamTime, status, info->userData );\r
if ( cbReturnValue == 2 ) {\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
- // abortStream();\r
- unsigned threadId;\r
- stopThreadCalled = true;\r
+ stream_.state = STREAM_STOPPING;\r
handle->drainCounter = 2;\r
+ unsigned threadId;\r
stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,\r
&stream_.callbackInfo, 0, &threadId );\r
return SUCCESS;\r
}\r
\r
}\r
+ }\r
\r
- if ( handle->drainCounter ) {\r
- handle->drainCounter++;\r
- goto unlock;\r
- }\r
+ // Don't bother draining input\r
+ if ( handle->drainCounter ) {\r
+ handle->drainCounter++;\r
+ goto unlock;\r
}\r
\r
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
// drivers apparently do not function correctly without it.\r
ASIOOutputReady();\r
\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
-\r
RtApi::tickStreamTime();\r
return SUCCESS;\r
}\r
\r
-void sampleRateChanged( ASIOSampleRate sRate )\r
+static void sampleRateChanged( ASIOSampleRate sRate )\r
{\r
// The ASIO documentation says that this usually only happens during\r
// external sync. Audio processing is not stopped by the driver,\r
try {\r
object->stopStream();\r
}\r
- catch ( RtError &exception ) {\r
+ catch ( RtAudioError &exception ) {\r
std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;\r
return;\r
}\r
std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;\r
}\r
\r
-long asioMessages( long selector, long value, void* message, double* opt )\r
+static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )\r
{\r
long ret = 0;\r
\r
const char*message;\r
};\r
\r
- static Messages m[] = \r
+ static const Messages m[] = \r
{\r
{ ASE_NotPresent, "Hardware input or output is not present or available." },\r
{ ASE_HWMalfunction, "Hardware is malfunctioning." },\r
\r
return "Unknown error.";\r
}\r
+\r
//******************** End of __WINDOWS_ASIO__ *********************//\r
#endif\r
\r
\r
-#if defined(__WINDOWS_DS__) // Windows DirectSound API\r
-\r
-// Modified by Robin Davies, October 2005\r
-// - Improvements to DirectX pointer chasing. \r
-// - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.\r
-// - Auto-call CoInitialize for DSOUND and ASIO platforms.\r
-// Various revisions for RtAudio 4.0 by Gary Scavone, April 2007\r
-// Changed device query structure for RtAudio 4.0.7, January 2010\r
+#if defined(__WINDOWS_WASAPI__) // Windows WASAPI API\r
\r
-#include <dsound.h>\r
-#include <assert.h>\r
-#include <algorithm>\r
+// Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014\r
+// - Introduces support for the Windows WASAPI API\r
+// - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required\r
+// - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface\r
+// - Includes automatic internal conversion of sample rate and buffer size between hardware and the user\r
\r
-#if defined(__MINGW32__)\r
- // missing from latest mingw winapi\r
-#define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */\r
-#define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */\r
-#define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */\r
-#define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */\r
+#ifndef INITGUID\r
+ #define INITGUID\r
#endif\r
+#include <audioclient.h>\r
+#include <avrt.h>\r
+#include <mmdeviceapi.h>\r
+#include <functiondiscoverykeys_devpkey.h>\r
+\r
+//=============================================================================\r
+\r
+#define SAFE_RELEASE( objectPtr )\\r
+if ( objectPtr )\\r
+{\\r
+ objectPtr->Release();\\r
+ objectPtr = NULL;\\r
+}\r
\r
-#define MINIMUM_DEVICE_BUFFER_SIZE 32768\r
+typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );\r
\r
-#ifdef _MSC_VER // if Microsoft Visual C++\r
-#pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.\r
-#endif\r
+//-----------------------------------------------------------------------------\r
\r
-static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )\r
+// WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.\r
+// Therefore we must perform all necessary conversions to user buffers in order to satisfy these\r
+// requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to\r
+// provide intermediate storage for read / write synchronization.\r
+class WasapiBuffer\r
{\r
- if ( pointer > bufferSize ) pointer -= bufferSize;\r
- if ( laterPointer < earlierPointer ) laterPointer += bufferSize;\r
- if ( pointer < earlierPointer ) pointer += bufferSize;\r
- return pointer >= earlierPointer && pointer < laterPointer;\r
-}\r
+public:\r
+ WasapiBuffer()\r
+ : buffer_( NULL ),\r
+ bufferSize_( 0 ),\r
+ inIndex_( 0 ),\r
+ outIndex_( 0 ) {}\r
\r
-// A structure to hold various information related to the DirectSound\r
-// API implementation.\r
-struct DsHandle {\r
- unsigned int drainCounter; // Tracks callback counts when draining\r
- bool internalDrain; // Indicates if stop is initiated from callback or not.\r
- void *id[2];\r
- void *buffer[2];\r
- bool xrun[2];\r
- UINT bufferPointer[2]; \r
- DWORD dsBufferSize[2];\r
- DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.\r
- HANDLE condition;\r
+ ~WasapiBuffer() {\r
+ free( buffer_ );\r
+ }\r
\r
- DsHandle()\r
- :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }\r
-};\r
+ // sets the length of the internal ring buffer\r
+ void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {\r
+ free( buffer_ );\r
\r
-// Declarations for utility functions, callbacks, and structures\r
-// specific to the DirectSound implementation.\r
-static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
- LPCTSTR description,\r
- LPCTSTR module,\r
- LPVOID lpContext );\r
+ buffer_ = ( char* ) calloc( bufferSize, formatBytes );\r
\r
-static const char* getErrorString( int code );\r
+ bufferSize_ = bufferSize;\r
+ inIndex_ = 0;\r
+ outIndex_ = 0;\r
+ }\r
\r
-extern "C" unsigned __stdcall callbackHandler( void *ptr );\r
+ // attempt to push a buffer into the ring buffer at the current "in" index\r
+ bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )\r
+ {\r
+ if ( !buffer || // incoming buffer is NULL\r
+ bufferSize == 0 || // incoming buffer has no data\r
+ bufferSize > bufferSize_ ) // incoming buffer too large\r
+ {\r
+ return false;\r
+ }\r
\r
-struct DsDevice {\r
- LPGUID id[2];\r
- bool validId[2];\r
- bool found;\r
- std::string name;\r
+ unsigned int relOutIndex = outIndex_;\r
+ unsigned int inIndexEnd = inIndex_ + bufferSize;\r
+ if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {\r
+ relOutIndex += bufferSize_;\r
+ }\r
\r
- DsDevice()\r
- : found(false) { validId[0] = false; validId[1] = false; }\r
-};\r
+ // "in" index can end on the "out" index but cannot begin at it\r
+ if ( inIndex_ <= relOutIndex && inIndexEnd > relOutIndex ) {\r
+ return false; // not enough space between "in" index and "out" index\r
+ }\r
\r
-std::vector< DsDevice > dsDevices;\r
+ // copy buffer from external to internal\r
+ int fromZeroSize = inIndex_ + bufferSize - bufferSize_;\r
+ fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;\r
+ int fromInSize = bufferSize - fromZeroSize;\r
\r
-RtApiDs :: RtApiDs()\r
+ switch( format )\r
+ {\r
+ case RTAUDIO_SINT8:\r
+ memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );\r
+ memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );\r
+ break;\r
+ case RTAUDIO_SINT16:\r
+ memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );\r
+ memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );\r
+ break;\r
+ case RTAUDIO_SINT24:\r
+ memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );\r
+ memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );\r
+ break;\r
+ case RTAUDIO_SINT32:\r
+ memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );\r
+ memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );\r
+ break;\r
+ case RTAUDIO_FLOAT32:\r
+ memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );\r
+ memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );\r
+ break;\r
+ case RTAUDIO_FLOAT64:\r
+ memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );\r
+ memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );\r
+ break;\r
+ }\r
+\r
+ // update "in" index\r
+ inIndex_ += bufferSize;\r
+ inIndex_ %= bufferSize_;\r
+\r
+ return true;\r
+ }\r
+\r
+ // attempt to pull a buffer from the ring buffer from the current "out" index\r
+ bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )\r
+ {\r
+ if ( !buffer || // incoming buffer is NULL\r
+ bufferSize == 0 || // incoming buffer has no data\r
+ bufferSize > bufferSize_ ) // incoming buffer too large\r
+ {\r
+ return false;\r
+ }\r
+\r
+ unsigned int relInIndex = inIndex_;\r
+ unsigned int outIndexEnd = outIndex_ + bufferSize;\r
+ if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {\r
+ relInIndex += bufferSize_;\r
+ }\r
+\r
+ // "out" index can begin at and end on the "in" index\r
+ if ( outIndex_ < relInIndex && outIndexEnd > relInIndex ) {\r
+ return false; // not enough space between "out" index and "in" index\r
+ }\r
+\r
+ // copy buffer from internal to external\r
+ int fromZeroSize = outIndex_ + bufferSize - bufferSize_;\r
+ fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;\r
+ int fromOutSize = bufferSize - fromZeroSize;\r
+\r
+ switch( format )\r
+ {\r
+ case RTAUDIO_SINT8:\r
+ memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );\r
+ memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );\r
+ break;\r
+ case RTAUDIO_SINT16:\r
+ memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );\r
+ memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );\r
+ break;\r
+ case RTAUDIO_SINT24:\r
+ memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );\r
+ memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );\r
+ break;\r
+ case RTAUDIO_SINT32:\r
+ memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );\r
+ memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );\r
+ break;\r
+ case RTAUDIO_FLOAT32:\r
+ memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );\r
+ memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );\r
+ break;\r
+ case RTAUDIO_FLOAT64:\r
+ memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );\r
+ memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );\r
+ break;\r
+ }\r
+\r
+ // update "out" index\r
+ outIndex_ += bufferSize;\r
+ outIndex_ %= bufferSize_;\r
+\r
+ return true;\r
+ }\r
+\r
+private:\r
+ char* buffer_;\r
+ unsigned int bufferSize_;\r
+ unsigned int inIndex_;\r
+ unsigned int outIndex_;\r
+};\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+// In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate\r
+// between HW and the user. The convertBufferWasapi function is used to perform this conversion\r
+// between HwIn->UserIn and UserOut->HwOut during the stream callback loop.\r
+// This sample rate converter works best with conversions between one rate and its multiple.\r
+void convertBufferWasapi( char* outBuffer,\r
+ const char* inBuffer,\r
+ const unsigned int& channelCount,\r
+ const unsigned int& inSampleRate,\r
+ const unsigned int& outSampleRate,\r
+ const unsigned int& inSampleCount,\r
+ unsigned int& outSampleCount,\r
+ const RtAudioFormat& format )\r
{\r
- // Dsound will run both-threaded. If CoInitialize fails, then just\r
- // accept whatever the mainline chose for a threading model.\r
- coInitialized_ = false;\r
- HRESULT hr = CoInitialize( NULL );\r
- if ( !FAILED( hr ) ) coInitialized_ = true;\r
+ // calculate the new outSampleCount and relative sampleStep\r
+ float sampleRatio = ( float ) outSampleRate / inSampleRate;\r
+ float sampleRatioInv = ( float ) 1 / sampleRatio;\r
+ float sampleStep = 1.0f / sampleRatio;\r
+ float inSampleFraction = 0.0f;\r
+\r
+ outSampleCount = ( unsigned int ) roundf( inSampleCount * sampleRatio );\r
+\r
+ // if inSampleRate is a multiple of outSampleRate (or vice versa) there's no need to interpolate\r
+ if ( floor( sampleRatio ) == sampleRatio || floor( sampleRatioInv ) == sampleRatioInv )\r
+ {\r
+ // frame-by-frame, copy each relative input sample into it's corresponding output sample\r
+ for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )\r
+ {\r
+ unsigned int inSample = ( unsigned int ) inSampleFraction;\r
+\r
+ switch ( format )\r
+ {\r
+ case RTAUDIO_SINT8:\r
+ memcpy( &( ( char* ) outBuffer )[ outSample * channelCount ], &( ( char* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( char ) );\r
+ break;\r
+ case RTAUDIO_SINT16:\r
+ memcpy( &( ( short* ) outBuffer )[ outSample * channelCount ], &( ( short* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( short ) );\r
+ break;\r
+ case RTAUDIO_SINT24:\r
+ memcpy( &( ( S24* ) outBuffer )[ outSample * channelCount ], &( ( S24* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( S24 ) );\r
+ break;\r
+ case RTAUDIO_SINT32:\r
+ memcpy( &( ( int* ) outBuffer )[ outSample * channelCount ], &( ( int* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( int ) );\r
+ break;\r
+ case RTAUDIO_FLOAT32:\r
+ memcpy( &( ( float* ) outBuffer )[ outSample * channelCount ], &( ( float* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( float ) );\r
+ break;\r
+ case RTAUDIO_FLOAT64:\r
+ memcpy( &( ( double* ) outBuffer )[ outSample * channelCount ], &( ( double* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( double ) );\r
+ break;\r
+ }\r
+\r
+ // jump to next in sample\r
+ inSampleFraction += sampleStep;\r
+ }\r
+ }\r
+ else // else interpolate\r
+ {\r
+ // frame-by-frame, copy each relative input sample into it's corresponding output sample\r
+ for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )\r
+ {\r
+ unsigned int inSample = ( unsigned int ) inSampleFraction;\r
+ float inSampleDec = inSampleFraction - inSample;\r
+ unsigned int frameInSample = inSample * channelCount;\r
+ unsigned int frameOutSample = outSample * channelCount;\r
+\r
+ switch ( format )\r
+ {\r
+ case RTAUDIO_SINT8:\r
+ {\r
+ char* convInBuffer = ( char* ) inBuffer;\r
+ for ( unsigned int channel = 0; channel < channelCount; channel++ )\r
+ {\r
+ char fromSample = convInBuffer[ frameInSample + channel ];\r
+ char toSample = convInBuffer[ frameInSample + channelCount + channel ];\r
+ char sampleDiff = ( char ) ( ( toSample - fromSample ) * inSampleDec );\r
+ ( ( char* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;\r
+ }\r
+ break;\r
+ }\r
+ case RTAUDIO_SINT16:\r
+ {\r
+ short* convInBuffer = ( short* ) inBuffer;\r
+ for ( unsigned int channel = 0; channel < channelCount; channel++ )\r
+ {\r
+ short fromSample = convInBuffer[ frameInSample + channel ];\r
+ short toSample = convInBuffer[ frameInSample + channelCount + channel ];\r
+ short sampleDiff = ( short ) ( ( toSample - fromSample ) * inSampleDec );\r
+ ( ( short* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;\r
+ }\r
+ break;\r
+ }\r
+ case RTAUDIO_SINT24:\r
+ {\r
+ S24* convInBuffer = ( S24* ) inBuffer;\r
+ for ( unsigned int channel = 0; channel < channelCount; channel++ )\r
+ {\r
+ int fromSample = convInBuffer[ frameInSample + channel ].asInt();\r
+ int toSample = convInBuffer[ frameInSample + channelCount + channel ].asInt();\r
+ int sampleDiff = ( int ) ( ( toSample - fromSample ) * inSampleDec );\r
+ ( ( S24* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;\r
+ }\r
+ break;\r
+ }\r
+ case RTAUDIO_SINT32:\r
+ {\r
+ int* convInBuffer = ( int* ) inBuffer;\r
+ for ( unsigned int channel = 0; channel < channelCount; channel++ )\r
+ {\r
+ int fromSample = convInBuffer[ frameInSample + channel ];\r
+ int toSample = convInBuffer[ frameInSample + channelCount + channel ];\r
+ int sampleDiff = ( int ) ( ( toSample - fromSample ) * inSampleDec );\r
+ ( ( int* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;\r
+ }\r
+ break;\r
+ }\r
+ case RTAUDIO_FLOAT32:\r
+ {\r
+ float* convInBuffer = ( float* ) inBuffer;\r
+ for ( unsigned int channel = 0; channel < channelCount; channel++ )\r
+ {\r
+ float fromSample = convInBuffer[ frameInSample + channel ];\r
+ float toSample = convInBuffer[ frameInSample + channelCount + channel ];\r
+ float sampleDiff = ( toSample - fromSample ) * inSampleDec;\r
+ ( ( float* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;\r
+ }\r
+ break;\r
+ }\r
+ case RTAUDIO_FLOAT64:\r
+ {\r
+ double* convInBuffer = ( double* ) inBuffer;\r
+ for ( unsigned int channel = 0; channel < channelCount; channel++ )\r
+ {\r
+ double fromSample = convInBuffer[ frameInSample + channel ];\r
+ double toSample = convInBuffer[ frameInSample + channelCount + channel ];\r
+ double sampleDiff = ( toSample - fromSample ) * inSampleDec;\r
+ ( ( double* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;\r
+ }\r
+ break;\r
+ }\r
+ }\r
+\r
+ // jump to next in sample\r
+ inSampleFraction += sampleStep;\r
+ }\r
+ }\r
}\r
\r
-RtApiDs :: ~RtApiDs()\r
+//-----------------------------------------------------------------------------\r
+\r
+// A structure to hold various information related to the WASAPI implementation.\r
+struct WasapiHandle\r
{\r
- if ( coInitialized_ ) CoUninitialize(); // balanced call.\r
- if ( stream_.state != STREAM_CLOSED ) closeStream();\r
-}\r
+ IAudioClient* captureAudioClient;\r
+ IAudioClient* renderAudioClient;\r
+ IAudioCaptureClient* captureClient;\r
+ IAudioRenderClient* renderClient;\r
+ HANDLE captureEvent;\r
+ HANDLE renderEvent;\r
+\r
+ WasapiHandle()\r
+ : captureAudioClient( NULL ),\r
+ renderAudioClient( NULL ),\r
+ captureClient( NULL ),\r
+ renderClient( NULL ),\r
+ captureEvent( NULL ),\r
+ renderEvent( NULL ) {}\r
+};\r
\r
-// The DirectSound default output is always the first device.\r
-unsigned int RtApiDs :: getDefaultOutputDevice( void )\r
+//=============================================================================\r
+\r
+RtApiWasapi::RtApiWasapi()\r
+ : coInitialized_( false ), deviceEnumerator_( NULL )\r
{\r
- return 0;\r
+ // WASAPI can run either apartment or multi-threaded\r
+ HRESULT hr = CoInitialize( NULL );\r
+ if ( !FAILED( hr ) )\r
+ coInitialized_ = true;\r
+\r
+ // Instantiate device enumerator\r
+ hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,\r
+ CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),\r
+ ( void** ) &deviceEnumerator_ );\r
+\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";\r
+ error( RtAudioError::DRIVER_ERROR );\r
+ }\r
}\r
\r
-// The DirectSound default input is always the first input device,\r
-// which is the first capture device enumerated.\r
-unsigned int RtApiDs :: getDefaultInputDevice( void )\r
+//-----------------------------------------------------------------------------\r
+\r
+RtApiWasapi::~RtApiWasapi()\r
{\r
- return 0;\r
+ if ( stream_.state != STREAM_CLOSED )\r
+ closeStream();\r
+\r
+ SAFE_RELEASE( deviceEnumerator_ );\r
+\r
+ // If this object previously called CoInitialize()\r
+ if ( coInitialized_ )\r
+ CoUninitialize();\r
}\r
\r
-unsigned int RtApiDs :: getDeviceCount( void )\r
+//=============================================================================\r
+\r
+unsigned int RtApiWasapi::getDeviceCount( void )\r
{\r
- // Set query flag for previously found devices to false, so that we\r
- // can check for any devices that have disappeared.\r
- for ( unsigned int i=0; i<dsDevices.size(); i++ )\r
- dsDevices[i].found = false;\r
+ unsigned int captureDeviceCount = 0;\r
+ unsigned int renderDeviceCount = 0;\r
\r
- // Query DirectSound devices.\r
- bool isInput = false;\r
- HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &isInput );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ IMMDeviceCollection* captureDevices = NULL;\r
+ IMMDeviceCollection* renderDevices = NULL;\r
+\r
+ // Count capture devices\r
+ errorText_.clear();\r
+ HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";\r
+ goto Exit;\r
}\r
\r
- // Query DirectSoundCapture devices.\r
- isInput = true;\r
- result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &isInput );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ hr = captureDevices->GetCount( &captureDeviceCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";\r
+ goto Exit;\r
}\r
\r
- // Clean out any devices that may have disappeared.\r
- std::vector< int > indices;\r
- for ( unsigned int i=0; i<dsDevices.size(); i++ )\r
- if ( dsDevices[i].found == false ) indices.push_back( i );\r
- unsigned int nErased = 0;\r
- for ( unsigned int i=0; i<indices.size(); i++ )\r
- dsDevices.erase( dsDevices.begin()-nErased++ );\r
+ // Count render devices\r
+ hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";\r
+ goto Exit;\r
+ }\r
+\r
+ hr = renderDevices->GetCount( &renderDeviceCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";\r
+ goto Exit;\r
+ }\r
+\r
+Exit:\r
+ // release all references\r
+ SAFE_RELEASE( captureDevices );\r
+ SAFE_RELEASE( renderDevices );\r
\r
- return dsDevices.size();\r
+ if ( errorText_.empty() )\r
+ return captureDeviceCount + renderDeviceCount;\r
+\r
+ error( RtAudioError::DRIVER_ERROR );\r
+ return 0;\r
}\r
\r
-RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )\r
+//-----------------------------------------------------------------------------\r
+\r
+RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )\r
{\r
RtAudio::DeviceInfo info;\r
+ unsigned int captureDeviceCount = 0;\r
+ unsigned int renderDeviceCount = 0;\r
+ std::string defaultDeviceName;\r
+ bool isCaptureDevice = false;\r
+\r
+ PROPVARIANT deviceNameProp;\r
+ PROPVARIANT defaultDeviceNameProp;\r
+\r
+ IMMDeviceCollection* captureDevices = NULL;\r
+ IMMDeviceCollection* renderDevices = NULL;\r
+ IMMDevice* devicePtr = NULL;\r
+ IMMDevice* defaultDevicePtr = NULL;\r
+ IAudioClient* audioClient = NULL;\r
+ IPropertyStore* devicePropStore = NULL;\r
+ IPropertyStore* defaultDevicePropStore = NULL;\r
+\r
+ WAVEFORMATEX* deviceFormat = NULL;\r
+ WAVEFORMATEX* closestMatchFormat = NULL;\r
+\r
+ // probed\r
info.probed = false;\r
\r
- if ( dsDevices.size() == 0 ) {\r
- // Force a query of all devices\r
- getDeviceCount();\r
- if ( dsDevices.size() == 0 ) {\r
- errorText_ = "RtApiDs::getDeviceInfo: no devices found!";\r
- error( RtError::INVALID_USE );\r
- }\r
+ // Count capture devices\r
+ errorText_.clear();\r
+ RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;\r
+ HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";\r
+ goto Exit;\r
}\r
\r
- if ( device >= dsDevices.size() ) {\r
- errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";\r
- error( RtError::INVALID_USE );\r
+ hr = captureDevices->GetCount( &captureDeviceCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";\r
+ goto Exit;\r
}\r
\r
- HRESULT result;\r
- if ( dsDevices[ device ].validId[0] == false ) goto probeInput;\r
+ // Count render devices\r
+ hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";\r
+ goto Exit;\r
+ }\r
\r
- LPDIRECTSOUND output;\r
- DSCAPS outCaps;\r
- result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto probeInput;\r
+ hr = renderDevices->GetCount( &renderDeviceCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";\r
+ goto Exit;\r
}\r
\r
- outCaps.dwSize = sizeof( outCaps );\r
- result = output->GetCaps( &outCaps );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto probeInput;\r
+ // validate device index\r
+ if ( device >= captureDeviceCount + renderDeviceCount ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";\r
+ errorType = RtAudioError::INVALID_USE;\r
+ goto Exit;\r
}\r
\r
- // Get output channel information.\r
- info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;\r
+ // determine whether index falls within capture or render devices\r
+ if ( device >= renderDeviceCount ) {\r
+ hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";\r
+ goto Exit;\r
+ }\r
+ isCaptureDevice = true;\r
+ }\r
+ else {\r
+ hr = renderDevices->Item( device, &devicePtr );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";\r
+ goto Exit;\r
+ }\r
+ isCaptureDevice = false;\r
+ }\r
\r
- // Get sample rate information.\r
- info.sampleRates.clear();\r
- for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
- if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&\r
- SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate )\r
- info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+ // get default device name\r
+ if ( isCaptureDevice ) {\r
+ hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";\r
+ goto Exit;\r
+ }\r
+ }\r
+ else {\r
+ hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";\r
+ goto Exit;\r
+ }\r
}\r
\r
- // Get format information.\r
- if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";\r
+ goto Exit;\r
+ }\r
+ PropVariantInit( &defaultDeviceNameProp );\r
\r
- output->Release();\r
+ hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";\r
+ goto Exit;\r
+ }\r
\r
- if ( getDefaultOutputDevice() == device )\r
- info.isDefaultOutput = true;\r
+ defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);\r
\r
- if ( dsDevices[ device ].validId[1] == false ) {\r
- info.name = dsDevices[ device ].name;\r
- info.probed = true;\r
- return info;\r
+ // name\r
+ hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";\r
+ goto Exit;\r
}\r
\r
- probeInput:\r
+ PropVariantInit( &deviceNameProp );\r
\r
- LPDIRECTSOUNDCAPTURE input;\r
- result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- return info;\r
+ hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";\r
+ goto Exit;\r
}\r
\r
- DSCCAPS inCaps;\r
- inCaps.dwSize = sizeof( inCaps );\r
- result = input->GetCaps( &inCaps );\r
- if ( FAILED( result ) ) {\r
- input->Release();\r
- errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- return info;\r
+ info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);\r
+\r
+ // is default\r
+ if ( isCaptureDevice ) {\r
+ info.isDefaultInput = info.name == defaultDeviceName;\r
+ info.isDefaultOutput = false;\r
+ }\r
+ else {\r
+ info.isDefaultInput = false;\r
+ info.isDefaultOutput = info.name == defaultDeviceName;\r
}\r
\r
- // Get input channel information.\r
- info.inputChannels = inCaps.dwChannels;\r
+ // channel count\r
+ hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";\r
+ goto Exit;\r
+ }\r
\r
- // Get sample rate and format information.\r
- std::vector<unsigned int> rates;\r
- if ( inCaps.dwChannels >= 2 ) {\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ hr = audioClient->GetMixFormat( &deviceFormat );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";\r
+ goto Exit;\r
+ }\r
\r
- if ( info.nativeFormats & RTAUDIO_SINT16 ) {\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );\r
+ if ( isCaptureDevice ) {\r
+ info.inputChannels = deviceFormat->nChannels;\r
+ info.outputChannels = 0;\r
+ info.duplexChannels = 0;\r
+ }\r
+ else {\r
+ info.inputChannels = 0;\r
+ info.outputChannels = deviceFormat->nChannels;\r
+ info.duplexChannels = 0;\r
+ }\r
+\r
+ // sample rates\r
+ info.sampleRates.clear();\r
+\r
+ // allow support for all sample rates as we have a built-in sample rate converter\r
+ for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {\r
+ info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+ }\r
+ info.preferredSampleRate = deviceFormat->nSamplesPerSec;\r
+\r
+ // native format\r
+ info.nativeFormats = 0;\r
+\r
+ if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||\r
+ ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&\r
+ ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )\r
+ {\r
+ if ( deviceFormat->wBitsPerSample == 32 ) {\r
+ info.nativeFormats |= RTAUDIO_FLOAT32;\r
}\r
- else if ( info.nativeFormats & RTAUDIO_SINT8 ) {\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );\r
+ else if ( deviceFormat->wBitsPerSample == 64 ) {\r
+ info.nativeFormats |= RTAUDIO_FLOAT64;\r
}\r
}\r
- else if ( inCaps.dwChannels == 1 ) {\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
-\r
- if ( info.nativeFormats & RTAUDIO_SINT16 ) {\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );\r
+ else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||\r
+ ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&\r
+ ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )\r
+ {\r
+ if ( deviceFormat->wBitsPerSample == 8 ) {\r
+ info.nativeFormats |= RTAUDIO_SINT8;\r
}\r
- else if ( info.nativeFormats & RTAUDIO_SINT8 ) {\r
- if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );\r
- if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );\r
+ else if ( deviceFormat->wBitsPerSample == 16 ) {\r
+ info.nativeFormats |= RTAUDIO_SINT16;\r
+ }\r
+ else if ( deviceFormat->wBitsPerSample == 24 ) {\r
+ info.nativeFormats |= RTAUDIO_SINT24;\r
+ }\r
+ else if ( deviceFormat->wBitsPerSample == 32 ) {\r
+ info.nativeFormats |= RTAUDIO_SINT32;\r
}\r
}\r
- else info.inputChannels = 0; // technically, this would be an error\r
-\r
- input->Release();\r
\r
- if ( info.inputChannels == 0 ) return info;\r
+ // probed\r
+ info.probed = true;\r
\r
- // Copy the supported rates to the info structure but avoid duplication.\r
- bool found;\r
- for ( unsigned int i=0; i<rates.size(); i++ ) {\r
- found = false;\r
- for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {\r
- if ( rates[i] == info.sampleRates[j] ) {\r
- found = true;\r
- break;\r
- }\r
- }\r
- if ( found == false ) info.sampleRates.push_back( rates[i] );\r
- }\r
- std::sort( info.sampleRates.begin(), info.sampleRates.end() );\r
+Exit:\r
+ // release all references\r
+ PropVariantClear( &deviceNameProp );\r
+ PropVariantClear( &defaultDeviceNameProp );\r
\r
- // If device opens for both playback and capture, we determine the channels.\r
- if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
- info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+ SAFE_RELEASE( captureDevices );\r
+ SAFE_RELEASE( renderDevices );\r
+ SAFE_RELEASE( devicePtr );\r
+ SAFE_RELEASE( defaultDevicePtr );\r
+ SAFE_RELEASE( audioClient );\r
+ SAFE_RELEASE( devicePropStore );\r
+ SAFE_RELEASE( defaultDevicePropStore );\r
\r
- if ( device == 0 ) info.isDefaultInput = true;\r
+ CoTaskMemFree( deviceFormat );\r
+ CoTaskMemFree( closestMatchFormat );\r
\r
- // Copy name and return.\r
- info.name = dsDevices[ device ].name;\r
- info.probed = true;\r
+ if ( !errorText_.empty() )\r
+ error( errorType );\r
return info;\r
}\r
\r
-bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
- unsigned int firstChannel, unsigned int sampleRate,\r
- RtAudioFormat format, unsigned int *bufferSize,\r
- RtAudio::StreamOptions *options )\r
+//-----------------------------------------------------------------------------\r
+\r
+unsigned int RtApiWasapi::getDefaultOutputDevice( void )\r
{\r
- if ( channels + firstChannel > 2 ) {\r
- errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";\r
- return FAILURE;\r
+ for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {\r
+ if ( getDeviceInfo( i ).isDefaultOutput ) {\r
+ return i;\r
+ }\r
}\r
\r
- unsigned int nDevices = dsDevices.size();\r
- if ( nDevices == 0 ) {\r
- // This should not happen because a check is made before this function is called.\r
- errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";\r
- return FAILURE;\r
- }\r
+ return 0;\r
+}\r
\r
- if ( device >= nDevices ) {\r
- // This should not happen because a check is made before this function is called.\r
- errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";\r
- return FAILURE;\r
- }\r
+//-----------------------------------------------------------------------------\r
\r
- if ( mode == OUTPUT ) {\r
- if ( dsDevices[ device ].validId[0] == false ) {\r
- errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+unsigned int RtApiWasapi::getDefaultInputDevice( void )\r
+{\r
+ for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {\r
+ if ( getDeviceInfo( i ).isDefaultInput ) {\r
+ return i;\r
}\r
}\r
- else { // mode == INPUT\r
- if ( dsDevices[ device ].validId[1] == false ) {\r
- errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+\r
+ return 0;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::closeStream( void )\r
+{\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiWasapi::closeStream: No open stream to close.";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- // According to a note in PortAudio, using GetDesktopWindow()\r
- // instead of GetForegroundWindow() is supposed to avoid problems\r
- // that occur when the application's window is not the foreground\r
- // window. Also, if the application window closes before the\r
- // DirectSound buffer, DirectSound can crash. In the past, I had\r
- // problems when using GetDesktopWindow() but it seems fine now\r
- // (January 2010). I'll leave it commented here.\r
- // HWND hWnd = GetForegroundWindow();\r
- HWND hWnd = GetDesktopWindow();\r
+ if ( stream_.state != STREAM_STOPPED )\r
+ stopStream();\r
\r
- // Check the numberOfBuffers parameter and limit the lowest value to\r
- // two. This is a judgement call and a value of two is probably too\r
- // low for capture, but it should work for playback.\r
- int nBuffers = 0;\r
- if ( options ) nBuffers = options->numberOfBuffers;\r
- if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;\r
- if ( nBuffers < 2 ) nBuffers = 3;\r
+ // clean up stream memory\r
+ SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )\r
+ SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )\r
\r
- // Check the lower range of the user-specified buffer size and set\r
- // (arbitrarily) to a lower bound of 32.\r
- if ( *bufferSize < 32 ) *bufferSize = 32;\r
+ SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )\r
+ SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )\r
\r
- // Create the wave format structure. The data format setting will\r
- // be determined later.\r
- WAVEFORMATEX waveFormat;\r
- ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );\r
- waveFormat.wFormatTag = WAVE_FORMAT_PCM;\r
- waveFormat.nChannels = channels + firstChannel;\r
- waveFormat.nSamplesPerSec = (unsigned long) sampleRate;\r
+ if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )\r
+ CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );\r
\r
- // Determine the device buffer size. By default, we'll use the value\r
- // defined above (32K), but we will grow it to make allowances for\r
- // very large software buffer sizes.\r
- DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;;\r
- DWORD dsPointerLeadTime = 0;\r
+ if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )\r
+ CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );\r
\r
- void *ohandle = 0, *bhandle = 0;\r
- HRESULT result;\r
- if ( mode == OUTPUT ) {\r
+ delete ( WasapiHandle* ) stream_.apiHandle;\r
+ stream_.apiHandle = NULL;\r
\r
- LPDIRECTSOUND output;\r
- result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ for ( int i = 0; i < 2; i++ ) {\r
+ if ( stream_.userBuffer[i] ) {\r
+ free( stream_.userBuffer[i] );\r
+ stream_.userBuffer[i] = 0;\r
}\r
+ }\r
\r
- DSCAPS outCaps;\r
- outCaps.dwSize = sizeof( outCaps );\r
- result = output->GetCaps( &outCaps );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
+ }\r
\r
- // Check channel information.\r
- if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {\r
- errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ // update stream state\r
+ stream_.state = STREAM_CLOSED;\r
+}\r
\r
- // Check format information. Use 16-bit format unless not\r
- // supported or user requests 8-bit.\r
- if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&\r
- !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {\r
- waveFormat.wBitsPerSample = 16;\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
- }\r
- else {\r
- waveFormat.wBitsPerSample = 8;\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
- }\r
- stream_.userFormat = format;\r
+//-----------------------------------------------------------------------------\r
\r
- // Update wave format structure and buffer information.\r
- waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;\r
- waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\r
- dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;\r
+void RtApiWasapi::startStream( void )\r
+{\r
+ verifyStream();\r
\r
- // If the user wants an even bigger buffer, increase the device buffer size accordingly.\r
- while ( dsPointerLeadTime * 2U > dsBufferSize )\r
- dsBufferSize *= 2;\r
+ if ( stream_.state == STREAM_RUNNING ) {\r
+ errorText_ = "RtApiWasapi::startStream: The stream is already running.";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
\r
- // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.\r
- // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );\r
- // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.\r
- result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ // update stream state\r
+ stream_.state = STREAM_RUNNING;\r
\r
- // Even though we will write to the secondary buffer, we need to\r
- // access the primary buffer to set the correct output format\r
- // (since the default is 8-bit, 22 kHz!). Setup the DS primary\r
- // buffer description.\r
- DSBUFFERDESC bufferDescription;\r
- ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );\r
- bufferDescription.dwSize = sizeof( DSBUFFERDESC );\r
- bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;\r
+ // create WASAPI stream thread\r
+ stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );\r
\r
- // Obtain the primary buffer\r
- LPDIRECTSOUNDBUFFER buffer;\r
- result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ if ( !stream_.callbackInfo.thread ) {\r
+ errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";\r
+ error( RtAudioError::THREAD_ERROR );\r
+ }\r
+ else {\r
+ SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );\r
+ ResumeThread( ( void* ) stream_.callbackInfo.thread );\r
+ }\r
+}\r
\r
- // Set the primary DS buffer sound format.\r
- result = buffer->SetFormat( &waveFormat );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+//-----------------------------------------------------------------------------\r
\r
- // Setup the secondary DS buffer description.\r
- ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );\r
- bufferDescription.dwSize = sizeof( DSBUFFERDESC );\r
- bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |\r
- DSBCAPS_GLOBALFOCUS |\r
- DSBCAPS_GETCURRENTPOSITION2 |\r
- DSBCAPS_LOCHARDWARE ); // Force hardware mixing\r
- bufferDescription.dwBufferBytes = dsBufferSize;\r
- bufferDescription.lpwfxFormat = &waveFormat;\r
+void RtApiWasapi::stopStream( void )\r
+{\r
+ verifyStream();\r
\r
- // Try to create the secondary DS buffer. If that doesn't work,\r
- // try to use software mixing. Otherwise, there's a problem.\r
- result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
- if ( FAILED( result ) ) {\r
- bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |\r
- DSBCAPS_GLOBALFOCUS |\r
- DSBCAPS_GETCURRENTPOSITION2 |\r
- DSBCAPS_LOCSOFTWARE ); // Force software mixing\r
- result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
+\r
+ // inform stream thread by setting stream state to STREAM_STOPPING\r
+ stream_.state = STREAM_STOPPING;\r
+\r
+ // wait until stream thread is stopped\r
+ while( stream_.state != STREAM_STOPPED ) {\r
+ Sleep( 1 );\r
+ }\r
+\r
+ // Wait for the last buffer to play before stopping.\r
+ Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );\r
+\r
+ // stop capture client if applicable\r
+ if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {\r
+ HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";\r
+ error( RtAudioError::DRIVER_ERROR );\r
+ return;\r
}\r
+ }\r
\r
- // Get the buffer size ... might be different from what we specified.\r
- DSBCAPS dsbcaps;\r
- dsbcaps.dwSize = sizeof( DSBCAPS );\r
- result = buffer->GetCaps( &dsbcaps );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- buffer->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ // stop render client if applicable\r
+ if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {\r
+ HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";\r
+ error( RtAudioError::DRIVER_ERROR );\r
+ return;\r
}\r
+ }\r
\r
- dsBufferSize = dsbcaps.dwBufferBytes;\r
+ // close thread handle\r
+ if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {\r
+ errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";\r
+ error( RtAudioError::THREAD_ERROR );\r
+ return;\r
+ }\r
\r
- // Lock the DS buffer\r
- LPVOID audioPtr;\r
- DWORD dataLen;\r
- result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- buffer->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ stream_.callbackInfo.thread = (ThreadHandle) NULL;\r
+}\r
\r
- // Zero the DS buffer\r
- ZeroMemory( audioPtr, dataLen );\r
+//-----------------------------------------------------------------------------\r
\r
- // Unlock the DS buffer\r
- result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- output->Release();\r
- buffer->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+void RtApiWasapi::abortStream( void )\r
+{\r
+ verifyStream();\r
\r
- ohandle = (void *) output;\r
- bhandle = (void *) buffer;\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- if ( mode == INPUT ) {\r
+ // inform stream thread by setting stream state to STREAM_STOPPING\r
+ stream_.state = STREAM_STOPPING;\r
\r
- LPDIRECTSOUNDCAPTURE input;\r
- result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ // wait until stream thread is stopped\r
+ while ( stream_.state != STREAM_STOPPED ) {\r
+ Sleep( 1 );\r
+ }\r
\r
- DSCCAPS inCaps;\r
- inCaps.dwSize = sizeof( inCaps );\r
- result = input->GetCaps( &inCaps );\r
- if ( FAILED( result ) ) {\r
- input->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ // stop capture client if applicable\r
+ if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {\r
+ HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";\r
+ error( RtAudioError::DRIVER_ERROR );\r
+ return;\r
}\r
+ }\r
\r
- // Check channel information.\r
- if ( inCaps.dwChannels < channels + firstChannel ) {\r
- errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";\r
- return FAILURE;\r
+ // stop render client if applicable\r
+ if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {\r
+ HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";\r
+ error( RtAudioError::DRIVER_ERROR );\r
+ return;\r
}\r
+ }\r
\r
- // Check format information. Use 16-bit format unless user\r
- // requests 8-bit.\r
- DWORD deviceFormats;\r
- if ( channels + firstChannel == 2 ) {\r
- deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;\r
- if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {\r
- waveFormat.wBitsPerSample = 8;\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
- }\r
- else { // assume 16-bit is supported\r
- waveFormat.wBitsPerSample = 16;\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
- }\r
- }\r
- else { // channel == 1\r
- deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;\r
- if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {\r
- waveFormat.wBitsPerSample = 8;\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
- }\r
- else { // assume 16-bit is supported\r
- waveFormat.wBitsPerSample = 16;\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
- }\r
- }\r
- stream_.userFormat = format;\r
+ // close thread handle\r
+ if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {\r
+ errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";\r
+ error( RtAudioError::THREAD_ERROR );\r
+ return;\r
+ }\r
\r
- // Update wave format structure and buffer information.\r
- waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;\r
- waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\r
- dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;\r
+ stream_.callbackInfo.thread = (ThreadHandle) NULL;\r
+}\r
\r
- // If the user wants an even bigger buffer, increase the device buffer size accordingly.\r
- while ( dsPointerLeadTime * 2U > dsBufferSize )\r
- dsBufferSize *= 2;\r
+//-----------------------------------------------------------------------------\r
\r
- // Setup the secondary DS buffer description.\r
- DSCBUFFERDESC bufferDescription;\r
- ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );\r
- bufferDescription.dwSize = sizeof( DSCBUFFERDESC );\r
- bufferDescription.dwFlags = 0;\r
- bufferDescription.dwReserved = 0;\r
- bufferDescription.dwBufferBytes = dsBufferSize;\r
- bufferDescription.lpwfxFormat = &waveFormat;\r
+bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+ unsigned int firstChannel, unsigned int sampleRate,\r
+ RtAudioFormat format, unsigned int* bufferSize,\r
+ RtAudio::StreamOptions* options )\r
+{\r
+ bool methodResult = FAILURE;\r
+ unsigned int captureDeviceCount = 0;\r
+ unsigned int renderDeviceCount = 0;\r
+\r
+ IMMDeviceCollection* captureDevices = NULL;\r
+ IMMDeviceCollection* renderDevices = NULL;\r
+ IMMDevice* devicePtr = NULL;\r
+ WAVEFORMATEX* deviceFormat = NULL;\r
+ unsigned int bufferBytes;\r
+ stream_.state = STREAM_STOPPED;\r
\r
- // Create the capture buffer.\r
- LPDIRECTSOUNDCAPTUREBUFFER buffer;\r
- result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );\r
- if ( FAILED( result ) ) {\r
- input->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ // create API Handle if not already created\r
+ if ( !stream_.apiHandle )\r
+ stream_.apiHandle = ( void* ) new WasapiHandle();\r
+\r
+ // Count capture devices\r
+ errorText_.clear();\r
+ RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;\r
+ HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";\r
+ goto Exit;\r
+ }\r
+\r
+ hr = captureDevices->GetCount( &captureDeviceCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";\r
+ goto Exit;\r
+ }\r
+\r
+ // Count render devices\r
+ hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";\r
+ goto Exit;\r
+ }\r
+\r
+ hr = renderDevices->GetCount( &renderDeviceCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";\r
+ goto Exit;\r
+ }\r
+\r
+ // validate device index\r
+ if ( device >= captureDeviceCount + renderDeviceCount ) {\r
+ errorType = RtAudioError::INVALID_USE;\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";\r
+ goto Exit;\r
+ }\r
+\r
+ // determine whether index falls within capture or render devices\r
+ if ( device >= renderDeviceCount ) {\r
+ if ( mode != INPUT ) {\r
+ errorType = RtAudioError::INVALID_USE;\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";\r
+ goto Exit;\r
}\r
\r
- // Get the buffer size ... might be different from what we specified.\r
- DSCBCAPS dscbcaps;\r
- dscbcaps.dwSize = sizeof( DSCBCAPS );\r
- result = buffer->GetCaps( &dscbcaps );\r
- if ( FAILED( result ) ) {\r
- input->Release();\r
- buffer->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ // retrieve captureAudioClient from devicePtr\r
+ IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;\r
+\r
+ hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";\r
+ goto Exit;\r
}\r
\r
- dsBufferSize = dscbcaps.dwBufferBytes;\r
+ hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,\r
+ NULL, ( void** ) &captureAudioClient );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";\r
+ goto Exit;\r
+ }\r
\r
- // NOTE: We could have a problem here if this is a duplex stream\r
- // and the play and capture hardware buffer sizes are different\r
- // (I'm actually not sure if that is a problem or not).\r
- // Currently, we are not verifying that.\r
+ hr = captureAudioClient->GetMixFormat( &deviceFormat );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";\r
+ goto Exit;\r
+ }\r
\r
- // Lock the capture buffer\r
- LPVOID audioPtr;\r
- DWORD dataLen;\r
- result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- input->Release();\r
- buffer->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ stream_.nDeviceChannels[mode] = deviceFormat->nChannels;\r
+ captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );\r
+ }\r
+ else {\r
+ if ( mode != OUTPUT ) {\r
+ errorType = RtAudioError::INVALID_USE;\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";\r
+ goto Exit;\r
}\r
\r
- // Zero the buffer\r
- ZeroMemory( audioPtr, dataLen );\r
+ // retrieve renderAudioClient from devicePtr\r
+ IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;\r
\r
- // Unlock the buffer\r
- result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- input->Release();\r
- buffer->Release();\r
- errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ hr = renderDevices->Item( device, &devicePtr );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";\r
+ goto Exit;\r
}\r
\r
- ohandle = (void *) input;\r
- bhandle = (void *) buffer;\r
+ hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,\r
+ NULL, ( void** ) &renderAudioClient );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";\r
+ goto Exit;\r
+ }\r
+\r
+ hr = renderAudioClient->GetMixFormat( &deviceFormat );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";\r
+ goto Exit;\r
+ }\r
+\r
+ stream_.nDeviceChannels[mode] = deviceFormat->nChannels;\r
+ renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );\r
}\r
\r
- // Set various stream parameters\r
- DsHandle *handle = 0;\r
- stream_.nDeviceChannels[mode] = channels + firstChannel;\r
- stream_.nUserChannels[mode] = channels;\r
+ // fill stream data\r
+ if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||\r
+ ( stream_.mode == INPUT && mode == OUTPUT ) ) {\r
+ stream_.mode = DUPLEX;\r
+ }\r
+ else {\r
+ stream_.mode = mode;\r
+ }\r
+\r
+ stream_.device[mode] = device;\r
+ stream_.doByteSwap[mode] = false;\r
+ stream_.sampleRate = sampleRate;\r
stream_.bufferSize = *bufferSize;\r
+ stream_.nBuffers = 1;\r
+ stream_.nUserChannels[mode] = channels;\r
stream_.channelOffset[mode] = firstChannel;\r
- stream_.deviceInterleaved[mode] = true;\r
- if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
- else stream_.userInterleaved = true;\r
+ stream_.userFormat = format;\r
+ stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;\r
\r
- // Set flag for buffer conversion\r
+ if ( options && options->flags & RTAUDIO_NONINTERLEAVED )\r
+ stream_.userInterleaved = false;\r
+ else\r
+ stream_.userInterleaved = true;\r
+ stream_.deviceInterleaved[mode] = true;\r
+\r
+ // Set flags for buffer conversion.\r
stream_.doConvertBuffer[mode] = false;\r
- if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])\r
- stream_.doConvertBuffer[mode] = true;\r
- if (stream_.userFormat != stream_.deviceFormat[mode])\r
+ if ( stream_.userFormat != stream_.deviceFormat[mode] ||\r
+ stream_.nUserChannels != stream_.nDeviceChannels )\r
stream_.doConvertBuffer[mode] = true;\r
- if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
- stream_.nUserChannels[mode] > 1 )\r
+ else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+ stream_.nUserChannels[mode] > 1 )\r
stream_.doConvertBuffer[mode] = true;\r
\r
+ if ( stream_.doConvertBuffer[mode] )\r
+ setConvertInfo( mode, 0 );\r
+\r
// Allocate necessary internal buffers\r
- long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
- stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
- if ( stream_.userBuffer[mode] == NULL ) {\r
- errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";\r
- goto error;\r
+ bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );\r
+\r
+ stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );\r
+ if ( !stream_.userBuffer[mode] ) {\r
+ errorType = RtAudioError::MEMORY_ERROR;\r
+ errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";\r
+ goto Exit;\r
}\r
\r
- if ( stream_.doConvertBuffer[mode] ) {\r
+ if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )\r
+ stream_.callbackInfo.priority = 15;\r
+ else\r
+ stream_.callbackInfo.priority = 0;\r
\r
- bool makeBuffer = true;\r
- bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
- if ( mode == INPUT ) {\r
- if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
- unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
- if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;\r
- }\r
- }\r
+ ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback\r
+ ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode\r
\r
- if ( makeBuffer ) {\r
- bufferBytes *= *bufferSize;\r
- if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
- if ( stream_.deviceBuffer == NULL ) {\r
- errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";\r
- goto error;\r
- }\r
- }\r
- }\r
+ methodResult = SUCCESS;\r
\r
- // Allocate our DsHandle structures for the stream.\r
- if ( stream_.apiHandle == 0 ) {\r
- try {\r
- handle = new DsHandle;\r
- }\r
- catch ( std::bad_alloc& ) {\r
- errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";\r
- goto error;\r
- }\r
+Exit:\r
+ //clean up\r
+ SAFE_RELEASE( captureDevices );\r
+ SAFE_RELEASE( renderDevices );\r
+ SAFE_RELEASE( devicePtr );\r
+ CoTaskMemFree( deviceFormat );\r
\r
- // Create a manual-reset event.\r
- handle->condition = CreateEvent( NULL, // no security\r
- TRUE, // manual-reset\r
- FALSE, // non-signaled initially\r
- NULL ); // unnamed\r
- stream_.apiHandle = (void *) handle;\r
- }\r
- else\r
- handle = (DsHandle *) stream_.apiHandle;\r
- handle->id[mode] = ohandle;\r
- handle->buffer[mode] = bhandle;\r
- handle->dsBufferSize[mode] = dsBufferSize;\r
- handle->dsPointerLeadTime[mode] = dsPointerLeadTime;\r
+ // if method failed, close the stream\r
+ if ( methodResult == FAILURE )\r
+ closeStream();\r
\r
- stream_.device[mode] = device;\r
- stream_.state = STREAM_STOPPED;\r
- if ( stream_.mode == OUTPUT && mode == INPUT )\r
- // We had already set up an output stream.\r
- stream_.mode = DUPLEX;\r
- else\r
- stream_.mode = mode;\r
- stream_.nBuffers = nBuffers;\r
- stream_.sampleRate = sampleRate;\r
+ if ( !errorText_.empty() )\r
+ error( errorType );\r
+ return methodResult;\r
+}\r
\r
- // Setup the buffer conversion information structure.\r
- if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+//=============================================================================\r
\r
- // Setup the callback thread.\r
- if ( stream_.callbackInfo.isRunning == false ) {\r
- unsigned threadId;\r
- stream_.callbackInfo.isRunning = true;\r
- stream_.callbackInfo.object = (void *) this;\r
- stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,\r
- &stream_.callbackInfo, 0, &threadId );\r
- if ( stream_.callbackInfo.thread == 0 ) {\r
- errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";\r
- goto error;\r
- }\r
+DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )\r
+{\r
+ if ( wasapiPtr )\r
+ ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();\r
\r
- // Boost DS thread priority\r
- SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );\r
- }\r
- return SUCCESS;\r
+ return 0;\r
+}\r
\r
- error:\r
- if ( handle ) {\r
- if ( handle->buffer[0] ) { // the object pointer can be NULL and valid\r
- LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];\r
- LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
- if ( buffer ) buffer->Release();\r
- object->Release();\r
- }\r
- if ( handle->buffer[1] ) {\r
- LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];\r
- LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
- if ( buffer ) buffer->Release();\r
- object->Release();\r
- }\r
- CloseHandle( handle->condition );\r
- delete handle;\r
- stream_.apiHandle = 0;\r
- }\r
+DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )\r
+{\r
+ if ( wasapiPtr )\r
+ ( ( RtApiWasapi* ) wasapiPtr )->stopStream();\r
\r
- for ( int i=0; i<2; i++ ) {\r
- if ( stream_.userBuffer[i] ) {\r
- free( stream_.userBuffer[i] );\r
- stream_.userBuffer[i] = 0;\r
- }\r
- }\r
+ return 0;\r
+}\r
\r
- if ( stream_.deviceBuffer ) {\r
- free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = 0;\r
- }\r
+DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )\r
+{\r
+ if ( wasapiPtr )\r
+ ( ( RtApiWasapi* ) wasapiPtr )->abortStream();\r
\r
- return FAILURE;\r
+ return 0;\r
}\r
\r
-void RtApiDs :: closeStream()\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::wasapiThread()\r
{\r
- if ( stream_.state == STREAM_CLOSED ) {\r
- errorText_ = "RtApiDs::closeStream(): no open stream to close!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
+ // as this is a new thread, we must CoInitialize it\r
+ CoInitialize( NULL );\r
\r
- // Stop the callback thread.\r
- stream_.callbackInfo.isRunning = false;\r
- WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );\r
- CloseHandle( (HANDLE) stream_.callbackInfo.thread );\r
+ HRESULT hr;\r
\r
- DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
- if ( handle ) {\r
- if ( handle->buffer[0] ) { // the object pointer can be NULL and valid\r
- LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];\r
- LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
- if ( buffer ) {\r
- buffer->Stop();\r
- buffer->Release();\r
+ IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;\r
+ IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;\r
+ IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;\r
+ IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;\r
+ HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;\r
+ HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;\r
+\r
+ WAVEFORMATEX* captureFormat = NULL;\r
+ WAVEFORMATEX* renderFormat = NULL;\r
+ float captureSrRatio = 0.0f;\r
+ float renderSrRatio = 0.0f;\r
+ WasapiBuffer captureBuffer;\r
+ WasapiBuffer renderBuffer;\r
+\r
+ // declare local stream variables\r
+ RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;\r
+ BYTE* streamBuffer = NULL;\r
+ unsigned long captureFlags = 0;\r
+ unsigned int bufferFrameCount = 0;\r
+ unsigned int numFramesPadding = 0;\r
+ unsigned int convBufferSize = 0;\r
+ bool callbackPushed = false;\r
+ bool callbackPulled = false;\r
+ bool callbackStopped = false;\r
+ int callbackResult = 0;\r
+\r
+ // convBuffer is used to store converted buffers between WASAPI and the user\r
+ char* convBuffer = NULL;\r
+ unsigned int convBuffSize = 0;\r
+ unsigned int deviceBuffSize = 0;\r
+\r
+ errorText_.clear();\r
+ RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;\r
+\r
+ // Attempt to assign "Pro Audio" characteristic to thread\r
+ HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );\r
+ if ( AvrtDll ) {\r
+ DWORD taskIndex = 0;\r
+ TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = ( TAvSetMmThreadCharacteristicsPtr ) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );\r
+ AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );\r
+ FreeLibrary( AvrtDll );\r
+ }\r
+\r
+ // start capture stream if applicable\r
+ if ( captureAudioClient ) {\r
+ hr = captureAudioClient->GetMixFormat( &captureFormat );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";\r
+ goto Exit;\r
+ }\r
+\r
+ captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );\r
+\r
+ // initialize capture stream according to desire buffer size\r
+ float desiredBufferSize = stream_.bufferSize * captureSrRatio;\r
+ REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / captureFormat->nSamplesPerSec );\r
+\r
+ if ( !captureClient ) {\r
+ hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,\r
+ AUDCLNT_STREAMFLAGS_EVENTCALLBACK,\r
+ desiredBufferPeriod,\r
+ desiredBufferPeriod,\r
+ captureFormat,\r
+ NULL );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";\r
+ goto Exit;\r
}\r
- object->Release();\r
- }\r
- if ( handle->buffer[1] ) {\r
- LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];\r
- LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
- if ( buffer ) {\r
- buffer->Stop();\r
- buffer->Release();\r
+\r
+ hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),\r
+ ( void** ) &captureClient );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";\r
+ goto Exit;\r
}\r
- object->Release();\r
+\r
+ // configure captureEvent to trigger on every available capture buffer\r
+ captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
+ if ( !captureEvent ) {\r
+ errorType = RtAudioError::SYSTEM_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";\r
+ goto Exit;\r
+ }\r
+\r
+ hr = captureAudioClient->SetEventHandle( captureEvent );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";\r
+ goto Exit;\r
+ }\r
+\r
+ ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;\r
+ ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;\r
}\r
- CloseHandle( handle->condition );\r
- delete handle;\r
- stream_.apiHandle = 0;\r
- }\r
\r
- for ( int i=0; i<2; i++ ) {\r
- if ( stream_.userBuffer[i] ) {\r
- free( stream_.userBuffer[i] );\r
- stream_.userBuffer[i] = 0;\r
+ unsigned int inBufferSize = 0;\r
+ hr = captureAudioClient->GetBufferSize( &inBufferSize );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";\r
+ goto Exit;\r
}\r
- }\r
\r
- if ( stream_.deviceBuffer ) {\r
- free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = 0;\r
- }\r
+ // scale outBufferSize according to stream->user sample rate ratio\r
+ unsigned int outBufferSize = ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];\r
+ inBufferSize *= stream_.nDeviceChannels[INPUT];\r
\r
- stream_.mode = UNINITIALIZED;\r
- stream_.state = STREAM_CLOSED;\r
-}\r
+ // set captureBuffer size\r
+ captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );\r
\r
-void RtApiDs :: startStream()\r
-{\r
- verifyStream();\r
- if ( stream_.state == STREAM_RUNNING ) {\r
- errorText_ = "RtApiDs::startStream(): the stream is already running!";\r
- error( RtError::WARNING );\r
- return;\r
+ // reset the capture stream\r
+ hr = captureAudioClient->Reset();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";\r
+ goto Exit;\r
+ }\r
+\r
+ // start the capture stream\r
+ hr = captureAudioClient->Start();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";\r
+ goto Exit;\r
+ }\r
}\r
\r
- //MUTEX_LOCK( &stream_.mutex );\r
- \r
- DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+ // start render stream if applicable\r
+ if ( renderAudioClient ) {\r
+ hr = renderAudioClient->GetMixFormat( &renderFormat );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";\r
+ goto Exit;\r
+ }\r
\r
- // Increase scheduler frequency on lesser windows (a side-effect of\r
- // increasing timer accuracy). On greater windows (Win2K or later),\r
- // this is already in effect.\r
- timeBeginPeriod( 1 ); \r
+ renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );\r
\r
- buffersRolling = false;\r
- duplexPrerollBytes = 0;\r
+ // initialize render stream according to desire buffer size\r
+ float desiredBufferSize = stream_.bufferSize * renderSrRatio;\r
+ REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / renderFormat->nSamplesPerSec );\r
\r
- if ( stream_.mode == DUPLEX ) {\r
- // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.\r
- duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );\r
- }\r
+ if ( !renderClient ) {\r
+ hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,\r
+ AUDCLNT_STREAMFLAGS_EVENTCALLBACK,\r
+ desiredBufferPeriod,\r
+ desiredBufferPeriod,\r
+ renderFormat,\r
+ NULL );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";\r
+ goto Exit;\r
+ }\r
\r
- HRESULT result = 0;\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),\r
+ ( void** ) &renderClient );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";\r
+ goto Exit;\r
+ }\r
\r
- LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
- result = buffer->Play( 0, 0, DSBPLAY_LOOPING );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
- }\r
+ // configure renderEvent to trigger on every available render buffer\r
+ renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
+ if ( !renderEvent ) {\r
+ errorType = RtAudioError::SYSTEM_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";\r
+ goto Exit;\r
+ }\r
\r
- if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+ hr = renderAudioClient->SetEventHandle( renderEvent );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";\r
+ goto Exit;\r
+ }\r
\r
- LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
- result = buffer->Start( DSCBSTART_LOOPING );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
- }\r
+ ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;\r
+ ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;\r
+ }\r
+\r
+ unsigned int outBufferSize = 0;\r
+ hr = renderAudioClient->GetBufferSize( &outBufferSize );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";\r
+ goto Exit;\r
+ }\r
+\r
+ // scale inBufferSize according to user->stream sample rate ratio\r
+ unsigned int inBufferSize = ( unsigned int ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];\r
+ outBufferSize *= stream_.nDeviceChannels[OUTPUT];\r
+\r
+ // set renderBuffer size\r
+ renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );\r
+\r
+ // reset the render stream\r
+ hr = renderAudioClient->Reset();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";\r
+ goto Exit;\r
+ }\r
+\r
+ // start the render stream\r
+ hr = renderAudioClient->Start();\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";\r
+ goto Exit;\r
+ }\r
+ }\r
+\r
+ if ( stream_.mode == INPUT ) {\r
+ convBuffSize = ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );\r
+ deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );\r
+ }\r
+ else if ( stream_.mode == OUTPUT ) {\r
+ convBuffSize = ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );\r
+ deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );\r
+ }\r
+ else if ( stream_.mode == DUPLEX ) {\r
+ convBuffSize = std::max( ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),\r
+ ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );\r
+ deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),\r
+ stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );\r
+ }\r
+\r
+ convBuffer = ( char* ) malloc( convBuffSize );\r
+ stream_.deviceBuffer = ( char* ) malloc( deviceBuffSize );\r
+ if ( !convBuffer || !stream_.deviceBuffer ) {\r
+ errorType = RtAudioError::MEMORY_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";\r
+ goto Exit;\r
+ }\r
+\r
+ // stream process loop\r
+ while ( stream_.state != STREAM_STOPPING ) {\r
+ if ( !callbackPulled ) {\r
+ // Callback Input\r
+ // ==============\r
+ // 1. Pull callback buffer from inputBuffer\r
+ // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count\r
+ // Convert callback buffer to user format\r
+\r
+ if ( captureAudioClient ) {\r
+ // Pull callback buffer from inputBuffer\r
+ callbackPulled = captureBuffer.pullBuffer( convBuffer,\r
+ ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT],\r
+ stream_.deviceFormat[INPUT] );\r
+\r
+ if ( callbackPulled ) {\r
+ // Convert callback buffer to user sample rate\r
+ convertBufferWasapi( stream_.deviceBuffer,\r
+ convBuffer,\r
+ stream_.nDeviceChannels[INPUT],\r
+ captureFormat->nSamplesPerSec,\r
+ stream_.sampleRate,\r
+ ( unsigned int ) ( stream_.bufferSize * captureSrRatio ),\r
+ convBufferSize,\r
+ stream_.deviceFormat[INPUT] );\r
+\r
+ if ( stream_.doConvertBuffer[INPUT] ) {\r
+ // Convert callback buffer to user format\r
+ convertBuffer( stream_.userBuffer[INPUT],\r
+ stream_.deviceBuffer,\r
+ stream_.convertInfo[INPUT] );\r
+ }\r
+ else {\r
+ // no further conversion, simple copy deviceBuffer to userBuffer\r
+ memcpy( stream_.userBuffer[INPUT],\r
+ stream_.deviceBuffer,\r
+ stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );\r
+ }\r
+ }\r
+ }\r
+ else {\r
+ // if there is no capture stream, set callbackPulled flag\r
+ callbackPulled = true;\r
+ }\r
\r
- handle->drainCounter = 0;\r
- handle->internalDrain = false;\r
- ResetEvent( handle->condition );\r
- stream_.state = STREAM_RUNNING;\r
+ // Execute Callback\r
+ // ================\r
+ // 1. Execute user callback method\r
+ // 2. Handle return value from callback\r
+\r
+ // if callback has not requested the stream to stop\r
+ if ( callbackPulled && !callbackStopped ) {\r
+ // Execute user callback method\r
+ callbackResult = callback( stream_.userBuffer[OUTPUT],\r
+ stream_.userBuffer[INPUT],\r
+ stream_.bufferSize,\r
+ getStreamTime(),\r
+ captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,\r
+ stream_.callbackInfo.userData );\r
+\r
+ // Handle return value from callback\r
+ if ( callbackResult == 1 ) {\r
+ // instantiate a thread to stop this thread\r
+ HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );\r
+ if ( !threadHandle ) {\r
+ errorType = RtAudioError::THREAD_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";\r
+ goto Exit;\r
+ }\r
+ else if ( !CloseHandle( threadHandle ) ) {\r
+ errorType = RtAudioError::THREAD_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";\r
+ goto Exit;\r
+ }\r
\r
- unlock:\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
+ callbackStopped = true;\r
+ }\r
+ else if ( callbackResult == 2 ) {\r
+ // instantiate a thread to stop this thread\r
+ HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );\r
+ if ( !threadHandle ) {\r
+ errorType = RtAudioError::THREAD_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";\r
+ goto Exit;\r
+ }\r
+ else if ( !CloseHandle( threadHandle ) ) {\r
+ errorType = RtAudioError::THREAD_ERROR;\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";\r
+ goto Exit;\r
+ }\r
\r
- if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );\r
-}\r
+ callbackStopped = true;\r
+ }\r
+ }\r
+ }\r
\r
-void RtApiDs :: stopStream()\r
-{\r
- verifyStream();\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
+ // Callback Output\r
+ // ===============\r
+ // 1. Convert callback buffer to stream format\r
+ // 2. Convert callback buffer to stream sample rate and channel count\r
+ // 3. Push callback buffer into outputBuffer\r
\r
- /*\r
- MUTEX_LOCK( &stream_.mutex );\r
+ if ( renderAudioClient && callbackPulled ) {\r
+ if ( stream_.doConvertBuffer[OUTPUT] ) {\r
+ // Convert callback buffer to stream format\r
+ convertBuffer( stream_.deviceBuffer,\r
+ stream_.userBuffer[OUTPUT],\r
+ stream_.convertInfo[OUTPUT] );\r
\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- return;\r
- }\r
- */\r
+ }\r
\r
- HRESULT result = 0;\r
- LPVOID audioPtr;\r
- DWORD dataLen;\r
- DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
- if ( handle->drainCounter == 0 ) {\r
- handle->drainCounter = 2;\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
- WaitForSingleObject( handle->condition, INFINITE ); // block until signaled\r
- //ResetEvent( handle->condition );\r
- // MUTEX_LOCK( &stream_.mutex );\r
+ // Convert callback buffer to stream sample rate\r
+ convertBufferWasapi( convBuffer,\r
+ stream_.deviceBuffer,\r
+ stream_.nDeviceChannels[OUTPUT],\r
+ stream_.sampleRate,\r
+ renderFormat->nSamplesPerSec,\r
+ stream_.bufferSize,\r
+ convBufferSize,\r
+ stream_.deviceFormat[OUTPUT] );\r
+\r
+ // Push callback buffer into outputBuffer\r
+ callbackPushed = renderBuffer.pushBuffer( convBuffer,\r
+ convBufferSize * stream_.nDeviceChannels[OUTPUT],\r
+ stream_.deviceFormat[OUTPUT] );\r
+ }\r
+ else {\r
+ // if there is no render stream, set callbackPushed flag\r
+ callbackPushed = true;\r
}\r
\r
- stream_.state = STREAM_STOPPED;\r
+ // Stream Capture\r
+ // ==============\r
+ // 1. Get capture buffer from stream\r
+ // 2. Push capture buffer into inputBuffer\r
+ // 3. If 2. was successful: Release capture buffer\r
\r
- // Stop the buffer and clear memory\r
- LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
- result = buffer->Stop();\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
+ if ( captureAudioClient ) {\r
+ // if the callback input buffer was not pulled from captureBuffer, wait for next capture event\r
+ if ( !callbackPulled ) {\r
+ WaitForSingleObject( captureEvent, INFINITE );\r
+ }\r
\r
- // Lock the buffer and clear it so that if we start to play again,\r
- // we won't have old data playing.\r
- result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
+ // Get capture buffer from stream\r
+ hr = captureClient->GetBuffer( &streamBuffer,\r
+ &bufferFrameCount,\r
+ &captureFlags, NULL, NULL );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";\r
+ goto Exit;\r
+ }\r
+\r
+ if ( bufferFrameCount != 0 ) {\r
+ // Push capture buffer into inputBuffer\r
+ if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,\r
+ bufferFrameCount * stream_.nDeviceChannels[INPUT],\r
+ stream_.deviceFormat[INPUT] ) )\r
+ {\r
+ // Release capture buffer\r
+ hr = captureClient->ReleaseBuffer( bufferFrameCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";\r
+ goto Exit;\r
+ }\r
+ }\r
+ else\r
+ {\r
+ // Inform WASAPI that capture was unsuccessful\r
+ hr = captureClient->ReleaseBuffer( 0 );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";\r
+ goto Exit;\r
+ }\r
+ }\r
+ }\r
+ else\r
+ {\r
+ // Inform WASAPI that capture was unsuccessful\r
+ hr = captureClient->ReleaseBuffer( 0 );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";\r
+ goto Exit;\r
+ }\r
+ }\r
}\r
\r
- // Zero the DS buffer\r
- ZeroMemory( audioPtr, dataLen );\r
+ // Stream Render\r
+ // =============\r
+ // 1. Get render buffer from stream\r
+ // 2. Pull next buffer from outputBuffer\r
+ // 3. If 2. was successful: Fill render buffer with next buffer\r
+ // Release render buffer\r
\r
- // Unlock the DS buffer\r
- result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
+ if ( renderAudioClient ) {\r
+ // if the callback output buffer was not pushed to renderBuffer, wait for next render event\r
+ if ( callbackPulled && !callbackPushed ) {\r
+ WaitForSingleObject( renderEvent, INFINITE );\r
+ }\r
\r
- // If we start playing again, we must begin at beginning of buffer.\r
- handle->bufferPointer[0] = 0;\r
- }\r
+ // Get render buffer from stream\r
+ hr = renderAudioClient->GetBufferSize( &bufferFrameCount );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";\r
+ goto Exit;\r
+ }\r
\r
- if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
- LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
- audioPtr = NULL;\r
- dataLen = 0;\r
+ hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";\r
+ goto Exit;\r
+ }\r
\r
- stream_.state = STREAM_STOPPED;\r
+ bufferFrameCount -= numFramesPadding;\r
\r
- result = buffer->Stop();\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
+ if ( bufferFrameCount != 0 ) {\r
+ hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";\r
+ goto Exit;\r
+ }\r
\r
- // Lock the buffer and clear it so that if we start to play again,\r
- // we won't have old data playing.\r
- result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
+ // Pull next buffer from outputBuffer\r
+ // Fill render buffer with next buffer\r
+ if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,\r
+ bufferFrameCount * stream_.nDeviceChannels[OUTPUT],\r
+ stream_.deviceFormat[OUTPUT] ) )\r
+ {\r
+ // Release render buffer\r
+ hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";\r
+ goto Exit;\r
+ }\r
+ }\r
+ else\r
+ {\r
+ // Inform WASAPI that render was unsuccessful\r
+ hr = renderClient->ReleaseBuffer( 0, 0 );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";\r
+ goto Exit;\r
+ }\r
+ }\r
+ }\r
+ else\r
+ {\r
+ // Inform WASAPI that render was unsuccessful\r
+ hr = renderClient->ReleaseBuffer( 0, 0 );\r
+ if ( FAILED( hr ) ) {\r
+ errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";\r
+ goto Exit;\r
+ }\r
+ }\r
}\r
\r
- // Zero the DS buffer\r
- ZeroMemory( audioPtr, dataLen );\r
-\r
- // Unlock the DS buffer\r
- result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
+ // if the callback buffer was pushed renderBuffer reset callbackPulled flag\r
+ if ( callbackPushed ) {\r
+ callbackPulled = false;\r
+ // tick stream time\r
+ RtApi::tickStreamTime();\r
}\r
\r
- // If we start recording again, we must begin at beginning of buffer.\r
- handle->bufferPointer[1] = 0;\r
}\r
\r
- unlock:\r
- timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
+Exit:\r
+ // clean up\r
+ CoTaskMemFree( captureFormat );\r
+ CoTaskMemFree( renderFormat );\r
\r
- if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );\r
-}\r
+ free ( convBuffer );\r
\r
-void RtApiDs :: abortStream()\r
-{\r
- verifyStream();\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
+ CoUninitialize();\r
\r
- DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
- handle->drainCounter = 2;\r
+ // update stream state\r
+ stream_.state = STREAM_STOPPED;\r
\r
- stopStream();\r
+ if ( errorText_.empty() )\r
+ return;\r
+ else\r
+ error( errorType );\r
}\r
\r
-void RtApiDs :: callbackEvent()\r
-{\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- Sleep( 50 ); // sleep 50 milliseconds\r
- return;\r
- }\r
+//******************** End of __WINDOWS_WASAPI__ *********************//\r
+#endif\r
\r
- if ( stream_.state == STREAM_CLOSED ) {\r
- errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
\r
- CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;\r
- DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+#if defined(__WINDOWS_DS__) // Windows DirectSound API\r
\r
- // Check if we were draining the stream and signal is finished.\r
- if ( handle->drainCounter > stream_.nBuffers + 2 ) {\r
- if ( handle->internalDrain == false )\r
- SetEvent( handle->condition );\r
- else\r
- stopStream();\r
- return;\r
- }\r
+// Modified by Robin Davies, October 2005\r
+// - Improvements to DirectX pointer chasing. \r
+// - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.\r
+// - Auto-call CoInitialize for DSOUND and ASIO platforms.\r
+// Various revisions for RtAudio 4.0 by Gary Scavone, April 2007\r
+// Changed device query structure for RtAudio 4.0.7, January 2010\r
\r
- /*\r
- MUTEX_LOCK( &stream_.mutex );\r
+#include <dsound.h>\r
+#include <assert.h>\r
+#include <algorithm>\r
\r
- // The state might change while waiting on a mutex.\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- return;\r
- }\r
- */\r
+#if defined(__MINGW32__)\r
+ // missing from latest mingw winapi\r
+#define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */\r
+#define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */\r
+#define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */\r
+#define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */\r
+#endif\r
\r
- // Invoke user callback to get fresh output data UNLESS we are\r
- // draining stream.\r
- if ( handle->drainCounter == 0 ) {\r
- RtAudioCallback callback = (RtAudioCallback) info->callback;\r
- double streamTime = getStreamTime();\r
- RtAudioStreamStatus status = 0;\r
- if ( stream_.mode != INPUT && handle->xrun[0] == true ) {\r
- status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
- handle->xrun[0] = false;\r
- }\r
- if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {\r
- status |= RTAUDIO_INPUT_OVERFLOW;\r
- handle->xrun[1] = false;\r
- }\r
- int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
- stream_.bufferSize, streamTime, status, info->userData );\r
- if ( cbReturnValue == 2 ) {\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
- handle->drainCounter = 2;\r
- abortStream();\r
- return;\r
- }\r
- else if ( cbReturnValue == 1 ) {\r
- handle->drainCounter = 1;\r
- handle->internalDrain = true;\r
- }\r
- }\r
+#define MINIMUM_DEVICE_BUFFER_SIZE 32768\r
\r
- HRESULT result;\r
- DWORD currentWritePointer, safeWritePointer;\r
- DWORD currentReadPointer, safeReadPointer;\r
- UINT nextWritePointer;\r
+#ifdef _MSC_VER // if Microsoft Visual C++\r
+#pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.\r
+#endif\r
\r
- LPVOID buffer1 = NULL;\r
- LPVOID buffer2 = NULL;\r
- DWORD bufferSize1 = 0;\r
- DWORD bufferSize2 = 0;\r
+static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )\r
+{\r
+ if ( pointer > bufferSize ) pointer -= bufferSize;\r
+ if ( laterPointer < earlierPointer ) laterPointer += bufferSize;\r
+ if ( pointer < earlierPointer ) pointer += bufferSize;\r
+ return pointer >= earlierPointer && pointer < laterPointer;\r
+}\r
\r
- char *buffer;\r
- long bufferBytes;\r
+// A structure to hold various information related to the DirectSound\r
+// API implementation.\r
+struct DsHandle {\r
+ unsigned int drainCounter; // Tracks callback counts when draining\r
+ bool internalDrain; // Indicates if stop is initiated from callback or not.\r
+ void *id[2];\r
+ void *buffer[2];\r
+ bool xrun[2];\r
+ UINT bufferPointer[2]; \r
+ DWORD dsBufferSize[2];\r
+ DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.\r
+ HANDLE condition;\r
\r
- if ( buffersRolling == false ) {\r
- if ( stream_.mode == DUPLEX ) {\r
- //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );\r
+ DsHandle()\r
+ :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }\r
+};\r
\r
- // It takes a while for the devices to get rolling. As a result,\r
- // there's no guarantee that the capture and write device pointers\r
- // will move in lockstep. Wait here for both devices to start\r
- // rolling, and then set our buffer pointers accordingly.\r
- // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600\r
- // bytes later than the write buffer.\r
+// Declarations for utility functions, callbacks, and structures\r
+// specific to the DirectSound implementation.\r
+static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
+ LPCTSTR description,\r
+ LPCTSTR module,\r
+ LPVOID lpContext );\r
\r
- // Stub: a serious risk of having a pre-emptive scheduling round\r
- // take place between the two GetCurrentPosition calls... but I'm\r
- // really not sure how to solve the problem. Temporarily boost to\r
- // Realtime priority, maybe; but I'm not sure what priority the\r
- // DirectSound service threads run at. We *should* be roughly\r
- // within a ms or so of correct.\r
+static const char* getErrorString( int code );\r
\r
- LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
- LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+static unsigned __stdcall callbackHandler( void *ptr );\r
\r
- DWORD startSafeWritePointer, startSafeReadPointer;\r
+struct DsDevice {\r
+ LPGUID id[2];\r
+ bool validId[2];\r
+ bool found;\r
+ std::string name;\r
\r
- result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- while ( true ) {\r
- result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;\r
- Sleep( 1 );\r
- }\r
+ DsDevice()\r
+ : found(false) { validId[0] = false; validId[1] = false; }\r
+};\r
\r
- //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );\r
+struct DsProbeData {\r
+ bool isInput;\r
+ std::vector<struct DsDevice>* dsDevices;\r
+};\r
\r
- handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];\r
- if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];\r
- handle->bufferPointer[1] = safeReadPointer;\r
- }\r
- else if ( stream_.mode == OUTPUT ) {\r
+RtApiDs :: RtApiDs()\r
+{\r
+ // Dsound will run both-threaded. If CoInitialize fails, then just\r
+ // accept whatever the mainline chose for a threading model.\r
+ coInitialized_ = false;\r
+ HRESULT hr = CoInitialize( NULL );\r
+ if ( !FAILED( hr ) ) coInitialized_ = true;\r
+}\r
\r
- // Set the proper nextWritePosition after initial startup.\r
- LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
- result = dsWriteBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];\r
- if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];\r
- }\r
+RtApiDs :: ~RtApiDs()\r
+{\r
+ if ( coInitialized_ ) CoUninitialize(); // balanced call.\r
+ if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
\r
- buffersRolling = true;\r
- }\r
+// The DirectSound default output is always the first device.\r
+unsigned int RtApiDs :: getDefaultOutputDevice( void )\r
+{\r
+ return 0;\r
+}\r
\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
- \r
- LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+// The DirectSound default input is always the first input device,\r
+// which is the first capture device enumerated.\r
+unsigned int RtApiDs :: getDefaultInputDevice( void )\r
+{\r
+ return 0;\r
+}\r
\r
- if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
- bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];\r
- bufferBytes *= formatBytes( stream_.userFormat );\r
- memset( stream_.userBuffer[0], 0, bufferBytes );\r
- }\r
+unsigned int RtApiDs :: getDeviceCount( void )\r
+{\r
+ // Set query flag for previously found devices to false, so that we\r
+ // can check for any devices that have disappeared.\r
+ for ( unsigned int i=0; i<dsDevices.size(); i++ )\r
+ dsDevices[i].found = false;\r
\r
- // Setup parameters and do buffer conversion if necessary.\r
- if ( stream_.doConvertBuffer[0] ) {\r
- buffer = stream_.deviceBuffer;\r
- convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
- bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];\r
- bufferBytes *= formatBytes( stream_.deviceFormat[0] );\r
- }\r
- else {\r
- buffer = stream_.userBuffer[0];\r
- bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];\r
- bufferBytes *= formatBytes( stream_.userFormat );\r
- }\r
+ // Query DirectSound devices.\r
+ struct DsProbeData probeInfo;\r
+ probeInfo.isInput = false;\r
+ probeInfo.dsDevices = &dsDevices;\r
+ HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ }\r
\r
- // No byte swapping necessary in DirectSound implementation.\r
+ // Query DirectSoundCapture devices.\r
+ probeInfo.isInput = true;\r
+ result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ }\r
\r
- // Ahhh ... windoze. 16-bit data is signed but 8-bit data is\r
- // unsigned. So, we need to convert our signed 8-bit data here to\r
- // unsigned.\r
- if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )\r
- for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );\r
+ // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).\r
+ for ( unsigned int i=0; i<dsDevices.size(); ) {\r
+ if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );\r
+ else i++;\r
+ }\r
\r
- DWORD dsBufferSize = handle->dsBufferSize[0];\r
- nextWritePointer = handle->bufferPointer[0];\r
+ return static_cast<unsigned int>(dsDevices.size());\r
+}\r
\r
- DWORD endWrite, leadPointer;\r
- while ( true ) {\r
- // Find out where the read and "safe write" pointers are.\r
- result = dsBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
+RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )\r
+{\r
+ RtAudio::DeviceInfo info;\r
+ info.probed = false;\r
\r
- // We will copy our output buffer into the region between\r
- // safeWritePointer and leadPointer. If leadPointer is not\r
- // beyond the next endWrite position, wait until it is.\r
- leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];\r
- //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;\r
- if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;\r
- if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset\r
- endWrite = nextWritePointer + bufferBytes;\r
+ if ( dsDevices.size() == 0 ) {\r
+ // Force a query of all devices\r
+ getDeviceCount();\r
+ if ( dsDevices.size() == 0 ) {\r
+ errorText_ = "RtApiDs::getDeviceInfo: no devices found!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
+ }\r
+ }\r
\r
- // Check whether the entire write region is behind the play pointer.\r
- if ( leadPointer >= endWrite ) break;\r
+ if ( device >= dsDevices.size() ) {\r
+ errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
+ }\r
\r
- // If we are here, then we must wait until the leadPointer advances\r
- // beyond the end of our next write region. We use the\r
- // Sleep() function to suspend operation until that happens.\r
- double millis = ( endWrite - leadPointer ) * 1000.0;\r
- millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);\r
- if ( millis < 1.0 ) millis = 1.0;\r
- Sleep( (DWORD) millis );\r
- }\r
+ HRESULT result;\r
+ if ( dsDevices[ device ].validId[0] == false ) goto probeInput;\r
\r
- if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )\r
- || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) { \r
- // We've strayed into the forbidden zone ... resync the read pointer.\r
- handle->xrun[0] = true;\r
- nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;\r
- if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;\r
- handle->bufferPointer[0] = nextWritePointer;\r
- endWrite = nextWritePointer + bufferBytes;\r
- }\r
+ LPDIRECTSOUND output;\r
+ DSCAPS outCaps;\r
+ result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto probeInput;\r
+ }\r
\r
- // Lock free space in the buffer\r
- result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,\r
- &bufferSize1, &buffer2, &bufferSize2, 0 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
+ outCaps.dwSize = sizeof( outCaps );\r
+ result = output->GetCaps( &outCaps );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto probeInput;\r
+ }\r
\r
- // Copy our buffer into the DS buffer\r
- CopyMemory( buffer1, buffer, bufferSize1 );\r
- if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );\r
+ // Get output channel information.\r
+ info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;\r
\r
- // Update our buffer offset and unlock sound buffer\r
- dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;\r
- handle->bufferPointer[0] = nextWritePointer;\r
+ // Get sample rate information.\r
+ info.sampleRates.clear();\r
+ for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
+ if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&\r
+ SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {\r
+ info.sampleRates.push_back( SAMPLE_RATES[k] );\r
\r
- if ( handle->drainCounter ) {\r
- handle->drainCounter++;\r
- goto unlock;\r
+ if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = SAMPLE_RATES[k];\r
}\r
}\r
\r
- if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+ // Get format information.\r
+ if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;\r
\r
- // Setup parameters.\r
- if ( stream_.doConvertBuffer[1] ) {\r
- buffer = stream_.deviceBuffer;\r
- bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];\r
- bufferBytes *= formatBytes( stream_.deviceFormat[1] );\r
- }\r
- else {\r
- buffer = stream_.userBuffer[1];\r
- bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];\r
- bufferBytes *= formatBytes( stream_.userFormat );\r
- }\r
+ output->Release();\r
\r
- LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
- long nextReadPointer = handle->bufferPointer[1];\r
- DWORD dsBufferSize = handle->dsBufferSize[1];\r
+ if ( getDefaultOutputDevice() == device )\r
+ info.isDefaultOutput = true;\r
\r
- // Find out where the write and "safe read" pointers are.\r
- result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
+ if ( dsDevices[ device ].validId[1] == false ) {\r
+ info.name = dsDevices[ device ].name;\r
+ info.probed = true;\r
+ return info;\r
+ }\r
\r
- if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
- DWORD endRead = nextReadPointer + bufferBytes;\r
+ probeInput:\r
\r
- // Handling depends on whether we are INPUT or DUPLEX. \r
- // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,\r
- // then a wait here will drag the write pointers into the forbidden zone.\r
- // \r
- // In DUPLEX mode, rather than wait, we will back off the read pointer until \r
- // it's in a safe position. This causes dropouts, but it seems to be the only \r
- // practical way to sync up the read and write pointers reliably, given the \r
- // the very complex relationship between phase and increment of the read and write \r
- // pointers.\r
- //\r
- // In order to minimize audible dropouts in DUPLEX mode, we will\r
- // provide a pre-roll period of 0.5 seconds in which we return\r
- // zeros from the read buffer while the pointers sync up.\r
+ LPDIRECTSOUNDCAPTURE input;\r
+ result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
\r
- if ( stream_.mode == DUPLEX ) {\r
- if ( safeReadPointer < endRead ) {\r
- if ( duplexPrerollBytes <= 0 ) {\r
- // Pre-roll time over. Be more agressive.\r
- int adjustment = endRead-safeReadPointer;\r
-\r
- handle->xrun[1] = true;\r
- // Two cases:\r
- // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,\r
- // and perform fine adjustments later.\r
- // - small adjustments: back off by twice as much.\r
- if ( adjustment >= 2*bufferBytes )\r
- nextReadPointer = safeReadPointer-2*bufferBytes;\r
- else\r
- nextReadPointer = safeReadPointer-bufferBytes-adjustment;\r
+ DSCCAPS inCaps;\r
+ inCaps.dwSize = sizeof( inCaps );\r
+ result = input->GetCaps( &inCaps );\r
+ if ( FAILED( result ) ) {\r
+ input->Release();\r
+ errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
\r
- if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;\r
+ // Get input channel information.\r
+ info.inputChannels = inCaps.dwChannels;\r
\r
- }\r
- else {\r
- // In pre=roll time. Just do it.\r
- nextReadPointer = safeReadPointer - bufferBytes;\r
- while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;\r
- }\r
- endRead = nextReadPointer + bufferBytes;\r
- }\r
- }\r
- else { // mode == INPUT\r
- while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {\r
- // See comments for playback.\r
- double millis = (endRead - safeReadPointer) * 1000.0;\r
- millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);\r
- if ( millis < 1.0 ) millis = 1.0;\r
- Sleep( (DWORD) millis );\r
+ // Get sample rate and format information.\r
+ std::vector<unsigned int> rates;\r
+ if ( inCaps.dwChannels >= 2 ) {\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
\r
- // Wake up and find out where we are now.\r
- result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
- }\r
- \r
- if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
- }\r
+ if ( info.nativeFormats & RTAUDIO_SINT16 ) {\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );\r
}\r
-\r
- // Lock free space in the buffer\r
- result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,\r
- &bufferSize1, &buffer2, &bufferSize2, 0 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
+ else if ( info.nativeFormats & RTAUDIO_SINT8 ) {\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );\r
}\r
+ }\r
+ else if ( inCaps.dwChannels == 1 ) {\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
\r
- if ( duplexPrerollBytes <= 0 ) {\r
- // Copy our buffer into the DS buffer\r
- CopyMemory( buffer, buffer1, bufferSize1 );\r
- if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );\r
- }\r
- else {\r
- memset( buffer, 0, bufferSize1 );\r
- if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );\r
- duplexPrerollBytes -= bufferSize1 + bufferSize2;\r
+ if ( info.nativeFormats & RTAUDIO_SINT16 ) {\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );\r
}\r
-\r
- // Update our buffer offset and unlock sound buffer\r
- nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;\r
- dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );\r
- if ( FAILED( result ) ) {\r
- errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";\r
- errorText_ = errorStream_.str();\r
- error( RtError::SYSTEM_ERROR );\r
+ else if ( info.nativeFormats & RTAUDIO_SINT8 ) {\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );\r
+ if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );\r
}\r
- handle->bufferPointer[1] = nextReadPointer;\r
-\r
- // No byte swapping necessary in DirectSound implementation.\r
-\r
- // If necessary, convert 8-bit data from unsigned to signed.\r
- if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )\r
- for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );\r
-\r
- // Do buffer conversion if necessary.\r
- if ( stream_.doConvertBuffer[1] )\r
- convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
}\r
+ else info.inputChannels = 0; // technically, this would be an error\r
\r
- unlock:\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
-\r
- RtApi::tickStreamTime();\r
-}\r
-\r
-// Definitions for utility functions and callbacks\r
-// specific to the DirectSound implementation.\r
+ input->Release();\r
\r
-extern "C" unsigned __stdcall callbackHandler( void *ptr )\r
-{\r
- CallbackInfo *info = (CallbackInfo *) ptr;\r
- RtApiDs *object = (RtApiDs *) info->object;\r
- bool* isRunning = &info->isRunning;\r
+ if ( info.inputChannels == 0 ) return info;\r
\r
- while ( *isRunning == true ) {\r
- object->callbackEvent();\r
+ // Copy the supported rates to the info structure but avoid duplication.\r
+ bool found;\r
+ for ( unsigned int i=0; i<rates.size(); i++ ) {\r
+ found = false;\r
+ for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {\r
+ if ( rates[i] == info.sampleRates[j] ) {\r
+ found = true;\r
+ break;\r
+ }\r
+ }\r
+ if ( found == false ) info.sampleRates.push_back( rates[i] );\r
}\r
+ std::sort( info.sampleRates.begin(), info.sampleRates.end() );\r
\r
- _endthreadex( 0 );\r
- return 0;\r
-}\r
-\r
-#include "tchar.h"\r
+ // If device opens for both playback and capture, we determine the channels.\r
+ if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+ info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
\r
-std::string convertTChar( LPCTSTR name )\r
-{\r
-#if defined( UNICODE ) || defined( _UNICODE )\r
- int length = WideCharToMultiByte(CP_UTF8, 0, name, -1, NULL, 0, NULL, NULL);\r
- std::string s( length, 0 );\r
- length = WideCharToMultiByte(CP_UTF8, 0, name, wcslen(name), &s[0], length, NULL, NULL);\r
-#else\r
- std::string s( name );\r
-#endif\r
+ if ( device == 0 ) info.isDefaultInput = true;\r
\r
- return s;\r
+ // Copy name and return.\r
+ info.name = dsDevices[ device ].name;\r
+ info.probed = true;\r
+ return info;\r
}\r
\r
-static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
- LPCTSTR description,\r
- LPCTSTR module,\r
- LPVOID lpContext )\r
+bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+ unsigned int firstChannel, unsigned int sampleRate,\r
+ RtAudioFormat format, unsigned int *bufferSize,\r
+ RtAudio::StreamOptions *options )\r
{\r
- bool *isInput = (bool *) lpContext;\r
-\r
- HRESULT hr;\r
- bool validDevice = false;\r
- if ( *isInput == true ) {\r
- DSCCAPS caps;\r
- LPDIRECTSOUNDCAPTURE object;\r
-\r
- hr = DirectSoundCaptureCreate( lpguid, &object, NULL );\r
- if ( hr != DS_OK ) return TRUE;\r
-\r
- caps.dwSize = sizeof(caps);\r
- hr = object->GetCaps( &caps );\r
- if ( hr == DS_OK ) {\r
- if ( caps.dwChannels > 0 && caps.dwFormats > 0 )\r
- validDevice = true;\r
- }\r
- object->Release();\r
+ if ( channels + firstChannel > 2 ) {\r
+ errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";\r
+ return FAILURE;\r
}\r
- else {\r
- DSCAPS caps;\r
- LPDIRECTSOUND object;\r
- hr = DirectSoundCreate( lpguid, &object, NULL );\r
- if ( hr != DS_OK ) return TRUE;\r
\r
- caps.dwSize = sizeof(caps);\r
- hr = object->GetCaps( &caps );\r
- if ( hr == DS_OK ) {\r
- if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )\r
- validDevice = true;\r
- }\r
- object->Release();\r
+ size_t nDevices = dsDevices.size();\r
+ if ( nDevices == 0 ) {\r
+ // This should not happen because a check is made before this function is called.\r
+ errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";\r
+ return FAILURE;\r
}\r
\r
- // If good device, then save its name and guid.\r
- std::string name = convertTChar( description );\r
- if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )\r
- name = "Default Device";\r
- if ( validDevice ) {\r
- for ( unsigned int i=0; i<dsDevices.size(); i++ ) {\r
- if ( dsDevices[i].name == name ) {\r
- dsDevices[i].found = true;\r
- if ( *isInput ) {\r
- dsDevices[i].id[1] = lpguid;\r
- dsDevices[i].validId[1] = true;\r
- }\r
- else {\r
- dsDevices[i].id[0] = lpguid;\r
- dsDevices[i].validId[0] = true;\r
- }\r
- return TRUE;\r
- }\r
- }\r
+ if ( device >= nDevices ) {\r
+ // This should not happen because a check is made before this function is called.\r
+ errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";\r
+ return FAILURE;\r
+ }\r
\r
- DsDevice device;\r
- device.name = name;\r
- device.found = true;\r
- if ( *isInput ) {\r
- device.id[1] = lpguid;\r
- device.validId[1] = true;\r
+ if ( mode == OUTPUT ) {\r
+ if ( dsDevices[ device ].validId[0] == false ) {\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
}\r
- else {\r
- device.id[0] = lpguid;\r
- device.validId[0] = true;\r
+ }\r
+ else { // mode == INPUT\r
+ if ( dsDevices[ device ].validId[1] == false ) {\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
}\r
- dsDevices.push_back( device );\r
}\r
\r
- return TRUE;\r
-}\r
-\r
-static const char* getErrorString( int code )\r
-{\r
- switch ( code ) {\r
-\r
- case DSERR_ALLOCATED:\r
- return "Already allocated";\r
+ // According to a note in PortAudio, using GetDesktopWindow()\r
+ // instead of GetForegroundWindow() is supposed to avoid problems\r
+ // that occur when the application's window is not the foreground\r
+ // window. Also, if the application window closes before the\r
+ // DirectSound buffer, DirectSound can crash. In the past, I had\r
+ // problems when using GetDesktopWindow() but it seems fine now\r
+ // (January 2010). I'll leave it commented here.\r
+ // HWND hWnd = GetForegroundWindow();\r
+ HWND hWnd = GetDesktopWindow();\r
\r
- case DSERR_CONTROLUNAVAIL:\r
- return "Control unavailable";\r
+ // Check the numberOfBuffers parameter and limit the lowest value to\r
+ // two. This is a judgement call and a value of two is probably too\r
+ // low for capture, but it should work for playback.\r
+ int nBuffers = 0;\r
+ if ( options ) nBuffers = options->numberOfBuffers;\r
+ if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;\r
+ if ( nBuffers < 2 ) nBuffers = 3;\r
\r
- case DSERR_INVALIDPARAM:\r
- return "Invalid parameter";\r
+ // Check the lower range of the user-specified buffer size and set\r
+ // (arbitrarily) to a lower bound of 32.\r
+ if ( *bufferSize < 32 ) *bufferSize = 32;\r
\r
- case DSERR_INVALIDCALL:\r
- return "Invalid call";\r
+ // Create the wave format structure. The data format setting will\r
+ // be determined later.\r
+ WAVEFORMATEX waveFormat;\r
+ ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );\r
+ waveFormat.wFormatTag = WAVE_FORMAT_PCM;\r
+ waveFormat.nChannels = channels + firstChannel;\r
+ waveFormat.nSamplesPerSec = (unsigned long) sampleRate;\r
\r
- case DSERR_GENERIC:\r
- return "Generic error";\r
+ // Determine the device buffer size. By default, we'll use the value\r
+ // defined above (32K), but we will grow it to make allowances for\r
+ // very large software buffer sizes.\r
+ DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;\r
+ DWORD dsPointerLeadTime = 0;\r
\r
- case DSERR_PRIOLEVELNEEDED:\r
- return "Priority level needed";\r
+ void *ohandle = 0, *bhandle = 0;\r
+ HRESULT result;\r
+ if ( mode == OUTPUT ) {\r
\r
- case DSERR_OUTOFMEMORY:\r
- return "Out of memory";\r
+ LPDIRECTSOUND output;\r
+ result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- case DSERR_BADFORMAT:\r
- return "The sample rate or the channel format is not supported";\r
+ DSCAPS outCaps;\r
+ outCaps.dwSize = sizeof( outCaps );\r
+ result = output->GetCaps( &outCaps );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- case DSERR_UNSUPPORTED:\r
- return "Not supported";\r
+ // Check channel information.\r
+ if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {\r
+ errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- case DSERR_NODRIVER:\r
- return "No driver";\r
+ // Check format information. Use 16-bit format unless not\r
+ // supported or user requests 8-bit.\r
+ if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&\r
+ !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {\r
+ waveFormat.wBitsPerSample = 16;\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+ }\r
+ else {\r
+ waveFormat.wBitsPerSample = 8;\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+ }\r
+ stream_.userFormat = format;\r
\r
- case DSERR_ALREADYINITIALIZED:\r
- return "Already initialized";\r
+ // Update wave format structure and buffer information.\r
+ waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;\r
+ waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\r
+ dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;\r
\r
- case DSERR_NOAGGREGATION:\r
- return "No aggregation";\r
+ // If the user wants an even bigger buffer, increase the device buffer size accordingly.\r
+ while ( dsPointerLeadTime * 2U > dsBufferSize )\r
+ dsBufferSize *= 2;\r
\r
- case DSERR_BUFFERLOST:\r
- return "Buffer lost";\r
+ // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.\r
+ // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );\r
+ // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.\r
+ result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- case DSERR_OTHERAPPHASPRIO:\r
- return "Another application already has priority";\r
+ // Even though we will write to the secondary buffer, we need to\r
+ // access the primary buffer to set the correct output format\r
+ // (since the default is 8-bit, 22 kHz!). Setup the DS primary\r
+ // buffer description.\r
+ DSBUFFERDESC bufferDescription;\r
+ ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );\r
+ bufferDescription.dwSize = sizeof( DSBUFFERDESC );\r
+ bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;\r
\r
- case DSERR_UNINITIALIZED:\r
- return "Uninitialized";\r
+ // Obtain the primary buffer\r
+ LPDIRECTSOUNDBUFFER buffer;\r
+ result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- default:\r
- return "DirectSound unknown error";\r
- }\r
-}\r
-//******************** End of __WINDOWS_DS__ *********************//\r
-#endif\r
+ // Set the primary DS buffer sound format.\r
+ result = buffer->SetFormat( &waveFormat );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
+ // Setup the secondary DS buffer description.\r
+ ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );\r
+ bufferDescription.dwSize = sizeof( DSBUFFERDESC );\r
+ bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |\r
+ DSBCAPS_GLOBALFOCUS |\r
+ DSBCAPS_GETCURRENTPOSITION2 |\r
+ DSBCAPS_LOCHARDWARE ); // Force hardware mixing\r
+ bufferDescription.dwBufferBytes = dsBufferSize;\r
+ bufferDescription.lpwfxFormat = &waveFormat;\r
\r
-#if defined(__LINUX_ALSA__)\r
+ // Try to create the secondary DS buffer. If that doesn't work,\r
+ // try to use software mixing. Otherwise, there's a problem.\r
+ result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
+ if ( FAILED( result ) ) {\r
+ bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |\r
+ DSBCAPS_GLOBALFOCUS |\r
+ DSBCAPS_GETCURRENTPOSITION2 |\r
+ DSBCAPS_LOCSOFTWARE ); // Force software mixing\r
+ result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+ }\r
\r
-#include <alsa/asoundlib.h>\r
-#include <unistd.h>\r
+ // Get the buffer size ... might be different from what we specified.\r
+ DSBCAPS dsbcaps;\r
+ dsbcaps.dwSize = sizeof( DSBCAPS );\r
+ result = buffer->GetCaps( &dsbcaps );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ buffer->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- // A structure to hold various information related to the ALSA API\r
- // implementation.\r
-struct AlsaHandle {\r
- snd_pcm_t *handles[2];\r
- bool synchronized;\r
- bool xrun[2];\r
- pthread_cond_t runnable_cv;\r
- bool runnable;\r
+ dsBufferSize = dsbcaps.dwBufferBytes;\r
\r
- AlsaHandle()\r
- :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }\r
-};\r
+ // Lock the DS buffer\r
+ LPVOID audioPtr;\r
+ DWORD dataLen;\r
+ result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ buffer->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
-extern "C" void *alsaCallbackHandler( void * ptr );\r
+ // Zero the DS buffer\r
+ ZeroMemory( audioPtr, dataLen );\r
\r
-RtApiAlsa :: RtApiAlsa()\r
-{\r
- // Nothing to do here.\r
-}\r
+ // Unlock the DS buffer\r
+ result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ output->Release();\r
+ buffer->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
-RtApiAlsa :: ~RtApiAlsa()\r
-{\r
- if ( stream_.state != STREAM_CLOSED ) closeStream();\r
-}\r
+ ohandle = (void *) output;\r
+ bhandle = (void *) buffer;\r
+ }\r
\r
-unsigned int RtApiAlsa :: getDeviceCount( void )\r
-{\r
- unsigned nDevices = 0;\r
- int result, subdevice, card;\r
- char name[64];\r
- snd_ctl_t *handle;\r
+ if ( mode == INPUT ) {\r
\r
- // Count cards and devices\r
- card = -1;\r
- snd_card_next( &card );\r
- while ( card >= 0 ) {\r
- sprintf( name, "hw:%d", card );\r
- result = snd_ctl_open( &handle, name, 0 );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
+ LPDIRECTSOUNDCAPTURE input;\r
+ result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto nextcard;\r
+ return FAILURE;\r
}\r
- subdevice = -1;\r
- while( 1 ) {\r
+\r
+ DSCCAPS inCaps;\r
+ inCaps.dwSize = sizeof( inCaps );\r
+ result = input->GetCaps( &inCaps );\r
+ if ( FAILED( result ) ) {\r
+ input->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+\r
+ // Check channel information.\r
+ if ( inCaps.dwChannels < channels + firstChannel ) {\r
+ errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";\r
+ return FAILURE;\r
+ }\r
+\r
+ // Check format information. Use 16-bit format unless user\r
+ // requests 8-bit.\r
+ DWORD deviceFormats;\r
+ if ( channels + firstChannel == 2 ) {\r
+ deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;\r
+ if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {\r
+ waveFormat.wBitsPerSample = 8;\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+ }\r
+ else { // assume 16-bit is supported\r
+ waveFormat.wBitsPerSample = 16;\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+ }\r
+ }\r
+ else { // channel == 1\r
+ deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;\r
+ if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {\r
+ waveFormat.wBitsPerSample = 8;\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+ }\r
+ else { // assume 16-bit is supported\r
+ waveFormat.wBitsPerSample = 16;\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+ }\r
+ }\r
+ stream_.userFormat = format;\r
+\r
+ // Update wave format structure and buffer information.\r
+ waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;\r
+ waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\r
+ dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;\r
+\r
+ // If the user wants an even bigger buffer, increase the device buffer size accordingly.\r
+ while ( dsPointerLeadTime * 2U > dsBufferSize )\r
+ dsBufferSize *= 2;\r
+\r
+ // Setup the secondary DS buffer description.\r
+ DSCBUFFERDESC bufferDescription;\r
+ ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );\r
+ bufferDescription.dwSize = sizeof( DSCBUFFERDESC );\r
+ bufferDescription.dwFlags = 0;\r
+ bufferDescription.dwReserved = 0;\r
+ bufferDescription.dwBufferBytes = dsBufferSize;\r
+ bufferDescription.lpwfxFormat = &waveFormat;\r
+\r
+ // Create the capture buffer.\r
+ LPDIRECTSOUNDCAPTUREBUFFER buffer;\r
+ result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );\r
+ if ( FAILED( result ) ) {\r
+ input->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+\r
+ // Get the buffer size ... might be different from what we specified.\r
+ DSCBCAPS dscbcaps;\r
+ dscbcaps.dwSize = sizeof( DSCBCAPS );\r
+ result = buffer->GetCaps( &dscbcaps );\r
+ if ( FAILED( result ) ) {\r
+ input->Release();\r
+ buffer->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+\r
+ dsBufferSize = dscbcaps.dwBufferBytes;\r
+\r
+ // NOTE: We could have a problem here if this is a duplex stream\r
+ // and the play and capture hardware buffer sizes are different\r
+ // (I'm actually not sure if that is a problem or not).\r
+ // Currently, we are not verifying that.\r
+\r
+ // Lock the capture buffer\r
+ LPVOID audioPtr;\r
+ DWORD dataLen;\r
+ result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ input->Release();\r
+ buffer->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+\r
+ // Zero the buffer\r
+ ZeroMemory( audioPtr, dataLen );\r
+\r
+ // Unlock the buffer\r
+ result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ input->Release();\r
+ buffer->Release();\r
+ errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+\r
+ ohandle = (void *) input;\r
+ bhandle = (void *) buffer;\r
+ }\r
+\r
+ // Set various stream parameters\r
+ DsHandle *handle = 0;\r
+ stream_.nDeviceChannels[mode] = channels + firstChannel;\r
+ stream_.nUserChannels[mode] = channels;\r
+ stream_.bufferSize = *bufferSize;\r
+ stream_.channelOffset[mode] = firstChannel;\r
+ stream_.deviceInterleaved[mode] = true;\r
+ if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+ else stream_.userInterleaved = true;\r
+\r
+ // Set flag for buffer conversion\r
+ stream_.doConvertBuffer[mode] = false;\r
+ if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])\r
+ stream_.doConvertBuffer[mode] = true;\r
+ if (stream_.userFormat != stream_.deviceFormat[mode])\r
+ stream_.doConvertBuffer[mode] = true;\r
+ if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+ stream_.nUserChannels[mode] > 1 )\r
+ stream_.doConvertBuffer[mode] = true;\r
+\r
+ // Allocate necessary internal buffers\r
+ long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+ stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+ if ( stream_.userBuffer[mode] == NULL ) {\r
+ errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";\r
+ goto error;\r
+ }\r
+\r
+ if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+ bool makeBuffer = true;\r
+ bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+ if ( mode == INPUT ) {\r
+ if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+ unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+ if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;\r
+ }\r
+ }\r
+\r
+ if ( makeBuffer ) {\r
+ bufferBytes *= *bufferSize;\r
+ if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+ if ( stream_.deviceBuffer == NULL ) {\r
+ errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";\r
+ goto error;\r
+ }\r
+ }\r
+ }\r
+\r
+ // Allocate our DsHandle structures for the stream.\r
+ if ( stream_.apiHandle == 0 ) {\r
+ try {\r
+ handle = new DsHandle;\r
+ }\r
+ catch ( std::bad_alloc& ) {\r
+ errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";\r
+ goto error;\r
+ }\r
+\r
+ // Create a manual-reset event.\r
+ handle->condition = CreateEvent( NULL, // no security\r
+ TRUE, // manual-reset\r
+ FALSE, // non-signaled initially\r
+ NULL ); // unnamed\r
+ stream_.apiHandle = (void *) handle;\r
+ }\r
+ else\r
+ handle = (DsHandle *) stream_.apiHandle;\r
+ handle->id[mode] = ohandle;\r
+ handle->buffer[mode] = bhandle;\r
+ handle->dsBufferSize[mode] = dsBufferSize;\r
+ handle->dsPointerLeadTime[mode] = dsPointerLeadTime;\r
+\r
+ stream_.device[mode] = device;\r
+ stream_.state = STREAM_STOPPED;\r
+ if ( stream_.mode == OUTPUT && mode == INPUT )\r
+ // We had already set up an output stream.\r
+ stream_.mode = DUPLEX;\r
+ else\r
+ stream_.mode = mode;\r
+ stream_.nBuffers = nBuffers;\r
+ stream_.sampleRate = sampleRate;\r
+\r
+ // Setup the buffer conversion information structure.\r
+ if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+\r
+ // Setup the callback thread.\r
+ if ( stream_.callbackInfo.isRunning == false ) {\r
+ unsigned threadId;\r
+ stream_.callbackInfo.isRunning = true;\r
+ stream_.callbackInfo.object = (void *) this;\r
+ stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,\r
+ &stream_.callbackInfo, 0, &threadId );\r
+ if ( stream_.callbackInfo.thread == 0 ) {\r
+ errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";\r
+ goto error;\r
+ }\r
+\r
+ // Boost DS thread priority\r
+ SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );\r
+ }\r
+ return SUCCESS;\r
+\r
+ error:\r
+ if ( handle ) {\r
+ if ( handle->buffer[0] ) { // the object pointer can be NULL and valid\r
+ LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];\r
+ LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+ if ( buffer ) buffer->Release();\r
+ object->Release();\r
+ }\r
+ if ( handle->buffer[1] ) {\r
+ LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];\r
+ LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+ if ( buffer ) buffer->Release();\r
+ object->Release();\r
+ }\r
+ CloseHandle( handle->condition );\r
+ delete handle;\r
+ stream_.apiHandle = 0;\r
+ }\r
+\r
+ for ( int i=0; i<2; i++ ) {\r
+ if ( stream_.userBuffer[i] ) {\r
+ free( stream_.userBuffer[i] );\r
+ stream_.userBuffer[i] = 0;\r
+ }\r
+ }\r
+\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
+ }\r
+\r
+ stream_.state = STREAM_CLOSED;\r
+ return FAILURE;\r
+}\r
+\r
+void RtApiDs :: closeStream()\r
+{\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiDs::closeStream(): no open stream to close!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
+\r
+ // Stop the callback thread.\r
+ stream_.callbackInfo.isRunning = false;\r
+ WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );\r
+ CloseHandle( (HANDLE) stream_.callbackInfo.thread );\r
+\r
+ DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+ if ( handle ) {\r
+ if ( handle->buffer[0] ) { // the object pointer can be NULL and valid\r
+ LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];\r
+ LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+ if ( buffer ) {\r
+ buffer->Stop();\r
+ buffer->Release();\r
+ }\r
+ object->Release();\r
+ }\r
+ if ( handle->buffer[1] ) {\r
+ LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];\r
+ LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+ if ( buffer ) {\r
+ buffer->Stop();\r
+ buffer->Release();\r
+ }\r
+ object->Release();\r
+ }\r
+ CloseHandle( handle->condition );\r
+ delete handle;\r
+ stream_.apiHandle = 0;\r
+ }\r
+\r
+ for ( int i=0; i<2; i++ ) {\r
+ if ( stream_.userBuffer[i] ) {\r
+ free( stream_.userBuffer[i] );\r
+ stream_.userBuffer[i] = 0;\r
+ }\r
+ }\r
+\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
+ }\r
+\r
+ stream_.mode = UNINITIALIZED;\r
+ stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+void RtApiDs :: startStream()\r
+{\r
+ verifyStream();\r
+ if ( stream_.state == STREAM_RUNNING ) {\r
+ errorText_ = "RtApiDs::startStream(): the stream is already running!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
+\r
+ DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+\r
+ // Increase scheduler frequency on lesser windows (a side-effect of\r
+ // increasing timer accuracy). On greater windows (Win2K or later),\r
+ // this is already in effect.\r
+ timeBeginPeriod( 1 ); \r
+\r
+ buffersRolling = false;\r
+ duplexPrerollBytes = 0;\r
+\r
+ if ( stream_.mode == DUPLEX ) {\r
+ // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.\r
+ duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );\r
+ }\r
+\r
+ HRESULT result = 0;\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+ LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+ result = buffer->Play( 0, 0, DSBPLAY_LOOPING );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+ }\r
+\r
+ if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+ LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+ result = buffer->Start( DSCBSTART_LOOPING );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+ }\r
+\r
+ handle->drainCounter = 0;\r
+ handle->internalDrain = false;\r
+ ResetEvent( handle->condition );\r
+ stream_.state = STREAM_RUNNING;\r
+\r
+ unlock:\r
+ if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiDs :: stopStream()\r
+{\r
+ verifyStream();\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
+\r
+ HRESULT result = 0;\r
+ LPVOID audioPtr;\r
+ DWORD dataLen;\r
+ DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ if ( handle->drainCounter == 0 ) {\r
+ handle->drainCounter = 2;\r
+ WaitForSingleObject( handle->condition, INFINITE ); // block until signaled\r
+ }\r
+\r
+ stream_.state = STREAM_STOPPED;\r
+\r
+ MUTEX_LOCK( &stream_.mutex );\r
+\r
+ // Stop the buffer and clear memory\r
+ LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+ result = buffer->Stop();\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+\r
+ // Lock the buffer and clear it so that if we start to play again,\r
+ // we won't have old data playing.\r
+ result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+\r
+ // Zero the DS buffer\r
+ ZeroMemory( audioPtr, dataLen );\r
+\r
+ // Unlock the DS buffer\r
+ result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+\r
+ // If we start playing again, we must begin at beginning of buffer.\r
+ handle->bufferPointer[0] = 0;\r
+ }\r
+\r
+ if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+ LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+ audioPtr = NULL;\r
+ dataLen = 0;\r
+\r
+ stream_.state = STREAM_STOPPED;\r
+\r
+ if ( stream_.mode != DUPLEX )\r
+ MUTEX_LOCK( &stream_.mutex );\r
+\r
+ result = buffer->Stop();\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+\r
+ // Lock the buffer and clear it so that if we start to play again,\r
+ // we won't have old data playing.\r
+ result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+\r
+ // Zero the DS buffer\r
+ ZeroMemory( audioPtr, dataLen );\r
+\r
+ // Unlock the DS buffer\r
+ result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+\r
+ // If we start recording again, we must begin at beginning of buffer.\r
+ handle->bufferPointer[1] = 0;\r
+ }\r
+\r
+ unlock:\r
+ timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+ if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiDs :: abortStream()\r
+{\r
+ verifyStream();\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
+\r
+ DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+ handle->drainCounter = 2;\r
+\r
+ stopStream();\r
+}\r
+\r
+void RtApiDs :: callbackEvent()\r
+{\r
+ if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {\r
+ Sleep( 50 ); // sleep 50 milliseconds\r
+ return;\r
+ }\r
+\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
+\r
+ CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;\r
+ DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+\r
+ // Check if we were draining the stream and signal is finished.\r
+ if ( handle->drainCounter > stream_.nBuffers + 2 ) {\r
+\r
+ stream_.state = STREAM_STOPPING;\r
+ if ( handle->internalDrain == false )\r
+ SetEvent( handle->condition );\r
+ else\r
+ stopStream();\r
+ return;\r
+ }\r
+\r
+ // Invoke user callback to get fresh output data UNLESS we are\r
+ // draining stream.\r
+ if ( handle->drainCounter == 0 ) {\r
+ RtAudioCallback callback = (RtAudioCallback) info->callback;\r
+ double streamTime = getStreamTime();\r
+ RtAudioStreamStatus status = 0;\r
+ if ( stream_.mode != INPUT && handle->xrun[0] == true ) {\r
+ status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+ handle->xrun[0] = false;\r
+ }\r
+ if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {\r
+ status |= RTAUDIO_INPUT_OVERFLOW;\r
+ handle->xrun[1] = false;\r
+ }\r
+ int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+ stream_.bufferSize, streamTime, status, info->userData );\r
+ if ( cbReturnValue == 2 ) {\r
+ stream_.state = STREAM_STOPPING;\r
+ handle->drainCounter = 2;\r
+ abortStream();\r
+ return;\r
+ }\r
+ else if ( cbReturnValue == 1 ) {\r
+ handle->drainCounter = 1;\r
+ handle->internalDrain = true;\r
+ }\r
+ }\r
+\r
+ HRESULT result;\r
+ DWORD currentWritePointer, safeWritePointer;\r
+ DWORD currentReadPointer, safeReadPointer;\r
+ UINT nextWritePointer;\r
+\r
+ LPVOID buffer1 = NULL;\r
+ LPVOID buffer2 = NULL;\r
+ DWORD bufferSize1 = 0;\r
+ DWORD bufferSize2 = 0;\r
+\r
+ char *buffer;\r
+ long bufferBytes;\r
+\r
+ MUTEX_LOCK( &stream_.mutex );\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ return;\r
+ }\r
+\r
+ if ( buffersRolling == false ) {\r
+ if ( stream_.mode == DUPLEX ) {\r
+ //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );\r
+\r
+ // It takes a while for the devices to get rolling. As a result,\r
+ // there's no guarantee that the capture and write device pointers\r
+ // will move in lockstep. Wait here for both devices to start\r
+ // rolling, and then set our buffer pointers accordingly.\r
+ // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600\r
+ // bytes later than the write buffer.\r
+\r
+ // Stub: a serious risk of having a pre-emptive scheduling round\r
+ // take place between the two GetCurrentPosition calls... but I'm\r
+ // really not sure how to solve the problem. Temporarily boost to\r
+ // Realtime priority, maybe; but I'm not sure what priority the\r
+ // DirectSound service threads run at. We *should* be roughly\r
+ // within a ms or so of correct.\r
+\r
+ LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+ LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+\r
+ DWORD startSafeWritePointer, startSafeReadPointer;\r
+\r
+ result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ while ( true ) {\r
+ result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;\r
+ Sleep( 1 );\r
+ }\r
+\r
+ //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );\r
+\r
+ handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];\r
+ if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];\r
+ handle->bufferPointer[1] = safeReadPointer;\r
+ }\r
+ else if ( stream_.mode == OUTPUT ) {\r
+\r
+ // Set the proper nextWritePosition after initial startup.\r
+ LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+ result = dsWriteBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];\r
+ if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];\r
+ }\r
+\r
+ buffersRolling = true;\r
+ }\r
+\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ \r
+ LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+\r
+ if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
+ bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];\r
+ bufferBytes *= formatBytes( stream_.userFormat );\r
+ memset( stream_.userBuffer[0], 0, bufferBytes );\r
+ }\r
+\r
+ // Setup parameters and do buffer conversion if necessary.\r
+ if ( stream_.doConvertBuffer[0] ) {\r
+ buffer = stream_.deviceBuffer;\r
+ convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+ bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];\r
+ bufferBytes *= formatBytes( stream_.deviceFormat[0] );\r
+ }\r
+ else {\r
+ buffer = stream_.userBuffer[0];\r
+ bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];\r
+ bufferBytes *= formatBytes( stream_.userFormat );\r
+ }\r
+\r
+ // No byte swapping necessary in DirectSound implementation.\r
+\r
+ // Ahhh ... windoze. 16-bit data is signed but 8-bit data is\r
+ // unsigned. So, we need to convert our signed 8-bit data here to\r
+ // unsigned.\r
+ if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )\r
+ for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );\r
+\r
+ DWORD dsBufferSize = handle->dsBufferSize[0];\r
+ nextWritePointer = handle->bufferPointer[0];\r
+\r
+ DWORD endWrite, leadPointer;\r
+ while ( true ) {\r
+ // Find out where the read and "safe write" pointers are.\r
+ result = dsBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+\r
+ // We will copy our output buffer into the region between\r
+ // safeWritePointer and leadPointer. If leadPointer is not\r
+ // beyond the next endWrite position, wait until it is.\r
+ leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];\r
+ //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;\r
+ if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;\r
+ if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset\r
+ endWrite = nextWritePointer + bufferBytes;\r
+\r
+ // Check whether the entire write region is behind the play pointer.\r
+ if ( leadPointer >= endWrite ) break;\r
+\r
+ // If we are here, then we must wait until the leadPointer advances\r
+ // beyond the end of our next write region. We use the\r
+ // Sleep() function to suspend operation until that happens.\r
+ double millis = ( endWrite - leadPointer ) * 1000.0;\r
+ millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);\r
+ if ( millis < 1.0 ) millis = 1.0;\r
+ Sleep( (DWORD) millis );\r
+ }\r
+\r
+ if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )\r
+ || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) { \r
+ // We've strayed into the forbidden zone ... resync the read pointer.\r
+ handle->xrun[0] = true;\r
+ nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;\r
+ if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;\r
+ handle->bufferPointer[0] = nextWritePointer;\r
+ endWrite = nextWritePointer + bufferBytes;\r
+ }\r
+\r
+ // Lock free space in the buffer\r
+ result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,\r
+ &bufferSize1, &buffer2, &bufferSize2, 0 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+\r
+ // Copy our buffer into the DS buffer\r
+ CopyMemory( buffer1, buffer, bufferSize1 );\r
+ if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );\r
+\r
+ // Update our buffer offset and unlock sound buffer\r
+ dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;\r
+ handle->bufferPointer[0] = nextWritePointer;\r
+ }\r
+\r
+ // Don't bother draining input\r
+ if ( handle->drainCounter ) {\r
+ handle->drainCounter++;\r
+ goto unlock;\r
+ }\r
+\r
+ if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+ // Setup parameters.\r
+ if ( stream_.doConvertBuffer[1] ) {\r
+ buffer = stream_.deviceBuffer;\r
+ bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];\r
+ bufferBytes *= formatBytes( stream_.deviceFormat[1] );\r
+ }\r
+ else {\r
+ buffer = stream_.userBuffer[1];\r
+ bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];\r
+ bufferBytes *= formatBytes( stream_.userFormat );\r
+ }\r
+\r
+ LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+ long nextReadPointer = handle->bufferPointer[1];\r
+ DWORD dsBufferSize = handle->dsBufferSize[1];\r
+\r
+ // Find out where the write and "safe read" pointers are.\r
+ result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+\r
+ if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
+ DWORD endRead = nextReadPointer + bufferBytes;\r
+\r
+ // Handling depends on whether we are INPUT or DUPLEX. \r
+ // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,\r
+ // then a wait here will drag the write pointers into the forbidden zone.\r
+ // \r
+ // In DUPLEX mode, rather than wait, we will back off the read pointer until \r
+ // it's in a safe position. This causes dropouts, but it seems to be the only \r
+ // practical way to sync up the read and write pointers reliably, given the \r
+ // the very complex relationship between phase and increment of the read and write \r
+ // pointers.\r
+ //\r
+ // In order to minimize audible dropouts in DUPLEX mode, we will\r
+ // provide a pre-roll period of 0.5 seconds in which we return\r
+ // zeros from the read buffer while the pointers sync up.\r
+\r
+ if ( stream_.mode == DUPLEX ) {\r
+ if ( safeReadPointer < endRead ) {\r
+ if ( duplexPrerollBytes <= 0 ) {\r
+ // Pre-roll time over. Be more agressive.\r
+ int adjustment = endRead-safeReadPointer;\r
+\r
+ handle->xrun[1] = true;\r
+ // Two cases:\r
+ // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,\r
+ // and perform fine adjustments later.\r
+ // - small adjustments: back off by twice as much.\r
+ if ( adjustment >= 2*bufferBytes )\r
+ nextReadPointer = safeReadPointer-2*bufferBytes;\r
+ else\r
+ nextReadPointer = safeReadPointer-bufferBytes-adjustment;\r
+\r
+ if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;\r
+\r
+ }\r
+ else {\r
+ // In pre=roll time. Just do it.\r
+ nextReadPointer = safeReadPointer - bufferBytes;\r
+ while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;\r
+ }\r
+ endRead = nextReadPointer + bufferBytes;\r
+ }\r
+ }\r
+ else { // mode == INPUT\r
+ while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {\r
+ // See comments for playback.\r
+ double millis = (endRead - safeReadPointer) * 1000.0;\r
+ millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);\r
+ if ( millis < 1.0 ) millis = 1.0;\r
+ Sleep( (DWORD) millis );\r
+\r
+ // Wake up and find out where we are now.\r
+ result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ \r
+ if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
+ }\r
+ }\r
+\r
+ // Lock free space in the buffer\r
+ result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,\r
+ &bufferSize1, &buffer2, &bufferSize2, 0 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+\r
+ if ( duplexPrerollBytes <= 0 ) {\r
+ // Copy our buffer into the DS buffer\r
+ CopyMemory( buffer, buffer1, bufferSize1 );\r
+ if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );\r
+ }\r
+ else {\r
+ memset( buffer, 0, bufferSize1 );\r
+ if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );\r
+ duplexPrerollBytes -= bufferSize1 + bufferSize2;\r
+ }\r
+\r
+ // Update our buffer offset and unlock sound buffer\r
+ nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;\r
+ dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );\r
+ if ( FAILED( result ) ) {\r
+ errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";\r
+ errorText_ = errorStream_.str();\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
+ }\r
+ handle->bufferPointer[1] = nextReadPointer;\r
+\r
+ // No byte swapping necessary in DirectSound implementation.\r
+\r
+ // If necessary, convert 8-bit data from unsigned to signed.\r
+ if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )\r
+ for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );\r
+\r
+ // Do buffer conversion if necessary.\r
+ if ( stream_.doConvertBuffer[1] )\r
+ convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+ }\r
+\r
+ unlock:\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ RtApi::tickStreamTime();\r
+}\r
+\r
+// Definitions for utility functions and callbacks\r
+// specific to the DirectSound implementation.\r
+\r
+static unsigned __stdcall callbackHandler( void *ptr )\r
+{\r
+ CallbackInfo *info = (CallbackInfo *) ptr;\r
+ RtApiDs *object = (RtApiDs *) info->object;\r
+ bool* isRunning = &info->isRunning;\r
+\r
+ while ( *isRunning == true ) {\r
+ object->callbackEvent();\r
+ }\r
+\r
+ _endthreadex( 0 );\r
+ return 0;\r
+}\r
+\r
+static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
+ LPCTSTR description,\r
+ LPCTSTR /*module*/,\r
+ LPVOID lpContext )\r
+{\r
+ struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;\r
+ std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;\r
+\r
+ HRESULT hr;\r
+ bool validDevice = false;\r
+ if ( probeInfo.isInput == true ) {\r
+ DSCCAPS caps;\r
+ LPDIRECTSOUNDCAPTURE object;\r
+\r
+ hr = DirectSoundCaptureCreate( lpguid, &object, NULL );\r
+ if ( hr != DS_OK ) return TRUE;\r
+\r
+ caps.dwSize = sizeof(caps);\r
+ hr = object->GetCaps( &caps );\r
+ if ( hr == DS_OK ) {\r
+ if ( caps.dwChannels > 0 && caps.dwFormats > 0 )\r
+ validDevice = true;\r
+ }\r
+ object->Release();\r
+ }\r
+ else {\r
+ DSCAPS caps;\r
+ LPDIRECTSOUND object;\r
+ hr = DirectSoundCreate( lpguid, &object, NULL );\r
+ if ( hr != DS_OK ) return TRUE;\r
+\r
+ caps.dwSize = sizeof(caps);\r
+ hr = object->GetCaps( &caps );\r
+ if ( hr == DS_OK ) {\r
+ if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )\r
+ validDevice = true;\r
+ }\r
+ object->Release();\r
+ }\r
+\r
+ // If good device, then save its name and guid.\r
+ std::string name = convertCharPointerToStdString( description );\r
+ //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )\r
+ if ( lpguid == NULL )\r
+ name = "Default Device";\r
+ if ( validDevice ) {\r
+ for ( unsigned int i=0; i<dsDevices.size(); i++ ) {\r
+ if ( dsDevices[i].name == name ) {\r
+ dsDevices[i].found = true;\r
+ if ( probeInfo.isInput ) {\r
+ dsDevices[i].id[1] = lpguid;\r
+ dsDevices[i].validId[1] = true;\r
+ }\r
+ else {\r
+ dsDevices[i].id[0] = lpguid;\r
+ dsDevices[i].validId[0] = true;\r
+ }\r
+ return TRUE;\r
+ }\r
+ }\r
+\r
+ DsDevice device;\r
+ device.name = name;\r
+ device.found = true;\r
+ if ( probeInfo.isInput ) {\r
+ device.id[1] = lpguid;\r
+ device.validId[1] = true;\r
+ }\r
+ else {\r
+ device.id[0] = lpguid;\r
+ device.validId[0] = true;\r
+ }\r
+ dsDevices.push_back( device );\r
+ }\r
+\r
+ return TRUE;\r
+}\r
+\r
+static const char* getErrorString( int code )\r
+{\r
+ switch ( code ) {\r
+\r
+ case DSERR_ALLOCATED:\r
+ return "Already allocated";\r
+\r
+ case DSERR_CONTROLUNAVAIL:\r
+ return "Control unavailable";\r
+\r
+ case DSERR_INVALIDPARAM:\r
+ return "Invalid parameter";\r
+\r
+ case DSERR_INVALIDCALL:\r
+ return "Invalid call";\r
+\r
+ case DSERR_GENERIC:\r
+ return "Generic error";\r
+\r
+ case DSERR_PRIOLEVELNEEDED:\r
+ return "Priority level needed";\r
+\r
+ case DSERR_OUTOFMEMORY:\r
+ return "Out of memory";\r
+\r
+ case DSERR_BADFORMAT:\r
+ return "The sample rate or the channel format is not supported";\r
+\r
+ case DSERR_UNSUPPORTED:\r
+ return "Not supported";\r
+\r
+ case DSERR_NODRIVER:\r
+ return "No driver";\r
+\r
+ case DSERR_ALREADYINITIALIZED:\r
+ return "Already initialized";\r
+\r
+ case DSERR_NOAGGREGATION:\r
+ return "No aggregation";\r
+\r
+ case DSERR_BUFFERLOST:\r
+ return "Buffer lost";\r
+\r
+ case DSERR_OTHERAPPHASPRIO:\r
+ return "Another application already has priority";\r
+\r
+ case DSERR_UNINITIALIZED:\r
+ return "Uninitialized";\r
+\r
+ default:\r
+ return "DirectSound unknown error";\r
+ }\r
+}\r
+//******************** End of __WINDOWS_DS__ *********************//\r
+#endif\r
+\r
+\r
+#if defined(__LINUX_ALSA__)\r
+\r
+#include <alsa/asoundlib.h>\r
+#include <unistd.h>\r
+\r
+ // A structure to hold various information related to the ALSA API\r
+ // implementation.\r
+struct AlsaHandle {\r
+ snd_pcm_t *handles[2];\r
+ bool synchronized;\r
+ bool xrun[2];\r
+ pthread_cond_t runnable_cv;\r
+ bool runnable;\r
+\r
+ AlsaHandle()\r
+ :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }\r
+};\r
+\r
+static void *alsaCallbackHandler( void * ptr );\r
+\r
+RtApiAlsa :: RtApiAlsa()\r
+{\r
+ // Nothing to do here.\r
+}\r
+\r
+RtApiAlsa :: ~RtApiAlsa()\r
+{\r
+ if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
+\r
+unsigned int RtApiAlsa :: getDeviceCount( void )\r
+{\r
+ unsigned nDevices = 0;\r
+ int result, subdevice, card;\r
+ char name[64];\r
+ snd_ctl_t *handle;\r
+\r
+ // Count cards and devices\r
+ card = -1;\r
+ snd_card_next( &card );\r
+ while ( card >= 0 ) {\r
+ sprintf( name, "hw:%d", card );\r
+ result = snd_ctl_open( &handle, name, 0 );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto nextcard;\r
+ }\r
+ subdevice = -1;\r
+ while( 1 ) {\r
result = snd_ctl_pcm_next_device( handle, &subdevice );\r
if ( result < 0 ) {\r
errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
break;\r
}\r
if ( subdevice < 0 )\r
snd_card_next( &card );\r
}\r
\r
- return nDevices;\r
+ result = snd_ctl_open( &handle, "default", 0 );\r
+ if (result == 0) {\r
+ nDevices++;\r
+ snd_ctl_close( handle );\r
+ }\r
+\r
+ return nDevices;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )\r
+{\r
+ RtAudio::DeviceInfo info;\r
+ info.probed = false;\r
+\r
+ unsigned nDevices = 0;\r
+ int result, subdevice, card;\r
+ char name[64];\r
+ snd_ctl_t *chandle;\r
+\r
+ // Count cards and devices\r
+ card = -1;\r
+ subdevice = -1;\r
+ snd_card_next( &card );\r
+ while ( card >= 0 ) {\r
+ sprintf( name, "hw:%d", card );\r
+ result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto nextcard;\r
+ }\r
+ subdevice = -1;\r
+ while( 1 ) {\r
+ result = snd_ctl_pcm_next_device( chandle, &subdevice );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ break;\r
+ }\r
+ if ( subdevice < 0 ) break;\r
+ if ( nDevices == device ) {\r
+ sprintf( name, "hw:%d,%d", card, subdevice );\r
+ goto foundDevice;\r
+ }\r
+ nDevices++;\r
+ }\r
+ nextcard:\r
+ snd_ctl_close( chandle );\r
+ snd_card_next( &card );\r
+ }\r
+\r
+ result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );\r
+ if ( result == 0 ) {\r
+ if ( nDevices == device ) {\r
+ strcpy( name, "default" );\r
+ goto foundDevice;\r
+ }\r
+ nDevices++;\r
+ }\r
+\r
+ if ( nDevices == 0 ) {\r
+ errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
+ }\r
+\r
+ if ( device >= nDevices ) {\r
+ errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
+ }\r
+\r
+ foundDevice:\r
+\r
+ // If a stream is already open, we cannot probe the stream devices.\r
+ // Thus, use the saved results.\r
+ if ( stream_.state != STREAM_CLOSED &&\r
+ ( stream_.device[0] == device || stream_.device[1] == device ) ) {\r
+ snd_ctl_close( chandle );\r
+ if ( device >= devices_.size() ) {\r
+ errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
+ return devices_[ device ];\r
+ }\r
+\r
+ int openMode = SND_PCM_ASYNC;\r
+ snd_pcm_stream_t stream;\r
+ snd_pcm_info_t *pcminfo;\r
+ snd_pcm_info_alloca( &pcminfo );\r
+ snd_pcm_t *phandle;\r
+ snd_pcm_hw_params_t *params;\r
+ snd_pcm_hw_params_alloca( ¶ms );\r
+\r
+ // First try for playback unless default device (which has subdev -1)\r
+ stream = SND_PCM_STREAM_PLAYBACK;\r
+ snd_pcm_info_set_stream( pcminfo, stream );\r
+ if ( subdevice != -1 ) {\r
+ snd_pcm_info_set_device( pcminfo, subdevice );\r
+ snd_pcm_info_set_subdevice( pcminfo, 0 );\r
+\r
+ result = snd_ctl_pcm_info( chandle, pcminfo );\r
+ if ( result < 0 ) {\r
+ // Device probably doesn't support playback.\r
+ goto captureProbe;\r
+ }\r
+ }\r
+\r
+ result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto captureProbe;\r
+ }\r
+\r
+ // The device is open ... fill the parameter structure.\r
+ result = snd_pcm_hw_params_any( phandle, params );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto captureProbe;\r
+ }\r
+\r
+ // Get output channel information.\r
+ unsigned int value;\r
+ result = snd_pcm_hw_params_get_channels_max( params, &value );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ goto captureProbe;\r
+ }\r
+ info.outputChannels = value;\r
+ snd_pcm_close( phandle );\r
+\r
+ captureProbe:\r
+ stream = SND_PCM_STREAM_CAPTURE;\r
+ snd_pcm_info_set_stream( pcminfo, stream );\r
+\r
+ // Now try for capture unless default device (with subdev = -1)\r
+ if ( subdevice != -1 ) {\r
+ result = snd_ctl_pcm_info( chandle, pcminfo );\r
+ snd_ctl_close( chandle );\r
+ if ( result < 0 ) {\r
+ // Device probably doesn't support capture.\r
+ if ( info.outputChannels == 0 ) return info;\r
+ goto probeParameters;\r
+ }\r
+ }\r
+ else\r
+ snd_ctl_close( chandle );\r
+\r
+ result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ if ( info.outputChannels == 0 ) return info;\r
+ goto probeParameters;\r
+ }\r
+\r
+ // The device is open ... fill the parameter structure.\r
+ result = snd_pcm_hw_params_any( phandle, params );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ if ( info.outputChannels == 0 ) return info;\r
+ goto probeParameters;\r
+ }\r
+\r
+ result = snd_pcm_hw_params_get_channels_max( params, &value );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ if ( info.outputChannels == 0 ) return info;\r
+ goto probeParameters;\r
+ }\r
+ info.inputChannels = value;\r
+ snd_pcm_close( phandle );\r
+\r
+ // If device opens for both playback and capture, we determine the channels.\r
+ if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+ info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+\r
+ // ALSA doesn't provide default devices so we'll use the first available one.\r
+ if ( device == 0 && info.outputChannels > 0 )\r
+ info.isDefaultOutput = true;\r
+ if ( device == 0 && info.inputChannels > 0 )\r
+ info.isDefaultInput = true;\r
+\r
+ probeParameters:\r
+ // At this point, we just need to figure out the supported data\r
+ // formats and sample rates. We'll proceed by opening the device in\r
+ // the direction with the maximum number of channels, or playback if\r
+ // they are equal. This might limit our sample rate options, but so\r
+ // be it.\r
+\r
+ if ( info.outputChannels >= info.inputChannels )\r
+ stream = SND_PCM_STREAM_PLAYBACK;\r
+ else\r
+ stream = SND_PCM_STREAM_CAPTURE;\r
+ snd_pcm_info_set_stream( pcminfo, stream );\r
+\r
+ result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
+\r
+ // The device is open ... fill the parameter structure.\r
+ result = snd_pcm_hw_params_any( phandle, params );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
+\r
+ // Test our discrete set of sample rate values.\r
+ info.sampleRates.clear();\r
+ for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
+ if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {\r
+ info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+\r
+ if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = SAMPLE_RATES[i];\r
+ }\r
+ }\r
+ if ( info.sampleRates.size() == 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
+\r
+ // Probe the supported data formats ... we don't care about endian-ness just yet\r
+ snd_pcm_format_t format;\r
+ info.nativeFormats = 0;\r
+ format = SND_PCM_FORMAT_S8;\r
+ if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+ info.nativeFormats |= RTAUDIO_SINT8;\r
+ format = SND_PCM_FORMAT_S16;\r
+ if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+ info.nativeFormats |= RTAUDIO_SINT16;\r
+ format = SND_PCM_FORMAT_S24;\r
+ if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+ info.nativeFormats |= RTAUDIO_SINT24;\r
+ format = SND_PCM_FORMAT_S32;\r
+ if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+ info.nativeFormats |= RTAUDIO_SINT32;\r
+ format = SND_PCM_FORMAT_FLOAT;\r
+ if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+ info.nativeFormats |= RTAUDIO_FLOAT32;\r
+ format = SND_PCM_FORMAT_FLOAT64;\r
+ if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+ info.nativeFormats |= RTAUDIO_FLOAT64;\r
+\r
+ // Check that we have at least one supported format\r
+ if ( info.nativeFormats == 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";\r
+ errorText_ = errorStream_.str();\r
+ error( RtAudioError::WARNING );\r
+ return info;\r
+ }\r
+\r
+ // Get the device name\r
+ char *cardname;\r
+ result = snd_card_get_name( card, &cardname );\r
+ if ( result >= 0 ) {\r
+ sprintf( name, "hw:%s,%d", cardname, subdevice );\r
+ free( cardname );\r
+ }\r
+ info.name = name;\r
+\r
+ // That's all ... close the device and return\r
+ snd_pcm_close( phandle );\r
+ info.probed = true;\r
+ return info;\r
}\r
\r
-RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )\r
+void RtApiAlsa :: saveDeviceInfo( void )\r
{\r
- RtAudio::DeviceInfo info;\r
- info.probed = false;\r
+ devices_.clear();\r
+\r
+ unsigned int nDevices = getDeviceCount();\r
+ devices_.resize( nDevices );\r
+ for ( unsigned int i=0; i<nDevices; i++ )\r
+ devices_[i] = getDeviceInfo( i );\r
+}\r
+\r
+bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+ unsigned int firstChannel, unsigned int sampleRate,\r
+ RtAudioFormat format, unsigned int *bufferSize,\r
+ RtAudio::StreamOptions *options )\r
+\r
+{\r
+#if defined(__RTAUDIO_DEBUG__)\r
+ snd_output_t *out;\r
+ snd_output_stdio_attach(&out, stderr, 0);\r
+#endif\r
+\r
+ // I'm not using the "plug" interface ... too much inconsistent behavior.\r
\r
unsigned nDevices = 0;\r
int result, subdevice, card;\r
char name[64];\r
snd_ctl_t *chandle;\r
\r
- // Count cards and devices\r
- card = -1;\r
- snd_card_next( &card );\r
- while ( card >= 0 ) {\r
- sprintf( name, "hw:%d", card );\r
- result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto nextcard;\r
- }\r
- subdevice = -1;\r
- while( 1 ) {\r
- result = snd_ctl_pcm_next_device( chandle, &subdevice );\r
+ if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )\r
+ snprintf(name, sizeof(name), "%s", "default");\r
+ else {\r
+ // Count cards and devices\r
+ card = -1;\r
+ snd_card_next( &card );\r
+ while ( card >= 0 ) {\r
+ sprintf( name, "hw:%d", card );\r
+ result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );\r
if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- break;\r
+ return FAILURE;\r
}\r
- if ( subdevice < 0 ) break;\r
+ subdevice = -1;\r
+ while( 1 ) {\r
+ result = snd_ctl_pcm_next_device( chandle, &subdevice );\r
+ if ( result < 0 ) break;\r
+ if ( subdevice < 0 ) break;\r
+ if ( nDevices == device ) {\r
+ sprintf( name, "hw:%d,%d", card, subdevice );\r
+ snd_ctl_close( chandle );\r
+ goto foundDevice;\r
+ }\r
+ nDevices++;\r
+ }\r
+ snd_ctl_close( chandle );\r
+ snd_card_next( &card );\r
+ }\r
+\r
+ result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );\r
+ if ( result == 0 ) {\r
if ( nDevices == device ) {\r
- sprintf( name, "hw:%d,%d", card, subdevice );\r
+ strcpy( name, "default" );\r
goto foundDevice;\r
}\r
nDevices++;\r
}\r
- nextcard:\r
- snd_ctl_close( chandle );\r
- snd_card_next( &card );\r
+\r
+ if ( nDevices == 0 ) {\r
+ // This should not happen because a check is made before this function is called.\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";\r
+ return FAILURE;\r
+ }\r
+\r
+ if ( device >= nDevices ) {\r
+ // This should not happen because a check is made before this function is called.\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";\r
+ return FAILURE;\r
+ }\r
}\r
\r
- if ( nDevices == 0 ) {\r
- errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";\r
- error( RtError::INVALID_USE );\r
+ foundDevice:\r
+\r
+ // The getDeviceInfo() function will not work for a device that is\r
+ // already open. Thus, we'll probe the system before opening a\r
+ // stream and save the results for use by getDeviceInfo().\r
+ if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once\r
+ this->saveDeviceInfo();\r
+\r
+ snd_pcm_stream_t stream;\r
+ if ( mode == OUTPUT )\r
+ stream = SND_PCM_STREAM_PLAYBACK;\r
+ else\r
+ stream = SND_PCM_STREAM_CAPTURE;\r
+\r
+ snd_pcm_t *phandle;\r
+ int openMode = SND_PCM_ASYNC;\r
+ result = snd_pcm_open( &phandle, name, stream, openMode );\r
+ if ( result < 0 ) {\r
+ if ( mode == OUTPUT )\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";\r
+ else\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
}\r
\r
- if ( device >= nDevices ) {\r
- errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";\r
- error( RtError::INVALID_USE );\r
+ // Fill the parameter structure.\r
+ snd_pcm_hw_params_t *hw_params;\r
+ snd_pcm_hw_params_alloca( &hw_params );\r
+ result = snd_pcm_hw_params_any( phandle, hw_params );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
}\r
\r
- foundDevice:\r
+#if defined(__RTAUDIO_DEBUG__)\r
+ fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );\r
+ snd_pcm_hw_params_dump( hw_params, out );\r
+#endif\r
\r
- // If a stream is already open, we cannot probe the stream devices.\r
- // Thus, use the saved results.\r
- if ( stream_.state != STREAM_CLOSED &&\r
- ( stream_.device[0] == device || stream_.device[1] == device ) ) {\r
- snd_ctl_close( chandle );\r
- if ( device >= devices_.size() ) {\r
- errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";\r
- error( RtError::WARNING );\r
- return info;\r
+ // Set access ... check user preference.\r
+ if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {\r
+ stream_.userInterleaved = false;\r
+ result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );\r
+ if ( result < 0 ) {\r
+ result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );\r
+ stream_.deviceInterleaved[mode] = true;\r
}\r
- return devices_[ device ];\r
+ else\r
+ stream_.deviceInterleaved[mode] = false;\r
+ }\r
+ else {\r
+ stream_.userInterleaved = true;\r
+ result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );\r
+ if ( result < 0 ) {\r
+ result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );\r
+ stream_.deviceInterleaved[mode] = false;\r
+ }\r
+ else\r
+ stream_.deviceInterleaved[mode] = true;\r
}\r
\r
- int openMode = SND_PCM_ASYNC;\r
- snd_pcm_stream_t stream;\r
- snd_pcm_info_t *pcminfo;\r
- snd_pcm_info_alloca( &pcminfo );\r
- snd_pcm_t *phandle;\r
- snd_pcm_hw_params_t *params;\r
- snd_pcm_hw_params_alloca( ¶ms );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
\r
- // First try for playback\r
- stream = SND_PCM_STREAM_PLAYBACK;\r
- snd_pcm_info_set_device( pcminfo, subdevice );\r
- snd_pcm_info_set_subdevice( pcminfo, 0 );\r
- snd_pcm_info_set_stream( pcminfo, stream );\r
+ // Determine how to set the device format.\r
+ stream_.userFormat = format;\r
+ snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;\r
+\r
+ if ( format == RTAUDIO_SINT8 )\r
+ deviceFormat = SND_PCM_FORMAT_S8;\r
+ else if ( format == RTAUDIO_SINT16 )\r
+ deviceFormat = SND_PCM_FORMAT_S16;\r
+ else if ( format == RTAUDIO_SINT24 )\r
+ deviceFormat = SND_PCM_FORMAT_S24;\r
+ else if ( format == RTAUDIO_SINT32 )\r
+ deviceFormat = SND_PCM_FORMAT_S32;\r
+ else if ( format == RTAUDIO_FLOAT32 )\r
+ deviceFormat = SND_PCM_FORMAT_FLOAT;\r
+ else if ( format == RTAUDIO_FLOAT64 )\r
+ deviceFormat = SND_PCM_FORMAT_FLOAT64;\r
+\r
+ if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {\r
+ stream_.deviceFormat[mode] = format;\r
+ goto setFormat;\r
+ }\r
+\r
+ // The user requested format is not natively supported by the device.\r
+ deviceFormat = SND_PCM_FORMAT_FLOAT64;\r
+ if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;\r
+ goto setFormat;\r
+ }\r
+\r
+ deviceFormat = SND_PCM_FORMAT_FLOAT;\r
+ if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+ goto setFormat;\r
+ }\r
+\r
+ deviceFormat = SND_PCM_FORMAT_S32;\r
+ if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+ goto setFormat;\r
+ }\r
+\r
+ deviceFormat = SND_PCM_FORMAT_S24;\r
+ if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+ goto setFormat;\r
+ }\r
+\r
+ deviceFormat = SND_PCM_FORMAT_S16;\r
+ if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+ goto setFormat;\r
+ }\r
+\r
+ deviceFormat = SND_PCM_FORMAT_S8;\r
+ if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+ stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+ goto setFormat;\r
+ }\r
+\r
+ // If we get here, no supported format was found.\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+\r
+ setFormat:\r
+ result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );\r
+ if ( result < 0 ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+\r
+ // Determine whether byte-swaping is necessary.\r
+ stream_.doByteSwap[mode] = false;\r
+ if ( deviceFormat != SND_PCM_FORMAT_S8 ) {\r
+ result = snd_pcm_format_cpu_endian( deviceFormat );\r
+ if ( result == 0 )\r
+ stream_.doByteSwap[mode] = true;\r
+ else if (result < 0) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
+ }\r
+ }\r
\r
- result = snd_ctl_pcm_info( chandle, pcminfo );\r
+ // Set the sample rate.\r
+ result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );\r
if ( result < 0 ) {\r
- // Device probably doesn't support playback.\r
- goto captureProbe;\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
}\r
\r
- result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ // Determine the number of channels for this device. We support a possible\r
+ // minimum device channel number > than the value requested by the user.\r
+ stream_.nUserChannels[mode] = channels;\r
+ unsigned int value;\r
+ result = snd_pcm_hw_params_get_channels_max( hw_params, &value );\r
+ unsigned int deviceChannels = value;\r
+ if ( result < 0 || deviceChannels < channels + firstChannel ) {\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto captureProbe;\r
+ return FAILURE;\r
}\r
\r
- // The device is open ... fill the parameter structure.\r
- result = snd_pcm_hw_params_any( phandle, params );\r
+ result = snd_pcm_hw_params_get_channels_min( hw_params, &value );\r
if ( result < 0 ) {\r
snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto captureProbe;\r
+ return FAILURE;\r
}\r
+ deviceChannels = value;\r
+ if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;\r
+ stream_.nDeviceChannels[mode] = deviceChannels;\r
\r
- // Get output channel information.\r
- unsigned int value;\r
- result = snd_pcm_hw_params_get_channels_max( params, &value );\r
+ // Set the device channels.\r
+ result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );\r
if ( result < 0 ) {\r
snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- goto captureProbe;\r
+ return FAILURE;\r
}\r
- info.outputChannels = value;\r
- snd_pcm_close( phandle );\r
\r
- captureProbe:\r
- // Now try for capture\r
- stream = SND_PCM_STREAM_CAPTURE;\r
- snd_pcm_info_set_stream( pcminfo, stream );\r
-\r
- result = snd_ctl_pcm_info( chandle, pcminfo );\r
- snd_ctl_close( chandle );\r
+ // Set the buffer (or period) size.\r
+ int dir = 0;\r
+ snd_pcm_uframes_t periodSize = *bufferSize;\r
+ result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );\r
if ( result < 0 ) {\r
- // Device probably doesn't support capture.\r
- if ( info.outputChannels == 0 ) return info;\r
- goto probeParameters;\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ return FAILURE;\r
}\r
+ *bufferSize = periodSize;\r
\r
- result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
+ // Set the buffer number, which in ALSA is referred to as the "period".\r
+ unsigned int periods = 0;\r
+ if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;\r
+ if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;\r
+ if ( periods < 2 ) periods = 4; // a fairly safe default value\r
+ result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );\r
if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ snd_pcm_close( phandle );\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- if ( info.outputChannels == 0 ) return info;\r
- goto probeParameters;\r
+ return FAILURE;\r
}\r
\r
- // The device is open ... fill the parameter structure.\r
- result = snd_pcm_hw_params_any( phandle, params );\r
- if ( result < 0 ) {\r
+ // If attempting to setup a duplex stream, the bufferSize parameter\r
+ // MUST be the same in both directions!\r
+ if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {\r
snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- if ( info.outputChannels == 0 ) return info;\r
- goto probeParameters;\r
+ return FAILURE;\r
}\r
\r
- result = snd_pcm_hw_params_get_channels_max( params, &value );\r
+ stream_.bufferSize = *bufferSize;\r
+\r
+ // Install the hardware configuration\r
+ result = snd_pcm_hw_params( phandle, hw_params );\r
if ( result < 0 ) {\r
snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- if ( info.outputChannels == 0 ) return info;\r
- goto probeParameters;\r
+ return FAILURE;\r
}\r
- info.inputChannels = value;\r
- snd_pcm_close( phandle );\r
-\r
- // If device opens for both playback and capture, we determine the channels.\r
- if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
- info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
\r
- // ALSA doesn't provide default devices so we'll use the first available one.\r
- if ( device == 0 && info.outputChannels > 0 )\r
- info.isDefaultOutput = true;\r
- if ( device == 0 && info.inputChannels > 0 )\r
- info.isDefaultInput = true;\r
+#if defined(__RTAUDIO_DEBUG__)\r
+ fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");\r
+ snd_pcm_hw_params_dump( hw_params, out );\r
+#endif\r
\r
- probeParameters:\r
- // At this point, we just need to figure out the supported data\r
- // formats and sample rates. We'll proceed by opening the device in\r
- // the direction with the maximum number of channels, or playback if\r
- // they are equal. This might limit our sample rate options, but so\r
- // be it.\r
+ // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.\r
+ snd_pcm_sw_params_t *sw_params = NULL;\r
+ snd_pcm_sw_params_alloca( &sw_params );\r
+ snd_pcm_sw_params_current( phandle, sw_params );\r
+ snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );\r
+ snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );\r
+ snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );\r
\r
- if ( info.outputChannels >= info.inputChannels )\r
- stream = SND_PCM_STREAM_PLAYBACK;\r
- else\r
- stream = SND_PCM_STREAM_CAPTURE;\r
- snd_pcm_info_set_stream( pcminfo, stream );\r
+ // The following two settings were suggested by Theo Veenker\r
+ //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );\r
+ //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );\r
\r
- result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- return info;\r
- }\r
+ // here are two options for a fix\r
+ //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );\r
+ snd_pcm_uframes_t val;\r
+ snd_pcm_sw_params_get_boundary( sw_params, &val );\r
+ snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );\r
\r
- // The device is open ... fill the parameter structure.\r
- result = snd_pcm_hw_params_any( phandle, params );\r
+ result = snd_pcm_sw_params( phandle, sw_params );\r
if ( result < 0 ) {\r
snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+ errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- return info;\r
+ return FAILURE;\r
}\r
\r
- // Test our discrete set of sample rate values.\r
- info.sampleRates.clear();\r
- for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
- if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 )\r
- info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+#if defined(__RTAUDIO_DEBUG__)\r
+ fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");\r
+ snd_pcm_sw_params_dump( sw_params, out );\r
+#endif\r
+\r
+ // Set flags for buffer conversion\r
+ stream_.doConvertBuffer[mode] = false;\r
+ if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+ stream_.doConvertBuffer[mode] = true;\r
+ if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
+ stream_.doConvertBuffer[mode] = true;\r
+ if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+ stream_.nUserChannels[mode] > 1 )\r
+ stream_.doConvertBuffer[mode] = true;\r
+\r
+ // Allocate the ApiHandle if necessary and then save.\r
+ AlsaHandle *apiInfo = 0;\r
+ if ( stream_.apiHandle == 0 ) {\r
+ try {\r
+ apiInfo = (AlsaHandle *) new AlsaHandle;\r
+ }\r
+ catch ( std::bad_alloc& ) {\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";\r
+ goto error;\r
+ }\r
+\r
+ if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";\r
+ goto error;\r
+ }\r
+\r
+ stream_.apiHandle = (void *) apiInfo;\r
+ apiInfo->handles[0] = 0;\r
+ apiInfo->handles[1] = 0;\r
}\r
- if ( info.sampleRates.size() == 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- return info;\r
+ else {\r
+ apiInfo = (AlsaHandle *) stream_.apiHandle;\r
}\r
+ apiInfo->handles[mode] = phandle;\r
+ phandle = 0;\r
\r
- // Probe the supported data formats ... we don't care about endian-ness just yet\r
- snd_pcm_format_t format;\r
- info.nativeFormats = 0;\r
- format = SND_PCM_FORMAT_S8;\r
- if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
- info.nativeFormats |= RTAUDIO_SINT8;\r
- format = SND_PCM_FORMAT_S16;\r
- if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
- info.nativeFormats |= RTAUDIO_SINT16;\r
- format = SND_PCM_FORMAT_S24;\r
- if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
- info.nativeFormats |= RTAUDIO_SINT24;\r
- format = SND_PCM_FORMAT_S32;\r
- if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
- info.nativeFormats |= RTAUDIO_SINT32;\r
- format = SND_PCM_FORMAT_FLOAT;\r
- if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
- info.nativeFormats |= RTAUDIO_FLOAT32;\r
- format = SND_PCM_FORMAT_FLOAT64;\r
- if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
- info.nativeFormats |= RTAUDIO_FLOAT64;\r
-\r
- // Check that we have at least one supported format\r
- if ( info.nativeFormats == 0 ) {\r
- errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";\r
- errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
- return info;\r
+ // Allocate necessary internal buffers.\r
+ unsigned long bufferBytes;\r
+ bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+ stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+ if ( stream_.userBuffer[mode] == NULL ) {\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";\r
+ goto error;\r
}\r
\r
- // Get the device name\r
- char *cardname;\r
- result = snd_card_get_name( card, &cardname );\r
- if ( result >= 0 )\r
- sprintf( name, "hw:%s,%d", cardname, subdevice );\r
- info.name = name;\r
+ if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+ bool makeBuffer = true;\r
+ bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+ if ( mode == INPUT ) {\r
+ if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+ unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+ if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+ }\r
+ }\r
+\r
+ if ( makeBuffer ) {\r
+ bufferBytes *= *bufferSize;\r
+ if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+ if ( stream_.deviceBuffer == NULL ) {\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";\r
+ goto error;\r
+ }\r
+ }\r
+ }\r
\r
- // That's all ... close the device and return\r
- snd_pcm_close( phandle );\r
- info.probed = true;\r
- return info;\r
-}\r
+ stream_.sampleRate = sampleRate;\r
+ stream_.nBuffers = periods;\r
+ stream_.device[mode] = device;\r
+ stream_.state = STREAM_STOPPED;\r
\r
-void RtApiAlsa :: saveDeviceInfo( void )\r
-{\r
- devices_.clear();\r
+ // Setup the buffer conversion information structure.\r
+ if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
\r
- unsigned int nDevices = getDeviceCount();\r
- devices_.resize( nDevices );\r
- for ( unsigned int i=0; i<nDevices; i++ )\r
- devices_[i] = getDeviceInfo( i );\r
-}\r
+ // Setup thread if necessary.\r
+ if ( stream_.mode == OUTPUT && mode == INPUT ) {\r
+ // We had already set up an output stream.\r
+ stream_.mode = DUPLEX;\r
+ // Link the streams if possible.\r
+ apiInfo->synchronized = false;\r
+ if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )\r
+ apiInfo->synchronized = true;\r
+ else {\r
+ errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";\r
+ error( RtAudioError::WARNING );\r
+ }\r
+ }\r
+ else {\r
+ stream_.mode = mode;\r
\r
-bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
- unsigned int firstChannel, unsigned int sampleRate,\r
- RtAudioFormat format, unsigned int *bufferSize,\r
- RtAudio::StreamOptions *options )\r
+ // Setup callback thread.\r
+ stream_.callbackInfo.object = (void *) this;\r
\r
-{\r
-#if defined(__RTAUDIO_DEBUG__)\r
- snd_output_t *out;\r
- snd_output_stdio_attach(&out, stderr, 0);\r
+ // Set the thread attributes for joinable and realtime scheduling\r
+ // priority (optional). The higher priority will only take affect\r
+ // if the program is run as root or suid. Note, under Linux\r
+ // processes with CAP_SYS_NICE privilege, a user can change\r
+ // scheduling policy and priority (thus need not be root). See\r
+ // POSIX "capabilities".\r
+ pthread_attr_t attr;\r
+ pthread_attr_init( &attr );\r
+ pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );\r
+\r
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
+ if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {\r
+ // We previously attempted to increase the audio callback priority\r
+ // to SCHED_RR here via the attributes. However, while no errors\r
+ // were reported in doing so, it did not work. So, now this is\r
+ // done in the alsaCallbackHandler function.\r
+ stream_.callbackInfo.doRealtime = true;\r
+ int priority = options->priority;\r
+ int min = sched_get_priority_min( SCHED_RR );\r
+ int max = sched_get_priority_max( SCHED_RR );\r
+ if ( priority < min ) priority = min;\r
+ else if ( priority > max ) priority = max;\r
+ stream_.callbackInfo.priority = priority;\r
+ }\r
#endif\r
\r
- // I'm not using the "plug" interface ... too much inconsistent behavior.\r
+ stream_.callbackInfo.isRunning = true;\r
+ result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );\r
+ pthread_attr_destroy( &attr );\r
+ if ( result ) {\r
+ stream_.callbackInfo.isRunning = false;\r
+ errorText_ = "RtApiAlsa::error creating callback thread!";\r
+ goto error;\r
+ }\r
+ }\r
\r
- unsigned nDevices = 0;\r
- int result, subdevice, card;\r
- char name[64];\r
- snd_ctl_t *chandle;\r
+ return SUCCESS;\r
\r
- if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )\r
- snprintf(name, sizeof(name), "%s", "default");\r
- else {\r
- // Count cards and devices\r
- card = -1;\r
- snd_card_next( &card );\r
- while ( card >= 0 ) {\r
- sprintf( name, "hw:%d", card );\r
- result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
- subdevice = -1;\r
- while( 1 ) {\r
- result = snd_ctl_pcm_next_device( chandle, &subdevice );\r
- if ( result < 0 ) break;\r
- if ( subdevice < 0 ) break;\r
- if ( nDevices == device ) {\r
- sprintf( name, "hw:%d,%d", card, subdevice );\r
- snd_ctl_close( chandle );\r
- goto foundDevice;\r
- }\r
- nDevices++;\r
- }\r
- snd_ctl_close( chandle );\r
- snd_card_next( &card );\r
- }\r
+ error:\r
+ if ( apiInfo ) {\r
+ pthread_cond_destroy( &apiInfo->runnable_cv );\r
+ if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );\r
+ if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );\r
+ delete apiInfo;\r
+ stream_.apiHandle = 0;\r
+ }\r
\r
- if ( nDevices == 0 ) {\r
- // This should not happen because a check is made before this function is called.\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";\r
- return FAILURE;\r
- }\r
+ if ( phandle) snd_pcm_close( phandle );\r
\r
- if ( device >= nDevices ) {\r
- // This should not happen because a check is made before this function is called.\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";\r
- return FAILURE;\r
+ for ( int i=0; i<2; i++ ) {\r
+ if ( stream_.userBuffer[i] ) {\r
+ free( stream_.userBuffer[i] );\r
+ stream_.userBuffer[i] = 0;\r
}\r
}\r
\r
- foundDevice:\r
-\r
- // The getDeviceInfo() function will not work for a device that is\r
- // already open. Thus, we'll probe the system before opening a\r
- // stream and save the results for use by getDeviceInfo().\r
- if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once\r
- this->saveDeviceInfo();\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
+ }\r
\r
- snd_pcm_stream_t stream;\r
- if ( mode == OUTPUT )\r
- stream = SND_PCM_STREAM_PLAYBACK;\r
- else\r
- stream = SND_PCM_STREAM_CAPTURE;\r
+ stream_.state = STREAM_CLOSED;\r
+ return FAILURE;\r
+}\r
\r
- snd_pcm_t *phandle;\r
- int openMode = SND_PCM_ASYNC;\r
- result = snd_pcm_open( &phandle, name, stream, openMode );\r
- if ( result < 0 ) {\r
- if ( mode == OUTPUT )\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";\r
- else\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+void RtApiAlsa :: closeStream()\r
+{\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- // Fill the parameter structure.\r
- snd_pcm_hw_params_t *hw_params;\r
- snd_pcm_hw_params_alloca( &hw_params );\r
- result = snd_pcm_hw_params_any( phandle, hw_params );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ stream_.callbackInfo.isRunning = false;\r
+ MUTEX_LOCK( &stream_.mutex );\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ apiInfo->runnable = true;\r
+ pthread_cond_signal( &apiInfo->runnable_cv );\r
}\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ pthread_join( stream_.callbackInfo.thread, NULL );\r
\r
-#if defined(__RTAUDIO_DEBUG__)\r
- fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );\r
- snd_pcm_hw_params_dump( hw_params, out );\r
-#endif\r
+ if ( stream_.state == STREAM_RUNNING ) {\r
+ stream_.state = STREAM_STOPPED;\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )\r
+ snd_pcm_drop( apiInfo->handles[0] );\r
+ if ( stream_.mode == INPUT || stream_.mode == DUPLEX )\r
+ snd_pcm_drop( apiInfo->handles[1] );\r
+ }\r
\r
- // Set access ... check user preference.\r
- if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {\r
- stream_.userInterleaved = false;\r
- result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );\r
- if ( result < 0 ) {\r
- result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );\r
- stream_.deviceInterleaved[mode] = true;\r
- }\r
- else\r
- stream_.deviceInterleaved[mode] = false;\r
+ if ( apiInfo ) {\r
+ pthread_cond_destroy( &apiInfo->runnable_cv );\r
+ if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );\r
+ if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );\r
+ delete apiInfo;\r
+ stream_.apiHandle = 0;\r
}\r
- else {\r
- stream_.userInterleaved = true;\r
- result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );\r
- if ( result < 0 ) {\r
- result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );\r
- stream_.deviceInterleaved[mode] = false;\r
+\r
+ for ( int i=0; i<2; i++ ) {\r
+ if ( stream_.userBuffer[i] ) {\r
+ free( stream_.userBuffer[i] );\r
+ stream_.userBuffer[i] = 0;\r
}\r
- else\r
- stream_.deviceInterleaved[mode] = true;\r
}\r
\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
}\r
\r
- // Determine how to set the device format.\r
- stream_.userFormat = format;\r
- snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;\r
+ stream_.mode = UNINITIALIZED;\r
+ stream_.state = STREAM_CLOSED;\r
+}\r
\r
- if ( format == RTAUDIO_SINT8 )\r
- deviceFormat = SND_PCM_FORMAT_S8;\r
- else if ( format == RTAUDIO_SINT16 )\r
- deviceFormat = SND_PCM_FORMAT_S16;\r
- else if ( format == RTAUDIO_SINT24 )\r
- deviceFormat = SND_PCM_FORMAT_S24;\r
- else if ( format == RTAUDIO_SINT32 )\r
- deviceFormat = SND_PCM_FORMAT_S32;\r
- else if ( format == RTAUDIO_FLOAT32 )\r
- deviceFormat = SND_PCM_FORMAT_FLOAT;\r
- else if ( format == RTAUDIO_FLOAT64 )\r
- deviceFormat = SND_PCM_FORMAT_FLOAT64;\r
+void RtApiAlsa :: startStream()\r
+{\r
+ // This method calls snd_pcm_prepare if the device isn't already in that state.\r
\r
- if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {\r
- stream_.deviceFormat[mode] = format;\r
- goto setFormat;\r
+ verifyStream();\r
+ if ( stream_.state == STREAM_RUNNING ) {\r
+ errorText_ = "RtApiAlsa::startStream(): the stream is already running!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- // The user requested format is not natively supported by the device.\r
- deviceFormat = SND_PCM_FORMAT_FLOAT64;\r
- if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {\r
- stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;\r
- goto setFormat;\r
- }\r
+ MUTEX_LOCK( &stream_.mutex );\r
\r
- deviceFormat = SND_PCM_FORMAT_FLOAT;\r
- if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
- stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
- goto setFormat;\r
+ int result = 0;\r
+ snd_pcm_state_t state;\r
+ AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ state = snd_pcm_state( handle[0] );\r
+ if ( state != SND_PCM_STATE_PREPARED ) {\r
+ result = snd_pcm_prepare( handle[0] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+ }\r
}\r
\r
- deviceFormat = SND_PCM_FORMAT_S32;\r
- if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
- goto setFormat;\r
+ if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
+ result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open\r
+ state = snd_pcm_state( handle[1] );\r
+ if ( state != SND_PCM_STATE_PREPARED ) {\r
+ result = snd_pcm_prepare( handle[1] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
+ }\r
}\r
\r
- deviceFormat = SND_PCM_FORMAT_S24;\r
- if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
- goto setFormat;\r
- }\r
+ stream_.state = STREAM_RUNNING;\r
\r
- deviceFormat = SND_PCM_FORMAT_S16;\r
- if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
- goto setFormat;\r
- }\r
+ unlock:\r
+ apiInfo->runnable = true;\r
+ pthread_cond_signal( &apiInfo->runnable_cv );\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
\r
- deviceFormat = SND_PCM_FORMAT_S8;\r
- if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
- stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
- goto setFormat;\r
+ if ( result >= 0 ) return;\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiAlsa :: stopStream()\r
+{\r
+ verifyStream();\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- // If we get here, no supported format was found.\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ stream_.state = STREAM_STOPPED;\r
+ MUTEX_LOCK( &stream_.mutex );\r
\r
- setFormat:\r
- result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ int result = 0;\r
+ AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ if ( apiInfo->synchronized ) \r
+ result = snd_pcm_drop( handle[0] );\r
+ else\r
+ result = snd_pcm_drain( handle[0] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
}\r
\r
- // Determine whether byte-swaping is necessary.\r
- stream_.doByteSwap[mode] = false;\r
- if ( deviceFormat != SND_PCM_FORMAT_S8 ) {\r
- result = snd_pcm_format_cpu_endian( deviceFormat );\r
- if ( result == 0 )\r
- stream_.doByteSwap[mode] = true;\r
- else if (result < 0) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";\r
+ if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
+ result = snd_pcm_drop( handle[1] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";\r
errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ goto unlock;\r
}\r
}\r
\r
- // Set the sample rate.\r
- result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ unlock:\r
+ apiInfo->runnable = false; // fixes high CPU usage when stopped\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
\r
- // Determine the number of channels for this device. We support a possible\r
- // minimum device channel number > than the value requested by the user.\r
- stream_.nUserChannels[mode] = channels;\r
- unsigned int value;\r
- result = snd_pcm_hw_params_get_channels_max( hw_params, &value );\r
- unsigned int deviceChannels = value;\r
- if ( result < 0 || deviceChannels < channels + firstChannel ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ if ( result >= 0 ) return;\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+}\r
\r
- result = snd_pcm_hw_params_get_channels_min( hw_params, &value );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+void RtApiAlsa :: abortStream()\r
+{\r
+ verifyStream();\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
- deviceChannels = value;\r
- if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;\r
- stream_.nDeviceChannels[mode] = deviceChannels;\r
\r
- // Set the device channels.\r
- result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ stream_.state = STREAM_STOPPED;\r
+ MUTEX_LOCK( &stream_.mutex );\r
\r
- // Set the buffer (or period) size.\r
- int dir = 0;\r
- snd_pcm_uframes_t periodSize = *bufferSize;\r
- result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ int result = 0;\r
+ AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ result = snd_pcm_drop( handle[0] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
}\r
- *bufferSize = periodSize;\r
\r
- // Set the buffer number, which in ALSA is referred to as the "period".\r
- unsigned int periods = 0;\r
- if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;\r
- if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;\r
- if ( periods < 2 ) periods = 4; // a fairly safe default value\r
- result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+ if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
+ result = snd_pcm_drop( handle[1] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ goto unlock;\r
+ }\r
}\r
\r
- // If attempting to setup a duplex stream, the bufferSize parameter\r
- // MUST be the same in both directions!\r
- if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ unlock:\r
+ apiInfo->runnable = false; // fixes high CPU usage when stopped\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
\r
- stream_.bufferSize = *bufferSize;\r
+ if ( result >= 0 ) return;\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+}\r
\r
- // Install the hardware configuration\r
- result = snd_pcm_hw_params( phandle, hw_params );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
+void RtApiAlsa :: callbackEvent()\r
+{\r
+ AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ MUTEX_LOCK( &stream_.mutex );\r
+ while ( !apiInfo->runnable )\r
+ pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );\r
+\r
+ if ( stream_.state != STREAM_RUNNING ) {\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ return;\r
+ }\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
}\r
\r
-#if defined(__RTAUDIO_DEBUG__)\r
- fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");\r
- snd_pcm_hw_params_dump( hw_params, out );\r
-#endif\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
\r
- // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.\r
- snd_pcm_sw_params_t *sw_params = NULL;\r
- snd_pcm_sw_params_alloca( &sw_params );\r
- snd_pcm_sw_params_current( phandle, sw_params );\r
- snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );\r
- snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );\r
- snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );\r
+ int doStopStream = 0;\r
+ RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
+ double streamTime = getStreamTime();\r
+ RtAudioStreamStatus status = 0;\r
+ if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {\r
+ status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+ apiInfo->xrun[0] = false;\r
+ }\r
+ if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {\r
+ status |= RTAUDIO_INPUT_OVERFLOW;\r
+ apiInfo->xrun[1] = false;\r
+ }\r
+ doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+ stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );\r
\r
- // The following two settings were suggested by Theo Veenker\r
- //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );\r
- //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );\r
+ if ( doStopStream == 2 ) {\r
+ abortStream();\r
+ return;\r
+ }\r
\r
- // here are two options for a fix\r
- //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );\r
- snd_pcm_uframes_t val;\r
- snd_pcm_sw_params_get_boundary( sw_params, &val );\r
- snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );\r
+ MUTEX_LOCK( &stream_.mutex );\r
\r
- result = snd_pcm_sw_params( phandle, sw_params );\r
- if ( result < 0 ) {\r
- snd_pcm_close( phandle );\r
- errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- return FAILURE;\r
- }\r
+ // The state might change while waiting on a mutex.\r
+ if ( stream_.state == STREAM_STOPPED ) goto unlock;\r
\r
-#if defined(__RTAUDIO_DEBUG__)\r
- fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");\r
- snd_pcm_sw_params_dump( sw_params, out );\r
-#endif\r
+ int result;\r
+ char *buffer;\r
+ int channels;\r
+ snd_pcm_t **handle;\r
+ snd_pcm_sframes_t frames;\r
+ RtAudioFormat format;\r
+ handle = (snd_pcm_t **) apiInfo->handles;\r
\r
- // Set flags for buffer conversion\r
- stream_.doConvertBuffer[mode] = false;\r
- if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
- stream_.doConvertBuffer[mode] = true;\r
- if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
- stream_.doConvertBuffer[mode] = true;\r
- if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
- stream_.nUserChannels[mode] > 1 )\r
- stream_.doConvertBuffer[mode] = true;\r
+ if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
\r
- // Allocate the ApiHandle if necessary and then save.\r
- AlsaHandle *apiInfo = 0;\r
- if ( stream_.apiHandle == 0 ) {\r
- try {\r
- apiInfo = (AlsaHandle *) new AlsaHandle;\r
+ // Setup parameters.\r
+ if ( stream_.doConvertBuffer[1] ) {\r
+ buffer = stream_.deviceBuffer;\r
+ channels = stream_.nDeviceChannels[1];\r
+ format = stream_.deviceFormat[1];\r
}\r
- catch ( std::bad_alloc& ) {\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";\r
- goto error;\r
+ else {\r
+ buffer = stream_.userBuffer[1];\r
+ channels = stream_.nUserChannels[1];\r
+ format = stream_.userFormat;\r
}\r
\r
- if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";\r
- goto error;\r
+ // Read samples from device in interleaved/non-interleaved format.\r
+ if ( stream_.deviceInterleaved[1] )\r
+ result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );\r
+ else {\r
+ void *bufs[channels];\r
+ size_t offset = stream_.bufferSize * formatBytes( format );\r
+ for ( int i=0; i<channels; i++ )\r
+ bufs[i] = (void *) (buffer + (i * offset));\r
+ result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );\r
}\r
\r
- stream_.apiHandle = (void *) apiInfo;\r
- apiInfo->handles[0] = 0;\r
- apiInfo->handles[1] = 0;\r
- }\r
- else {\r
- apiInfo = (AlsaHandle *) stream_.apiHandle;\r
- }\r
- apiInfo->handles[mode] = phandle;\r
- phandle = 0;\r
+ if ( result < (int) stream_.bufferSize ) {\r
+ // Either an error or overrun occured.\r
+ if ( result == -EPIPE ) {\r
+ snd_pcm_state_t state = snd_pcm_state( handle[1] );\r
+ if ( state == SND_PCM_STATE_XRUN ) {\r
+ apiInfo->xrun[1] = true;\r
+ result = snd_pcm_prepare( handle[1] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ }\r
+ }\r
+ else {\r
+ errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ }\r
+ }\r
+ else {\r
+ errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ }\r
+ error( RtAudioError::WARNING );\r
+ goto tryOutput;\r
+ }\r
\r
- // Allocate necessary internal buffers.\r
- unsigned long bufferBytes;\r
- bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
- stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
- if ( stream_.userBuffer[mode] == NULL ) {\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";\r
- goto error;\r
+ // Do byte swapping if necessary.\r
+ if ( stream_.doByteSwap[1] )\r
+ byteSwapBuffer( buffer, stream_.bufferSize * channels, format );\r
+\r
+ // Do buffer conversion if necessary.\r
+ if ( stream_.doConvertBuffer[1] )\r
+ convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+\r
+ // Check stream latency\r
+ result = snd_pcm_delay( handle[1], &frames );\r
+ if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;\r
}\r
\r
- if ( stream_.doConvertBuffer[mode] ) {\r
+ tryOutput:\r
\r
- bool makeBuffer = true;\r
- bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
- if ( mode == INPUT ) {\r
- if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
- unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
- if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
- }\r
+ if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+ // Setup parameters and do buffer conversion if necessary.\r
+ if ( stream_.doConvertBuffer[0] ) {\r
+ buffer = stream_.deviceBuffer;\r
+ convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+ channels = stream_.nDeviceChannels[0];\r
+ format = stream_.deviceFormat[0];\r
+ }\r
+ else {\r
+ buffer = stream_.userBuffer[0];\r
+ channels = stream_.nUserChannels[0];\r
+ format = stream_.userFormat;\r
}\r
\r
- if ( makeBuffer ) {\r
- bufferBytes *= *bufferSize;\r
- if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
- if ( stream_.deviceBuffer == NULL ) {\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";\r
- goto error;\r
+ // Do byte swapping if necessary.\r
+ if ( stream_.doByteSwap[0] )\r
+ byteSwapBuffer(buffer, stream_.bufferSize * channels, format);\r
+\r
+ // Write samples to device in interleaved/non-interleaved format.\r
+ if ( stream_.deviceInterleaved[0] )\r
+ result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );\r
+ else {\r
+ void *bufs[channels];\r
+ size_t offset = stream_.bufferSize * formatBytes( format );\r
+ for ( int i=0; i<channels; i++ )\r
+ bufs[i] = (void *) (buffer + (i * offset));\r
+ result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );\r
+ }\r
+\r
+ if ( result < (int) stream_.bufferSize ) {\r
+ // Either an error or underrun occured.\r
+ if ( result == -EPIPE ) {\r
+ snd_pcm_state_t state = snd_pcm_state( handle[0] );\r
+ if ( state == SND_PCM_STATE_XRUN ) {\r
+ apiInfo->xrun[0] = true;\r
+ result = snd_pcm_prepare( handle[0] );\r
+ if ( result < 0 ) {\r
+ errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ }\r
+ else\r
+ errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";\r
+ }\r
+ else {\r
+ errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
+ }\r
+ }\r
+ else {\r
+ errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";\r
+ errorText_ = errorStream_.str();\r
}\r
+ error( RtAudioError::WARNING );\r
+ goto unlock;\r
}\r
+\r
+ // Check stream latency\r
+ result = snd_pcm_delay( handle[0], &frames );\r
+ if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;\r
}\r
\r
- stream_.sampleRate = sampleRate;\r
- stream_.nBuffers = periods;\r
- stream_.device[mode] = device;\r
- stream_.state = STREAM_STOPPED;\r
+ unlock:\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
\r
- // Setup the buffer conversion information structure.\r
- if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+ RtApi::tickStreamTime();\r
+ if ( doStopStream == 1 ) this->stopStream();\r
+}\r
\r
- // Setup thread if necessary.\r
- if ( stream_.mode == OUTPUT && mode == INPUT ) {\r
- // We had already set up an output stream.\r
- stream_.mode = DUPLEX;\r
- // Link the streams if possible.\r
- apiInfo->synchronized = false;\r
- if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )\r
- apiInfo->synchronized = true;\r
- else {\r
- errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";\r
- error( RtError::WARNING );\r
- }\r
+static void *alsaCallbackHandler( void *ptr )\r
+{\r
+ CallbackInfo *info = (CallbackInfo *) ptr;\r
+ RtApiAlsa *object = (RtApiAlsa *) info->object;\r
+ bool *isRunning = &info->isRunning;\r
+\r
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
+ if ( info->doRealtime ) {\r
+ pthread_t tID = pthread_self(); // ID of this thread\r
+ sched_param prio = { info->priority }; // scheduling priority of thread\r
+ pthread_setschedparam( tID, SCHED_RR, &prio );\r
}\r
- else {\r
- stream_.mode = mode;\r
+#endif\r
\r
- // Setup callback thread.\r
- stream_.callbackInfo.object = (void *) this;\r
+ while ( *isRunning == true ) {\r
+ pthread_testcancel();\r
+ object->callbackEvent();\r
+ }\r
\r
- // Set the thread attributes for joinable and realtime scheduling\r
- // priority (optional). The higher priority will only take affect\r
- // if the program is run as root or suid. Note, under Linux\r
- // processes with CAP_SYS_NICE privilege, a user can change\r
- // scheduling policy and priority (thus need not be root). See\r
- // POSIX "capabilities".\r
- pthread_attr_t attr;\r
- pthread_attr_init( &attr );\r
- pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );\r
-#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
- if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {\r
- struct sched_param param;\r
- int priority = options->priority;\r
- int min = sched_get_priority_min( SCHED_RR );\r
- int max = sched_get_priority_max( SCHED_RR );\r
- if ( priority < min ) priority = min;\r
- else if ( priority > max ) priority = max;\r
- param.sched_priority = priority;\r
- pthread_attr_setschedparam( &attr, ¶m );\r
- pthread_attr_setschedpolicy( &attr, SCHED_RR );\r
- }\r
- else\r
- pthread_attr_setschedpolicy( &attr, SCHED_OTHER );\r
-#else\r
- pthread_attr_setschedpolicy( &attr, SCHED_OTHER );\r
+ pthread_exit( NULL );\r
+}\r
+\r
+//******************** End of __LINUX_ALSA__ *********************//\r
#endif\r
\r
- stream_.callbackInfo.isRunning = true;\r
- result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );\r
- pthread_attr_destroy( &attr );\r
- if ( result ) {\r
- stream_.callbackInfo.isRunning = false;\r
- errorText_ = "RtApiAlsa::error creating callback thread!";\r
- goto error;\r
- }\r
- }\r
+#if defined(__LINUX_PULSE__)\r
\r
- return SUCCESS;\r
+// Code written by Peter Meerwald, pmeerw@pmeerw.net\r
+// and Tristan Matthews.\r
\r
- error:\r
- if ( apiInfo ) {\r
- pthread_cond_destroy( &apiInfo->runnable_cv );\r
- if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );\r
- if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );\r
- delete apiInfo;\r
- stream_.apiHandle = 0;\r
- }\r
+#include <pulse/error.h>\r
+#include <pulse/simple.h>\r
+#include <cstdio>\r
\r
- if ( phandle) snd_pcm_close( phandle );\r
+static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,\r
+ 44100, 48000, 96000, 0};\r
\r
- for ( int i=0; i<2; i++ ) {\r
- if ( stream_.userBuffer[i] ) {\r
- free( stream_.userBuffer[i] );\r
- stream_.userBuffer[i] = 0;\r
- }\r
- }\r
+struct rtaudio_pa_format_mapping_t {\r
+ RtAudioFormat rtaudio_format;\r
+ pa_sample_format_t pa_format;\r
+};\r
\r
- if ( stream_.deviceBuffer ) {\r
- free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = 0;\r
- }\r
+static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {\r
+ {RTAUDIO_SINT16, PA_SAMPLE_S16LE},\r
+ {RTAUDIO_SINT32, PA_SAMPLE_S32LE},\r
+ {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},\r
+ {0, PA_SAMPLE_INVALID}};\r
\r
- return FAILURE;\r
+struct PulseAudioHandle {\r
+ pa_simple *s_play;\r
+ pa_simple *s_rec;\r
+ pthread_t thread;\r
+ pthread_cond_t runnable_cv;\r
+ bool runnable;\r
+ PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }\r
+};\r
+\r
+RtApiPulse::~RtApiPulse()\r
+{\r
+ if ( stream_.state != STREAM_CLOSED )\r
+ closeStream();\r
}\r
\r
-void RtApiAlsa :: closeStream()\r
+unsigned int RtApiPulse::getDeviceCount( void )\r
{\r
- if ( stream_.state == STREAM_CLOSED ) {\r
- errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";\r
- error( RtError::WARNING );\r
- return;\r
+ return 1;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )\r
+{\r
+ RtAudio::DeviceInfo info;\r
+ info.probed = true;\r
+ info.name = "PulseAudio";\r
+ info.outputChannels = 2;\r
+ info.inputChannels = 2;\r
+ info.duplexChannels = 2;\r
+ info.isDefaultOutput = true;\r
+ info.isDefaultInput = true;\r
+\r
+ for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )\r
+ info.sampleRates.push_back( *sr );\r
+\r
+ info.preferredSampleRate = 48000;\r
+ info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;\r
+\r
+ return info;\r
+}\r
+\r
+static void *pulseaudio_callback( void * user )\r
+{\r
+ CallbackInfo *cbi = static_cast<CallbackInfo *>( user );\r
+ RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );\r
+ volatile bool *isRunning = &cbi->isRunning;\r
+\r
+ while ( *isRunning ) {\r
+ pthread_testcancel();\r
+ context->callbackEvent();\r
}\r
\r
- AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ pthread_exit( NULL );\r
+}\r
+\r
+void RtApiPulse::closeStream( void )\r
+{\r
+ PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
stream_.callbackInfo.isRunning = false;\r
- MUTEX_LOCK( &stream_.mutex );\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- apiInfo->runnable = true;\r
- pthread_cond_signal( &apiInfo->runnable_cv );\r
- }\r
- MUTEX_UNLOCK( &stream_.mutex );\r
- pthread_join( stream_.callbackInfo.thread, NULL );\r
+ if ( pah ) {\r
+ MUTEX_LOCK( &stream_.mutex );\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ pah->runnable = true;\r
+ pthread_cond_signal( &pah->runnable_cv );\r
+ }\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
\r
- if ( stream_.state == STREAM_RUNNING ) {\r
- stream_.state = STREAM_STOPPED;\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )\r
- snd_pcm_drop( apiInfo->handles[0] );\r
- if ( stream_.mode == INPUT || stream_.mode == DUPLEX )\r
- snd_pcm_drop( apiInfo->handles[1] );\r
- }\r
+ pthread_join( pah->thread, 0 );\r
+ if ( pah->s_play ) {\r
+ pa_simple_flush( pah->s_play, NULL );\r
+ pa_simple_free( pah->s_play );\r
+ }\r
+ if ( pah->s_rec )\r
+ pa_simple_free( pah->s_rec );\r
\r
- if ( apiInfo ) {\r
- pthread_cond_destroy( &apiInfo->runnable_cv );\r
- if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );\r
- if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );\r
- delete apiInfo;\r
+ pthread_cond_destroy( &pah->runnable_cv );\r
+ delete pah;\r
stream_.apiHandle = 0;\r
}\r
\r
- for ( int i=0; i<2; i++ ) {\r
- if ( stream_.userBuffer[i] ) {\r
- free( stream_.userBuffer[i] );\r
- stream_.userBuffer[i] = 0;\r
- }\r
+ if ( stream_.userBuffer[0] ) {\r
+ free( stream_.userBuffer[0] );\r
+ stream_.userBuffer[0] = 0;\r
}\r
-\r
- if ( stream_.deviceBuffer ) {\r
- free( stream_.deviceBuffer );\r
- stream_.deviceBuffer = 0;\r
+ if ( stream_.userBuffer[1] ) {\r
+ free( stream_.userBuffer[1] );\r
+ stream_.userBuffer[1] = 0;\r
}\r
\r
- stream_.mode = UNINITIALIZED;\r
stream_.state = STREAM_CLOSED;\r
+ stream_.mode = UNINITIALIZED;\r
}\r
\r
-void RtApiAlsa :: startStream()\r
+void RtApiPulse::callbackEvent( void )\r
{\r
- // This method calls snd_pcm_prepare if the device isn't already in that state.\r
-\r
- verifyStream();\r
- if ( stream_.state == STREAM_RUNNING ) {\r
- errorText_ = "RtApiAlsa::startStream(): the stream is already running!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
+ PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
\r
- MUTEX_LOCK( &stream_.mutex );\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ MUTEX_LOCK( &stream_.mutex );\r
+ while ( !pah->runnable )\r
+ pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );\r
\r
- int result = 0;\r
- snd_pcm_state_t state;\r
- AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
- snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
- state = snd_pcm_state( handle[0] );\r
- if ( state != SND_PCM_STATE_PREPARED ) {\r
- result = snd_pcm_prepare( handle[0] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
+ if ( stream_.state != STREAM_RUNNING ) {\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ return;\r
}\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
}\r
\r
- if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
- state = snd_pcm_state( handle[1] );\r
- if ( state != SND_PCM_STATE_PREPARED ) {\r
- result = snd_pcm_prepare( handle[1] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
- }\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "\r
+ "this shouldn't happen!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- stream_.state = STREAM_RUNNING;\r
-\r
- unlock:\r
- apiInfo->runnable = true;\r
- pthread_cond_signal( &apiInfo->runnable_cv );\r
- MUTEX_UNLOCK( &stream_.mutex );\r
-\r
- if ( result >= 0 ) return;\r
- error( RtError::SYSTEM_ERROR );\r
-}\r
+ RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
+ double streamTime = getStreamTime();\r
+ RtAudioStreamStatus status = 0;\r
+ int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],\r
+ stream_.bufferSize, streamTime, status,\r
+ stream_.callbackInfo.userData );\r
\r
-void RtApiAlsa :: stopStream()\r
-{\r
- verifyStream();\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ if ( doStopStream == 2 ) {\r
+ abortStream();\r
return;\r
}\r
\r
- stream_.state = STREAM_STOPPED;\r
MUTEX_LOCK( &stream_.mutex );\r
+ void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];\r
+ void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];\r
\r
- //if ( stream_.state == STREAM_STOPPED ) {\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
- // return;\r
- //}\r
+ if ( stream_.state != STREAM_RUNNING )\r
+ goto unlock;\r
\r
- int result = 0;\r
- AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
- snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
- if ( apiInfo->synchronized ) \r
- result = snd_pcm_drop( handle[0] );\r
- else\r
- result = snd_pcm_drain( handle[0] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";\r
+ int pa_error;\r
+ size_t bytes;\r
+ if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ if ( stream_.doConvertBuffer[OUTPUT] ) {\r
+ convertBuffer( stream_.deviceBuffer,\r
+ stream_.userBuffer[OUTPUT],\r
+ stream_.convertInfo[OUTPUT] );\r
+ bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *\r
+ formatBytes( stream_.deviceFormat[OUTPUT] );\r
+ } else\r
+ bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *\r
+ formatBytes( stream_.userFormat );\r
+\r
+ if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {\r
+ errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<\r
+ pa_strerror( pa_error ) << ".";\r
errorText_ = errorStream_.str();\r
- goto unlock;\r
+ error( RtAudioError::WARNING );\r
}\r
}\r
\r
- if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
- result = snd_pcm_drop( handle[1] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";\r
+ if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {\r
+ if ( stream_.doConvertBuffer[INPUT] )\r
+ bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *\r
+ formatBytes( stream_.deviceFormat[INPUT] );\r
+ else\r
+ bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *\r
+ formatBytes( stream_.userFormat );\r
+ \r
+ if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {\r
+ errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<\r
+ pa_strerror( pa_error ) << ".";\r
errorText_ = errorStream_.str();\r
- goto unlock;\r
+ error( RtAudioError::WARNING );\r
+ }\r
+ if ( stream_.doConvertBuffer[INPUT] ) {\r
+ convertBuffer( stream_.userBuffer[INPUT],\r
+ stream_.deviceBuffer,\r
+ stream_.convertInfo[INPUT] );\r
}\r
}\r
\r
unlock:\r
- stream_.state = STREAM_STOPPED;\r
MUTEX_UNLOCK( &stream_.mutex );\r
+ RtApi::tickStreamTime();\r
\r
- if ( result >= 0 ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ if ( doStopStream == 1 )\r
+ stopStream();\r
}\r
\r
-void RtApiAlsa :: abortStream()\r
+void RtApiPulse::startStream( void )\r
{\r
- verifyStream();\r
- if ( stream_.state == STREAM_STOPPED ) {\r
- errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiPulse::startStream(): the stream is not open!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
+ }\r
+ if ( stream_.state == STREAM_RUNNING ) {\r
+ errorText_ = "RtApiPulse::startStream(): the stream is already running!";\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
- stream_.state = STREAM_STOPPED;\r
MUTEX_LOCK( &stream_.mutex );\r
\r
- //if ( stream_.state == STREAM_STOPPED ) {\r
- // MUTEX_UNLOCK( &stream_.mutex );\r
- // return;\r
- //}\r
+ stream_.state = STREAM_RUNNING;\r
+\r
+ pah->runnable = true;\r
+ pthread_cond_signal( &pah->runnable_cv );\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
\r
- int result = 0;\r
- AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
- snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
- result = snd_pcm_drop( handle[0] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- goto unlock;\r
- }\r
+void RtApiPulse::stopStream( void )\r
+{\r
+ PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiPulse::stopStream(): the stream is not open!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
+ }\r
+ if ( stream_.state == STREAM_STOPPED ) {\r
+ errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
}\r
\r
- if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
- result = snd_pcm_drop( handle[1] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";\r
+ stream_.state = STREAM_STOPPED;\r
+ MUTEX_LOCK( &stream_.mutex );\r
+\r
+ if ( pah && pah->s_play ) {\r
+ int pa_error;\r
+ if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {\r
+ errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<\r
+ pa_strerror( pa_error ) << ".";\r
errorText_ = errorStream_.str();\r
- goto unlock;\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
+ return;\r
}\r
}\r
\r
- unlock:\r
stream_.state = STREAM_STOPPED;\r
MUTEX_UNLOCK( &stream_.mutex );\r
-\r
- if ( result >= 0 ) return;\r
- error( RtError::SYSTEM_ERROR );\r
}\r
\r
-void RtApiAlsa :: callbackEvent()\r
+void RtApiPulse::abortStream( void )\r
{\r
- AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+ PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );\r
+\r
+ if ( stream_.state == STREAM_CLOSED ) {\r
+ errorText_ = "RtApiPulse::abortStream(): the stream is not open!";\r
+ error( RtAudioError::INVALID_USE );\r
+ return;\r
+ }\r
if ( stream_.state == STREAM_STOPPED ) {\r
- MUTEX_LOCK( &stream_.mutex );\r
- while ( !apiInfo->runnable )\r
- pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );\r
+ errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";\r
+ error( RtAudioError::WARNING );\r
+ return;\r
+ }\r
\r
- if ( stream_.state != STREAM_RUNNING ) {\r
+ stream_.state = STREAM_STOPPED;\r
+ MUTEX_LOCK( &stream_.mutex );\r
+\r
+ if ( pah && pah->s_play ) {\r
+ int pa_error;\r
+ if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {\r
+ errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<\r
+ pa_strerror( pa_error ) << ".";\r
+ errorText_ = errorStream_.str();\r
MUTEX_UNLOCK( &stream_.mutex );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
return;\r
}\r
- MUTEX_UNLOCK( &stream_.mutex );\r
}\r
\r
- if ( stream_.state == STREAM_CLOSED ) {\r
- errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
- error( RtError::WARNING );\r
- return;\r
- }\r
+ stream_.state = STREAM_STOPPED;\r
+ MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
\r
- int doStopStream = 0;\r
- RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
- double streamTime = getStreamTime();\r
- RtAudioStreamStatus status = 0;\r
- if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {\r
- status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
- apiInfo->xrun[0] = false;\r
+bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,\r
+ unsigned int channels, unsigned int firstChannel,\r
+ unsigned int sampleRate, RtAudioFormat format,\r
+ unsigned int *bufferSize, RtAudio::StreamOptions *options )\r
+{\r
+ PulseAudioHandle *pah = 0;\r
+ unsigned long bufferBytes = 0;\r
+ pa_sample_spec ss;\r
+\r
+ if ( device != 0 ) return false;\r
+ if ( mode != INPUT && mode != OUTPUT ) return false;\r
+ if ( channels != 1 && channels != 2 ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";\r
+ return false;\r
+ }\r
+ ss.channels = channels;\r
+\r
+ if ( firstChannel != 0 ) return false;\r
+\r
+ bool sr_found = false;\r
+ for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {\r
+ if ( sampleRate == *sr ) {\r
+ sr_found = true;\r
+ stream_.sampleRate = sampleRate;\r
+ ss.rate = sampleRate;\r
+ break;\r
+ }\r
}\r
- if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {\r
- status |= RTAUDIO_INPUT_OVERFLOW;\r
- apiInfo->xrun[1] = false;\r
+ if ( !sr_found ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";\r
+ return false;\r
}\r
- doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
- stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );\r
\r
- if ( doStopStream == 2 ) {\r
- abortStream();\r
- return;\r
+ bool sf_found = 0;\r
+ for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;\r
+ sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {\r
+ if ( format == sf->rtaudio_format ) {\r
+ sf_found = true;\r
+ stream_.userFormat = sf->rtaudio_format;\r
+ stream_.deviceFormat[mode] = stream_.userFormat;\r
+ ss.format = sf->pa_format;\r
+ break;\r
+ }\r
+ }\r
+ if ( !sf_found ) { // Use internal data format conversion.\r
+ stream_.userFormat = format;\r
+ stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+ ss.format = PA_SAMPLE_FLOAT32LE;\r
}\r
\r
- MUTEX_LOCK( &stream_.mutex );\r
-\r
- // The state might change while waiting on a mutex.\r
- if ( stream_.state == STREAM_STOPPED ) goto unlock;\r
+ // Set other stream parameters.\r
+ if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+ else stream_.userInterleaved = true;\r
+ stream_.deviceInterleaved[mode] = true;\r
+ stream_.nBuffers = 1;\r
+ stream_.doByteSwap[mode] = false;\r
+ stream_.nUserChannels[mode] = channels;\r
+ stream_.nDeviceChannels[mode] = channels + firstChannel;\r
+ stream_.channelOffset[mode] = 0;\r
+ std::string streamName = "RtAudio";\r
\r
- int result;\r
- char *buffer;\r
- int channels;\r
- snd_pcm_t **handle;\r
- snd_pcm_sframes_t frames;\r
- RtAudioFormat format;\r
- handle = (snd_pcm_t **) apiInfo->handles;\r
+ // Set flags for buffer conversion.\r
+ stream_.doConvertBuffer[mode] = false;\r
+ if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+ stream_.doConvertBuffer[mode] = true;\r
+ if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
+ stream_.doConvertBuffer[mode] = true;\r
\r
- if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+ // Allocate necessary internal buffers.\r
+ bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+ stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+ if ( stream_.userBuffer[mode] == NULL ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";\r
+ goto error;\r
+ }\r
+ stream_.bufferSize = *bufferSize;\r
\r
- // Setup parameters.\r
- if ( stream_.doConvertBuffer[1] ) {\r
- buffer = stream_.deviceBuffer;\r
- channels = stream_.nDeviceChannels[1];\r
- format = stream_.deviceFormat[1];\r
- }\r
- else {\r
- buffer = stream_.userBuffer[1];\r
- channels = stream_.nUserChannels[1];\r
- format = stream_.userFormat;\r
- }\r
+ if ( stream_.doConvertBuffer[mode] ) {\r
\r
- // Read samples from device in interleaved/non-interleaved format.\r
- if ( stream_.deviceInterleaved[1] )\r
- result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );\r
- else {\r
- void *bufs[channels];\r
- size_t offset = stream_.bufferSize * formatBytes( format );\r
- for ( int i=0; i<channels; i++ )\r
- bufs[i] = (void *) (buffer + (i * offset));\r
- result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );\r
+ bool makeBuffer = true;\r
+ bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+ if ( mode == INPUT ) {\r
+ if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+ unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+ if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+ }\r
}\r
\r
- if ( result < (int) stream_.bufferSize ) {\r
- // Either an error or overrun occured.\r
- if ( result == -EPIPE ) {\r
- snd_pcm_state_t state = snd_pcm_state( handle[1] );\r
- if ( state == SND_PCM_STATE_XRUN ) {\r
- apiInfo->xrun[1] = true;\r
- result = snd_pcm_prepare( handle[1] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- }\r
- }\r
- else {\r
- errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- }\r
- }\r
- else {\r
- errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
+ if ( makeBuffer ) {\r
+ bufferBytes *= *bufferSize;\r
+ if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+ if ( stream_.deviceBuffer == NULL ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";\r
+ goto error;\r
}\r
- error( RtError::WARNING );\r
- goto tryOutput;\r
}\r
-\r
- // Do byte swapping if necessary.\r
- if ( stream_.doByteSwap[1] )\r
- byteSwapBuffer( buffer, stream_.bufferSize * channels, format );\r
-\r
- // Do buffer conversion if necessary.\r
- if ( stream_.doConvertBuffer[1] )\r
- convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
-\r
- // Check stream latency\r
- result = snd_pcm_delay( handle[1], &frames );\r
- if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;\r
}\r
\r
- tryOutput:\r
+ stream_.device[mode] = device;\r
\r
- if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+ // Setup the buffer conversion information structure.\r
+ if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
\r
- // Setup parameters and do buffer conversion if necessary.\r
- if ( stream_.doConvertBuffer[0] ) {\r
- buffer = stream_.deviceBuffer;\r
- convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
- channels = stream_.nDeviceChannels[0];\r
- format = stream_.deviceFormat[0];\r
+ if ( !stream_.apiHandle ) {\r
+ PulseAudioHandle *pah = new PulseAudioHandle;\r
+ if ( !pah ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";\r
+ goto error;\r
}\r
- else {\r
- buffer = stream_.userBuffer[0];\r
- channels = stream_.nUserChannels[0];\r
- format = stream_.userFormat;\r
+\r
+ stream_.apiHandle = pah;\r
+ if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";\r
+ goto error;\r
}\r
+ }\r
+ pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
\r
- // Do byte swapping if necessary.\r
- if ( stream_.doByteSwap[0] )\r
- byteSwapBuffer(buffer, stream_.bufferSize * channels, format);\r
+ int error;\r
+ if ( options && !options->streamName.empty() ) streamName = options->streamName;\r
+ switch ( mode ) {\r
+ case INPUT:\r
+ pa_buffer_attr buffer_attr;\r
+ buffer_attr.fragsize = bufferBytes;\r
+ buffer_attr.maxlength = -1;\r
\r
- // Write samples to device in interleaved/non-interleaved format.\r
- if ( stream_.deviceInterleaved[0] )\r
- result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );\r
- else {\r
- void *bufs[channels];\r
- size_t offset = stream_.bufferSize * formatBytes( format );\r
- for ( int i=0; i<channels; i++ )\r
- bufs[i] = (void *) (buffer + (i * offset));\r
- result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );\r
+ pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );\r
+ if ( !pah->s_rec ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";\r
+ goto error;\r
}\r
-\r
- if ( result < (int) stream_.bufferSize ) {\r
- // Either an error or underrun occured.\r
- if ( result == -EPIPE ) {\r
- snd_pcm_state_t state = snd_pcm_state( handle[0] );\r
- if ( state == SND_PCM_STATE_XRUN ) {\r
- apiInfo->xrun[0] = true;\r
- result = snd_pcm_prepare( handle[0] );\r
- if ( result < 0 ) {\r
- errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- }\r
- }\r
- else {\r
- errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- }\r
- }\r
- else {\r
- errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";\r
- errorText_ = errorStream_.str();\r
- }\r
- error( RtError::WARNING );\r
- goto unlock;\r
+ break;\r
+ case OUTPUT:\r
+ pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );\r
+ if ( !pah->s_play ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";\r
+ goto error;\r
}\r
-\r
- // Check stream latency\r
- result = snd_pcm_delay( handle[0], &frames );\r
- if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;\r
+ break;\r
+ default:\r
+ goto error;\r
}\r
\r
- unlock:\r
- MUTEX_UNLOCK( &stream_.mutex );\r
+ if ( stream_.mode == UNINITIALIZED )\r
+ stream_.mode = mode;\r
+ else if ( stream_.mode == mode )\r
+ goto error;\r
+ else\r
+ stream_.mode = DUPLEX;\r
\r
- RtApi::tickStreamTime();\r
- if ( doStopStream == 1 ) this->stopStream();\r
-}\r
+ if ( !stream_.callbackInfo.isRunning ) {\r
+ stream_.callbackInfo.object = this;\r
+ stream_.callbackInfo.isRunning = true;\r
+ if ( pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0 ) {\r
+ errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";\r
+ goto error;\r
+ }\r
+ }\r
\r
-extern "C" void *alsaCallbackHandler( void *ptr )\r
-{\r
- CallbackInfo *info = (CallbackInfo *) ptr;\r
- RtApiAlsa *object = (RtApiAlsa *) info->object;\r
- bool *isRunning = &info->isRunning;\r
+ stream_.state = STREAM_STOPPED;\r
+ return true;\r
+ \r
+ error:\r
+ if ( pah && stream_.callbackInfo.isRunning ) {\r
+ pthread_cond_destroy( &pah->runnable_cv );\r
+ delete pah;\r
+ stream_.apiHandle = 0;\r
+ }\r
\r
- while ( *isRunning == true ) {\r
- pthread_testcancel();\r
- object->callbackEvent();\r
+ for ( int i=0; i<2; i++ ) {\r
+ if ( stream_.userBuffer[i] ) {\r
+ free( stream_.userBuffer[i] );\r
+ stream_.userBuffer[i] = 0;\r
+ }\r
}\r
\r
- pthread_exit( NULL );\r
+ if ( stream_.deviceBuffer ) {\r
+ free( stream_.deviceBuffer );\r
+ stream_.deviceBuffer = 0;\r
+ }\r
+\r
+ return FAILURE;\r
}\r
\r
-//******************** End of __LINUX_ALSA__ *********************//\r
+//******************** End of __LINUX_PULSE__ *********************//\r
#endif\r
\r
-\r
#if defined(__LINUX_OSS__)\r
\r
#include <unistd.h>\r
#include <sys/ioctl.h>\r
#include <unistd.h>\r
#include <fcntl.h>\r
-#include "soundcard.h"\r
+#include <sys/soundcard.h>\r
#include <errno.h>\r
#include <math.h>\r
\r
-extern "C" void *ossCallbackHandler(void * ptr);\r
+static void *ossCallbackHandler(void * ptr);\r
\r
// A structure to hold various information related to the OSS API\r
// implementation.\r
int mixerfd = open( "/dev/mixer", O_RDWR, 0 );\r
if ( mixerfd == -1 ) {\r
errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {\r
close( mixerfd );\r
errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return 0;\r
}\r
\r
int mixerfd = open( "/dev/mixer", O_RDWR, 0 );\r
if ( mixerfd == -1 ) {\r
errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( result == -1 ) {\r
close( mixerfd );\r
errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( nDevices == 0 ) {\r
close( mixerfd );\r
errorText_ = "RtApiOss::getDeviceInfo: no devices found!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
if ( device >= nDevices ) {\r
close( mixerfd );\r
errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
+ return info;\r
}\r
\r
oss_audioinfo ainfo;\r
if ( result == -1 ) {\r
errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
if ( info.nativeFormats == 0 ) {\r
errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return info;\r
}\r
\r
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {\r
info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+ if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = SAMPLE_RATES[k];\r
+\r
break;\r
}\r
}\r
else {\r
// Check min and max rate values;\r
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
- if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] )\r
+ if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {\r
info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+ if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+ info.preferredSampleRate = SAMPLE_RATES[k];\r
+ }\r
}\r
}\r
\r
if ( info.sampleRates.size() == 0 ) {\r
errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";\r
errorText_ = errorStream_.str();\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
}\r
else {\r
info.probed = true;\r
{\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiOss::closeStream(): no open stream to close!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
verifyStream();\r
if ( stream_.state == STREAM_RUNNING ) {\r
errorText_ = "RtApiOss::startStream(): the stream is already running!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
result = write( handle->id[0], buffer, samples * formatBytes(format) );\r
if ( result == -1 ) {\r
errorText_ = "RtApiOss::stopStream: audio write error.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
}\r
}\r
\r
MUTEX_UNLOCK( &stream_.mutex );\r
\r
if ( result != -1 ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiOss :: abortStream()\r
verifyStream();\r
if ( stream_.state == STREAM_STOPPED ) {\r
errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
MUTEX_UNLOCK( &stream_.mutex );\r
\r
if ( result != -1 ) return;\r
- error( RtError::SYSTEM_ERROR );\r
+ error( RtAudioError::SYSTEM_ERROR );\r
}\r
\r
void RtApiOss :: callbackEvent()\r
\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
return;\r
}\r
\r
// specific means for determining that.\r
handle->xrun[0] = true;\r
errorText_ = "RtApiOss::callbackEvent: audio write error.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
// Continue on to input section.\r
}\r
}\r
// specific means for determining that.\r
handle->xrun[1] = true;\r
errorText_ = "RtApiOss::callbackEvent: audio read error.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
goto unlock;\r
}\r
\r
if ( doStopStream == 1 ) this->stopStream();\r
}\r
\r
-extern "C" void *ossCallbackHandler( void *ptr )\r
+static void *ossCallbackHandler( void *ptr )\r
{\r
CallbackInfo *info = (CallbackInfo *) ptr;\r
RtApiOss *object = (RtApiOss *) info->object;\r
\r
// This method can be modified to control the behavior of error\r
// message printing.\r
-void RtApi :: error( RtError::Type type )\r
+void RtApi :: error( RtAudioError::Type type )\r
{\r
errorStream_.str(""); // clear the ostringstream\r
- if ( type == RtError::WARNING && showWarnings_ == true )\r
+\r
+ RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;\r
+ if ( errorCallback ) {\r
+ // abortStream() can generate new error messages. Ignore them. Just keep original one.\r
+\r
+ if ( firstErrorOccurred_ )\r
+ return;\r
+\r
+ firstErrorOccurred_ = true;\r
+ const std::string errorMessage = errorText_;\r
+\r
+ if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {\r
+ stream_.callbackInfo.isRunning = false; // exit from the thread\r
+ abortStream();\r
+ }\r
+\r
+ errorCallback( type, errorMessage );\r
+ firstErrorOccurred_ = false;\r
+ return;\r
+ }\r
+\r
+ if ( type == RtAudioError::WARNING && showWarnings_ == true )\r
std::cerr << '\n' << errorText_ << "\n\n";\r
- else if ( type != RtError::WARNING )\r
- throw( RtError( errorText_, type ) );\r
+ else if ( type != RtAudioError::WARNING )\r
+ throw( RtAudioError( errorText_, type ) );\r
}\r
\r
void RtApi :: verifyStream()\r
{\r
if ( stream_.state == STREAM_CLOSED ) {\r
errorText_ = "RtApi:: a stream is not open!";\r
- error( RtError::INVALID_USE );\r
+ error( RtAudioError::INVALID_USE );\r
}\r
}\r
\r
stream_.callbackInfo.callback = 0;\r
stream_.callbackInfo.userData = 0;\r
stream_.callbackInfo.isRunning = false;\r
+ stream_.callbackInfo.errorCallback = 0;\r
for ( int i=0; i<2; i++ ) {\r
stream_.device[i] = 11111;\r
stream_.doConvertBuffer[i] = false;\r
{\r
if ( format == RTAUDIO_SINT16 )\r
return 2;\r
- else if ( format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 ||\r
- format == RTAUDIO_FLOAT32 )\r
+ else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )\r
return 4;\r
else if ( format == RTAUDIO_FLOAT64 )\r
return 8;\r
+ else if ( format == RTAUDIO_SINT24 )\r
+ return 3;\r
else if ( format == RTAUDIO_SINT8 )\r
return 1;\r
\r
errorText_ = "RtApi::formatBytes: undefined format.";\r
- error( RtError::WARNING );\r
+ error( RtAudioError::WARNING );\r
\r
return 0;\r
}\r
}\r
}\r
else if (info.inFormat == RTAUDIO_SINT24) {\r
- Int32 *in = (Int32 *)inBuffer;\r
+ Int24 *in = (Int24 *)inBuffer;\r
scale = 1.0 / 8388607.5;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]] & 0x00ffffff);\r
+ out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());\r
out[info.outOffset[j]] += 0.5;\r
out[info.outOffset[j]] *= scale;\r
}\r
}\r
}\r
else if (info.inFormat == RTAUDIO_SINT24) {\r
- Int32 *in = (Int32 *)inBuffer;\r
+ Int24 *in = (Int24 *)inBuffer;\r
scale = (Float32) ( 1.0 / 8388607.5 );\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]] & 0x00ffffff);\r
+ out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());\r
out[info.outOffset[j]] += 0.5;\r
out[info.outOffset[j]] *= scale;\r
}\r
out += info.outJump;\r
}\r
}\r
- else if (info.inFormat == RTAUDIO_SINT24) { // Hmmm ... we could just leave it in the lower 3 bytes\r
- Int32 *in = (Int32 *)inBuffer;\r
+ else if (info.inFormat == RTAUDIO_SINT24) {\r
+ Int24 *in = (Int24 *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
+ out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();\r
out[info.outOffset[j]] <<= 8;\r
}\r
in += info.inJump;\r
}\r
}\r
else if (info.outFormat == RTAUDIO_SINT24) {\r
- Int32 *out = (Int32 *)outBuffer;\r
+ Int24 *out = (Int24 *)outBuffer;\r
if (info.inFormat == RTAUDIO_SINT8) {\r
signed char *in = (signed char *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
- out[info.outOffset[j]] <<= 16;\r
+ out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);\r
+ //out[info.outOffset[j]] <<= 16;\r
}\r
in += info.inJump;\r
out += info.outJump;\r
Int16 *in = (Int16 *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
- out[info.outOffset[j]] <<= 8;\r
+ out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);\r
+ //out[info.outOffset[j]] <<= 8;\r
}\r
in += info.inJump;\r
out += info.outJump;\r
}\r
else if (info.inFormat == RTAUDIO_SINT24) {\r
// Channel compensation and/or (de)interleaving only.\r
- Int32 *in = (Int32 *)inBuffer;\r
+ Int24 *in = (Int24 *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
out[info.outOffset[j]] = in[info.inOffset[j]];\r
Int32 *in = (Int32 *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
- out[info.outOffset[j]] >>= 8;\r
+ out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);\r
+ //out[info.outOffset[j]] >>= 8;\r
}\r
in += info.inJump;\r
out += info.outJump;\r
}\r
}\r
else if (info.inFormat == RTAUDIO_SINT24) {\r
- Int32 *in = (Int32 *)inBuffer;\r
+ Int24 *in = (Int24 *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 8) & 0x0000ffff);\r
+ out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);\r
}\r
in += info.inJump;\r
out += info.outJump;\r
}\r
}\r
else if (info.inFormat == RTAUDIO_SINT24) {\r
- Int32 *in = (Int32 *)inBuffer;\r
+ Int24 *in = (Int24 *)inBuffer;\r
for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
for (j=0; j<info.channels; j++) {\r
- out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 16) & 0x000000ff);\r
+ out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);\r
}\r
in += info.inJump;\r
out += info.outJump;\r
}\r
}\r
\r
- //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }\r
- //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }\r
- //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }\r
+//static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }\r
+//static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }\r
+//static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }\r
\r
void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )\r
{\r
- register char val;\r
- register char *ptr;\r
+ char val;\r
+ char *ptr;\r
\r
ptr = buffer;\r
if ( format == RTAUDIO_SINT16 ) {\r
ptr += 2;\r
}\r
}\r
- else if ( format == RTAUDIO_SINT24 ||\r
- format == RTAUDIO_SINT32 ||\r
+ else if ( format == RTAUDIO_SINT32 ||\r
format == RTAUDIO_FLOAT32 ) {\r
for ( unsigned int i=0; i<samples; i++ ) {\r
// Swap 1st and 4th bytes.\r
ptr += 3;\r
}\r
}\r
+ else if ( format == RTAUDIO_SINT24 ) {\r
+ for ( unsigned int i=0; i<samples; i++ ) {\r
+ // Swap 1st and 3rd bytes.\r
+ val = *(ptr);\r
+ *(ptr) = *(ptr+2);\r
+ *(ptr+2) = val;\r
+\r
+ // Increment 2 more bytes.\r
+ ptr += 2;\r
+ }\r
+ }\r
else if ( format == RTAUDIO_FLOAT64 ) {\r
for ( unsigned int i=0; i<samples; i++ ) {\r
// Swap 1st and 8th bytes\r