示例#1
0
audioSink::audioSink	(int16_t latency,
                         QComboBox *s,
                         RingBuffer<int16_t> *b): audioBase (b) {
    int32_t	i;
    this	-> latency	= latency;
    this	-> streamSelector	= s;

    this	-> CardRate	= 48000;
    this	-> latency	= latency;
    _O_Buffer		= new RingBuffer<float>(2 * 32768);
    portAudio		= false;
    writerRunning		= false;
    if (Pa_Initialize () != paNoError) {
        fprintf (stderr, "Initializing Pa for output failed\n");
        return;
    }

    portAudio	= true;
    qDebug ("Hostapis: %d\n", Pa_GetHostApiCount ());

    for (i = 0; i < Pa_GetHostApiCount (); i ++)
        qDebug ("Api %d is %s\n", i, Pa_GetHostApiInfo (i) -> name);

    numofDevices	= Pa_GetDeviceCount ();
    outTable	= new int16_t [numofDevices + 1];
    for (i = 0; i < numofDevices; i ++)
        outTable [i] = -1;
    ostream		= NULL;
    setupChannels (streamSelector);
    connect (streamSelector, SIGNAL (activated (int)),
             this,  SLOT (set_streamSelector (int)));
    streamSelector	-> show ();
    selectDefaultDevice ();

}
示例#2
0
/*
 *	The class is the sink for the data generated.
 *	It will send the data to the soundcard
 */
	paWriter::paWriter	(int32_t cardRate,
	                         uint8_t  Latency) {
int32_t	i;

	CardRate		= cardRate;
	this -> Latency		= Latency;
	this	-> Latency	= LOWLATENCY;
	_O_Buffer		= new RingBuffer<float>(4 * 16384);
	portAudio		= false;
	writerRunning		= false;

	if (Pa_Initialize () != paNoError) {
	   fprintf (stderr, "Initializing Pa for output failed\n");
	   return;
	}
	portAudio	= true;

	qDebug ("Hostapis: %d\n", Pa_GetHostApiCount ());

	for (i = 0; i < Pa_GetHostApiCount (); i ++)
	   qDebug ("Api %d is %s\n", i, Pa_GetHostApiInfo (i) -> name);

	numofDevices	= Pa_GetDeviceCount ();
	ostream		= NULL;
}
示例#3
0
void
CPaCommon::Enumerate(vector < string > &choices, vector < string > &descriptions)
{
    vector < string > tmp;

    names.clear();
    descriptions.clear();
	names.push_back(""); /* default device */
	descriptions.push_back("");

    int numDevices = Pa_GetDeviceCount();
    if (numDevices < 0)
        throw string("PortAudio error: ") + Pa_GetErrorText(numDevices);
    PaHostApiIndex nApis = Pa_GetHostApiCount();

    for (int i = 0; i < numDevices; i++)
    {
        const PaDeviceInfo *deviceInfo = Pa_GetDeviceInfo(i);
        if (( is_capture && deviceInfo->maxInputChannels > 1)
                || ( (!is_capture) && deviceInfo->maxOutputChannels > 1))
        {
            string api="";
            if (nApis>1)
            {
                const PaHostApiInfo* info = Pa_GetHostApiInfo(deviceInfo->hostApi);
                if (info)
                    api = string(info->name)+":";
            }
            names.push_back(api+deviceInfo->name);
            devices.push_back(i);
        }
    }
    choices = names;
}
示例#4
0
JNIEXPORT jobject JNICALL Java_org_jpab_PortAudio_getHostAPIsAsBuffer(JNIEnv *env, jclass paClass) {
	HostAPI * host_api;
	const PaHostApiInfo * host_api_info;
	const UINT8 count = Pa_GetHostApiCount();
	UINT16 index, size = HOST_API_SIZE * count, offset = 0, temp;
	char * buffer = (char *)malloc(size);
	for (index = 0; index < count; index ++) {
        host_api_info = Pa_GetHostApiInfo(index);
		host_api = (HostAPI *) (buffer + offset);
		host_api->default_input_device = host_api_info->defaultInputDevice == -1 ? -1 : Pa_HostApiDeviceIndexToDeviceIndex(index, host_api_info->defaultInputDevice);
		host_api->default_output_device = host_api_info->defaultOutputDevice == -1 ? -1 : Pa_HostApiDeviceIndexToDeviceIndex(index, host_api_info->defaultOutputDevice);
		if (host_api->default_input_device < -1) host_api->default_input_device = -1;
		if (host_api->default_output_device < -1) host_api->default_output_device = -1;
		host_api->device_count = host_api_info->deviceCount;
		host_api->type = host_api_info->type;
		host_api->index = index;
		temp = strlen(host_api_info->name);
		host_api->name_length = temp;
		size += temp;
		buffer = (char *) realloc(buffer, size);
		offset += HOST_API_SIZE;
		memcpy(buffer + offset, host_api_info->name, temp);
		offset += temp;
	}
	return env->NewDirectByteBuffer(buffer, (jint) size);
}
示例#5
0
// print info about the audio device to stdout
void pa_printdevinfo()
{
	mexPrintf("Printing audio devices...\n");

	Pa_Initialize();		

	int dev_type_indx = -1;
	const PaHostApiInfo* Api_Info;
	int num_APIs = (int )Pa_GetHostApiCount();
	for (int i=0; i<num_APIs; i++) {
 		Api_Info = Pa_GetHostApiInfo(i);
		if (strcmp(Api_Info->name,API_NAME)==0)
			dev_type_indx = i;
	}
	if (dev_type_indx == -1) {
		return;
	}
	Api_Info = Pa_GetHostApiInfo(dev_type_indx);


	for( int d = 0; d < Api_Info->deviceCount; d++) {
		//PaDeviceIndex dev_indx = Pa_HostApiDeviceIndexToDeviceIndex(dev_type_indx, d);
		//printdevice((int )dev_indx);
		printdevice(dev_type_indx, d);
	}
	
	Pa_Terminate();
}
示例#6
0
void AudioPortAudioSetupUtil::updateDevices()
{
	PaError err = Pa_Initialize();
	if( err != paNoError ) {
		printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) );
		return;
	}

	// get active backend 
	const QString& backend = m_backendModel.currentText();
	int hostApi = 0;
	const PaHostApiInfo * hi;
	for( int i = 0; i < Pa_GetHostApiCount(); ++i )
	{
		hi = Pa_GetHostApiInfo( i );
		if( backend == hi->name )
		{
			hostApi = i;
			break;
		}
	}

	// get devices for selected backend
	m_deviceModel.clear();
	const PaDeviceInfo * di;
	for( int i = 0; i < Pa_GetDeviceCount(); ++i )
	{
		di = Pa_GetDeviceInfo( i );
		if( di->hostApi == hostApi )
		{
			m_deviceModel.addItem( di->name );
		}
	}
	Pa_Terminate();
}
示例#7
0
void GetAudioInfo()
{
	PaHostApiIndex ApiCount = Pa_GetHostApiCount();

	Log::Logf("AUDIO: The default API is %d\n", Pa_GetDefaultHostApi());

	for (PaHostApiIndex i = 0; i < ApiCount; i++)
	{
		const PaHostApiInfo* Index = Pa_GetHostApiInfo(i);
		Log::Logf("(%d) %s: %d (%d)\n", i, Index->name, Index->defaultOutputDevice, Index->type);

#ifdef WIN32
		if (Index->type == paWASAPI)
			DefaultWasapiDevice = Index->defaultOutputDevice;
		else if (Index->type == paDirectSound)
			DefaultDSDevice = Index->defaultOutputDevice;
#endif
	}

	Log::Logf("\nAUDIO: The audio devices are\n");

	PaDeviceIndex DevCount = Pa_GetDeviceCount();
	for (PaDeviceIndex i = 0; i < DevCount; i++)
	{
		const PaDeviceInfo *Info = Pa_GetDeviceInfo(i);
		Log::Logf("(%d): %s\n", i, Info->name);
		Log::Logf("\thighLat: %f, lowLat: %f\n", Info->defaultHighOutputLatency, Info->defaultLowOutputLatency);
		Log::Logf("\tsampleRate: %f, hostApi: %d\n", Info->defaultSampleRate, Info->hostApi);
		Log::Logf("\tmaxchannels: %d\n", Info->maxOutputChannels);
	}
}
std::vector<ApiInfo> getHostApis(){
    // Returns information about available host apis. Currently uses portaudio.
    if( Pa_Initialize() != paNoError ) throw std::runtime_error("Portaudio could not be initialized during 'getHostApis'.");

    PaHostApiIndex apiCount = Pa_GetHostApiCount();
    PaDeviceIndex devCount = 0;
    PaDeviceIndex devNum = 0;
    std::vector<DevInfo> devInf;
    const PaHostApiInfo* p_ApiInf;
    const PaDeviceInfo* p_DevInf;
    std::vector<ApiInfo> vApiInf(apiCount);

    for(int api=0; api<apiCount; ++api){
        p_ApiInf = Pa_GetHostApiInfo(api);
        vApiInf[api].apiName = p_ApiInf->name;
        devCount = p_ApiInf->deviceCount;
        devInf.resize(devCount);
        for(int dev=0; dev<devCount; ++dev){
            devNum = Pa_HostApiDeviceIndexToDeviceIndex(api, dev);
            p_DevInf = Pa_GetDeviceInfo(devNum);
            devInf[dev].devName = p_DevInf->name;
            devInf[dev].numInputs = p_DevInf->maxInputChannels;
            devInf[dev].numOutputs= p_DevInf->maxOutputChannels;
            vApiInf[api].devices = devInf;
		}
    }
    if( Pa_Terminate() != paNoError ) throw std::runtime_error("Error terminating portaudio during 'getHostApis'.");
    return vApiInf;
}
QHash<int, QString> hostApiNames()
{
    QHash<int, QString> names;
    for (int i = 0; i < Pa_GetHostApiCount(); ++i)
       names[i] = Pa_GetHostApiInfo(i)->name;

    return names;
}
示例#10
0
文件: init.c 项目: andresy/lua---pa
static int pa_hostapicount(lua_State *L)
{
  int narg = lua_gettop(L);
  if(narg != 0)
    luaL_error(L, "invalid arguments: no argument expected");

  lua_pushnumber(L, Pa_GetHostApiCount());
  return 1;
}
示例#11
0
int HostApiList::rowCount(const QModelIndex &parent) const
{
    (void)parent;
    int apiCount = Pa_GetHostApiCount();

    if (apiCount < 0)
        qWarning() << Pa_GetErrorText(apiCount);

    return apiCount;
}
示例#12
0
/* Internal: Get PortAudio default output device ID */
static int pa_get_default_output_dev(int channel_count)
{
    int i, count;

    /* Special for Windows - try to use the DirectSound implementation
     * first since it provides better latency.
     */
#if PJMEDIA_PREFER_DIRECT_SOUND
    if (Pa_HostApiTypeIdToHostApiIndex(paDirectSound) >= 0) {
	const PaHostApiInfo *pHI;
	int index = Pa_HostApiTypeIdToHostApiIndex(paDirectSound);
	pHI = Pa_GetHostApiInfo(index);
	if (pHI) {
	    const PaDeviceInfo *paDevInfo = NULL;
	    paDevInfo = Pa_GetDeviceInfo(pHI->defaultOutputDevice);
	    if (paDevInfo && paDevInfo->maxOutputChannels >= channel_count)
		return pHI->defaultOutputDevice;
	}
    }
#endif

    /* Enumerate the host api's for the default devices, and return
     * the device with suitable channels.
     */
    count = Pa_GetHostApiCount();
    for (i=0; i < count; ++i) {
	const PaHostApiInfo *pHAInfo;

	pHAInfo = Pa_GetHostApiInfo(i);
	if (!pHAInfo)
	    continue;

	if (pHAInfo->defaultOutputDevice >= 0) {
	    const PaDeviceInfo *paDevInfo;

	    paDevInfo = Pa_GetDeviceInfo(pHAInfo->defaultOutputDevice);

	    if (paDevInfo->maxOutputChannels >= channel_count)
		return pHAInfo->defaultOutputDevice;
	}
    }

    /* If still no device is found, enumerate all devices */
    count = Pa_GetDeviceCount();
    for (i=0; i<count; ++i) {
	const PaDeviceInfo *paDevInfo;

	paDevInfo = Pa_GetDeviceInfo(i);
	if (paDevInfo->maxOutputChannels >= channel_count)
	    return i;
    }

    return -1;
}
示例#13
0
QStringList Portaudio::apiList() const
      {
      QStringList al;

      PaHostApiIndex apis = Pa_GetHostApiCount();
      for (PaHostApiIndex i = 0; i < apis; ++i) {
            const PaHostApiInfo* info = Pa_GetHostApiInfo(i);
            if (info)
                  al.append(info->name);
            }
      return al;
      }
示例#14
0
static const PaHostApiInfo *findHostAPIInfo(const char *hostAPI, PaHostApiIndex *index)
{
  const PaHostApiInfo *hostAPIInfo = NULL;
  PaHostApiIndex i;

  for (i = 0; i < Pa_GetHostApiCount(); i++) {
    hostAPIInfo = Pa_GetHostApiInfo(i);

    if (hostAPIInfo && strcmp(hostAPI, hostAPIInfo->name) == 0) {
      break;
    }
  }
  if (i >= Pa_GetHostApiCount()) {
    i = Pa_GetDefaultHostApi();
    hostAPIInfo = Pa_GetHostApiInfo(i);
  }

  if (index) {
    *index = i;
  }
  return hostAPIInfo;
}
示例#15
0
int AudioAdapter::SelectApi(){
	cout << "Query Supported Host Api" <<endl;
	int i,res=0;
	for(i=0;i<hostApiCount;i++){
			cout << "[" << i << "]	"<< Pa_GetHostApiInfo(i)->name << endl;
	}
	do{
		cout << "Choose Host Api : ";
		cin >> res;
	}while(! (0<=res && res<Pa_GetHostApiCount()) );

	return res;
}
示例#16
0
/*
 *	The class is the sink for the data generated
 *	Note that for DAB, we always take 48000 as outputrate
 *	The only parameter is the combobox for selection (which
 *	we fill first)
 */
	audioSink::audioSink	(QComboBox *s) {
int32_t	i;

	this	-> streamSelector	= s;

	_O_Buffer		= new RingBuffer<float>(16 * 32768);
	portAudio		= false;
	writerRunning		= false;

	if (Pa_Initialize () != paNoError) {
	   fprintf (stderr, "Initializing Pa for output failed\n");
	   return;
	}

	portAudio	= true;
	qDebug ("Hostapis: %d\n", Pa_GetHostApiCount ());

	for (i = 0; i < Pa_GetHostApiCount (); i ++)
	   qDebug ("Api %d is %s\n", i, Pa_GetHostApiInfo (i) -> name);

	numofDevices	= Pa_GetDeviceCount ();
	
	outTable	= new int16_t [numofDevices + 1];
	for (i = 0; i < numofDevices; i ++)
	   outTable [i] = -1;
	ostream		= NULL;
	setupChannels (streamSelector);
	connect (streamSelector, SIGNAL (activated (int)),
	         this,  SLOT (set_streamSelector (int)));
	streamSelector	-> show ();
	ostream		= NULL;
	dumpFile	= NULL;
//
//	data may enter with different samplerates, all data
//	is mapped onto a rate of 48000
	f_16000		= new LowPassFIR (5, 16000, 48000);
	f_24000		= new LowPassFIR (5, 24000, 48000);
	f_32000		= new LowPassFIR (5, 32000, 96000);
}
示例#17
0
/*
 * Init sound library.
 */
PJ_DEF(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory)
{
    int err;

    snd_mgr.factory = factory;
    err = Pa_Initialize();

    PJ_LOG(4,(THIS_FILE, "PortAudio sound library initialized, status=%d", err));
    PJ_LOG(4,(THIS_FILE, "PortAudio host api count=%d",
			 Pa_GetHostApiCount()));
    PJ_LOG(4,(THIS_FILE, "Sound device count=%d",
			 pjmedia_snd_get_dev_count()));

    return err ? PJMEDIA_ERRNO_FROM_PORTAUDIO(err) : PJ_SUCCESS;
}
示例#18
0
QStringList AudioPA::DeviceList(bool typeInput)
{
	//This static method may get called before constructor
	//So we have to make sure Pa_Initialize is called, make sure we have matching Pa_Terminate()
	Pa_Initialize();
	QStringList devList;
	QString di;
	int apiCnt = Pa_GetHostApiCount();
	const PaHostApiInfo *apiInfo;
	const PaDeviceInfo *devInfo;

	for (int i = 0; i < apiCnt; i++)
	{
		apiInfo = Pa_GetHostApiInfo(i);
		for (int j=0; j < apiInfo->deviceCount; j++)
		{
			devInfo = Pa_GetDeviceInfo(j);
			//Note: PortAudio must be compiled as ASIO files to enable ASIO4ALL driver support
            //Ignore device types we don't support
            if (apiInfo->type==paMME
                    || apiInfo->type==paASIO
                    || apiInfo->type==paDirectSound
                    //Mac types
                    || apiInfo->type==paCoreAudio)
            {

                //Ignore input and output devices that only have 1 channel
                //We need stereo in for I/Q
                if(typeInput && devInfo->maxInputChannels > 1)
                {
                    di = di.sprintf("%2d:%s:%s",Pa_HostApiDeviceIndexToDeviceIndex(i,j),
                        apiInfo->name,devInfo->name);
                    devList << di;
                }
                else if(!typeInput && devInfo->maxOutputChannels > 1)
                {
                    //This is the fully qualified name that will be saved and used to find the same device
                    //See FindDeviceByName()
                    di = di.sprintf("%2d:%s:%s",Pa_HostApiDeviceIndexToDeviceIndex(i,j),
                        apiInfo->name,devInfo->name);
                    devList << di;
                }
            }
        }
	}
	Pa_Terminate();
	return devList;
}
void PortAudioSettingsPage::populateHostAPIList()
{
  PaHostApiIndex i;
  hostAPIList->clear();
  for (i = 0; i < Pa_GetHostApiCount(); i++) {
    const PaHostApiInfo *hostAPIInfo = Pa_GetHostApiInfo(i);
    if (!hostAPIInfo) {
      continue;
    }
    if (hostAPIInfo->deviceCount <= 0) {
      continue;
    }
    QString name = QString::fromUtf8(hostAPIInfo->name);
    hostAPIList->addItem(name, i);
  }
}
示例#20
0
DeviceSourceMap* DeviceManager::GetDefaultDevice(int hostIndex, int isInput)
{
   if (hostIndex < 0 || hostIndex >= Pa_GetHostApiCount()) {
      return NULL;
   }

   const struct PaHostApiInfo *apiinfo = Pa_GetHostApiInfo(hostIndex);   // get info on API
   std::vector<DeviceSourceMap> & maps = isInput ? mInputDeviceSourceMaps : mOutputDeviceSourceMaps;
   size_t i;
   int targetDevice = isInput ? apiinfo->defaultInputDevice : apiinfo->defaultOutputDevice;

   for (i = 0; i < maps.size(); i++) {
      if (maps[i].deviceIndex == targetDevice)
         return &maps[i];
   }
   
   wxLogDebug(wxT("GetDefaultDevice() no default device"));
   return NULL;
}
示例#21
0
int Portaudio::currentDevice() const
      {
      PaDeviceIndex idx = preferences.portaudioDevice;
      if (idx < 0)
            idx = Pa_GetDefaultOutputDevice();

      for (int api = 0; api < Pa_GetHostApiCount(); ++api) {
            const PaHostApiInfo* info = Pa_GetHostApiInfo(api);
            if (info) {
                  for (int k = 0; k < info->deviceCount; ++k) {
                        PaDeviceIndex i = Pa_HostApiDeviceIndexToDeviceIndex(api, k);
                        if (i == idx)
                              return k;
                        }
                  }
            }
      qDebug("Portaudio: no current ApiDevice found for device %d", idx);
      return -1;
      }
示例#22
0
const QList<audioDevice> PortAudioSystem::enumerateDevices(bool input, PaDeviceIndex match) {
	PaHostApiIndex iApiCnt;
	PaHostApiIndex iApiIndex;
	int            iApiDevIndex;
	PaDeviceIndex  iDevIndex;
	const PaDeviceInfo *pDevInfo;

	QList<audioDevice> adl;

	adl << audioDevice(tr("Default Device"), -1);

	iApiCnt = Pa_GetHostApiCount();
	for (iApiIndex = 0; iApiIndex < iApiCnt; iApiIndex++) {
		const PaHostApiInfo *apiInfo = Pa_GetHostApiInfo(iApiIndex);
		if (!apiInfo)
			continue;

		QString qsApiName = QLatin1String(apiInfo->name);

		for (iApiDevIndex = 0; iApiDevIndex < apiInfo->deviceCount; iApiDevIndex++) {
			iDevIndex = Pa_HostApiDeviceIndexToDeviceIndex(iApiIndex, iApiDevIndex);
			pDevInfo = Pa_GetDeviceInfo(iDevIndex);
			if (!pDevInfo)
				continue;

			QString qsDevName = QLatin1String(pDevInfo->name);

			if ((input && (pDevInfo->maxInputChannels > 0)) ||
			        (!input && (pDevInfo->maxOutputChannels > 0)))
				adl << audioDevice(qsApiName + QLatin1String(": ") + qsDevName, iDevIndex);
		}
	}
	for (int i=0;i<adl.count();++i) {
		if (adl.at(i).second == match) {
			audioDevice ad = adl.takeAt(i);
			adl.prepend(ad);
			break;
		}
	}
	return adl;
}
示例#23
0
/* API: Init factory */
static pj_status_t pa_init(pjmedia_aud_dev_factory *f)
{
    int err;

    PJ_UNUSED_ARG(f);

#ifdef USE_PA_DEBUG_PRINT
    PaUtil_SetDebugPrintFunction(&pa_log_cb);
#endif

    err = Pa_Initialize();

    PJ_LOG(4,(THIS_FILE, 
	      "PortAudio sound library initialized, status=%d", err));
    PJ_LOG(4,(THIS_FILE, "PortAudio host api count=%d",
			 Pa_GetHostApiCount()));
    PJ_LOG(4,(THIS_FILE, "Sound device count=%d",
			 pa_get_dev_count(f)));

    return err ? PJMEDIA_AUDIODEV_ERRNO_FROM_PORTAUDIO(err) : PJ_SUCCESS;
}
示例#24
0
int AudioPA::FindDeviceByName(QString name, bool inputDevice)
{
    QString di;
    int apiCnt = Pa_GetHostApiCount();
    const PaHostApiInfo *apiInfo;
    const PaDeviceInfo *devInfo;

    for (int i = 0; i < apiCnt; i++)
    {
        apiInfo = Pa_GetHostApiInfo(i);
        for (int j=0; j < apiInfo->deviceCount; j++){
            devInfo = Pa_GetDeviceInfo(j);
            if ((inputDevice && devInfo->maxInputChannels > 1) || (!inputDevice && devInfo->maxOutputChannels > 0)){
                //Must be EXACT format as returned by DeviceList, minus device index number
                di = di.sprintf("%s:%s",apiInfo->name,devInfo->name);
                if (di == name)
                    return Pa_HostApiDeviceIndexToDeviceIndex(i,j); //Index
            }
        }
    }
    return -1; //Not found
}
示例#25
0
/* Get PortAudio default output device ID */
static int pa_get_default_output_dev(int channel_count)
{
    int i, count;

    /* Enumerate the host api's for the default devices, and return
     * the device with suitable channels.
     */
    count = Pa_GetHostApiCount();
    for (i=0; i < count; ++i) {
	const PaHostApiInfo *pHAInfo;

	pHAInfo = Pa_GetHostApiInfo(i);
	if (!pHAInfo)
	    continue;

	if (pHAInfo->defaultOutputDevice >= 0) {
	    const PaDeviceInfo *paDevInfo;

	    paDevInfo = Pa_GetDeviceInfo(pHAInfo->defaultOutputDevice);

	    if (paDevInfo->maxOutputChannels >= channel_count)
		return pHAInfo->defaultOutputDevice;
	}
    }

    /* If still no device is found, enumerate all devices */
    count = Pa_GetDeviceCount();
    for (i=0; i<count; ++i) {
	const PaDeviceInfo *paDevInfo;

	paDevInfo = Pa_GetDeviceInfo(i);
	if (paDevInfo->maxOutputChannels >= channel_count)
	    return i;
    }
    
    return -1;
}
示例#26
0
void audiosource_portaudio::init() {
	err = Pa_Initialize();
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_Initialize");
	}

	PaHostApiIndex api_idx;

	const PaHostApiInfo* info = Pa_GetHostApiInfo(Pa_GetDefaultHostApi());

	std::cerr << "Default device: " << info->name << std::endl;

	for (api_idx = 0; api_idx < Pa_GetHostApiCount(); ++api_idx) {
		info = Pa_GetHostApiInfo(api_idx);
		std::cerr << "device " << api_idx << ": " << info->name << std::endl;
	}

	//int frames_per_buffer = get_sample_rate();
	int frames_per_buffer = paFramesPerBufferUnspecified;

	/*
	 * We have two separate streams for input and output to work-around a Debian specific
	 * bug on PortAudio.
	 */

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_in,
    							get_in_channel_count(),          /* input channels */
                                0,          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_in_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_in );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_out,
    							0,          /* input channels */
    							get_out_channel_count(),          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_out_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_out );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}
}
bool S9xPortAudioSoundDriver::open_device()
{
    PaStreamParameters param;
    const PaDeviceInfo *device_info;
    const PaHostApiInfo *hostapi_info;
    PaError err = paNoError;

    if (audio_stream != NULL)
    {
        printf("Shutting down sound for reset\n");
        err = Pa_CloseStream(audio_stream);

        if (err != paNoError)
        {
            fprintf(stderr,
                    "Couldn't reset audio stream.\nError: %s\n",
                    Pa_GetErrorText(err));
            return true;
        }

        audio_stream = NULL;
    }

    param.channelCount = 2;
    param.sampleFormat = paInt16;
    param.hostApiSpecificStreamInfo = NULL;

    printf("PortAudio sound driver initializing...\n");

    for (int i = 0; i < Pa_GetHostApiCount(); i++)
    {
        printf("    --> ");

        hostapi_info = Pa_GetHostApiInfo(i);
        if (!hostapi_info)
        {
            printf("Host API #%d has no info\n", i);
            err = paNotInitialized;
            continue;
        }

        device_info = Pa_GetDeviceInfo(hostapi_info->defaultOutputDevice);
        if (!device_info)
        {
            printf("(%s)...No device info available.\n", hostapi_info->name);
            err = paNotInitialized;
            continue;
        }

        param.device = hostapi_info->defaultOutputDevice;
        param.suggestedLatency = gui_config->sound_buffer_size * 0.001;

        printf("(%s : %s, latency %dms)...\n",
               hostapi_info->name,
               device_info->name,
               (int)(param.suggestedLatency * 1000.0));

        fflush(stdout);

        err = Pa_OpenStream(&audio_stream,
                            NULL,
                            &param,
                            Settings.SoundPlaybackRate,
                            0,
                            paNoFlag,
                            NULL,
                            NULL);

        int frames = Pa_GetStreamWriteAvailable(audio_stream);
        printf ("PortAudio set buffer size to %d frames.\n", frames);
        output_buffer_size = frames;

        if (err == paNoError)
        {
            printf("OK\n");
            break;
        }
        else
        {
            printf("Failed (%s)\n",
                   Pa_GetErrorText(err));
        }
    }

    if (err != paNoError || Pa_GetHostApiCount() < 1)
    {
        fprintf(stderr,
                "Couldn't initialize sound\n");
        return false;
    }

    S9xSetSamplesAvailableCallback(port_audio_samples_available_callback, this);

    fflush(stdout);
    fflush(stderr);

    return true;
}
示例#28
0
void DevicePrefs::OnHost(wxCommandEvent & e)
{
   // Bail if we have no hosts
   if (mHostNames.size() < 1)
      return;

   // Find the index for the host API selected
   int index = -1;
   wxString apiName = mHostNames[mHost->GetCurrentSelection()];
   int nHosts = Pa_GetHostApiCount();
   for (int i = 0; i < nHosts; ++i) {
      wxString name(Pa_GetHostApiInfo(i)->name, wxConvLocal);
      if (name == apiName) {
         index = i;
         break;
      }
   }
   // We should always find the host!
   if (index < 0) {
      wxLogDebug(wxT("DevicePrefs::OnHost(): API index not found"));
      return;
   }

   int nDevices = Pa_GetDeviceCount();

   if (nDevices == 0) {
      mHost->Clear();
      mHost->Append(_("No audio interfaces"), (void *) NULL);
      mHost->SetSelection(0);
   }

   const std::vector<DeviceSourceMap> &inMaps  = DeviceManager::Instance()->GetInputDeviceMaps();
   const std::vector<DeviceSourceMap> &outMaps = DeviceManager::Instance()->GetOutputDeviceMaps();

   wxArrayString playnames;
   wxArrayString recordnames;
   size_t i;
   int devindex;  /* temp variable to hold the numeric ID of each device in turn */
   wxString device;
   wxString recDevice;

   recDevice = mRecordDevice;
   if (this->mRecordSource != wxT(""))
      recDevice += wxString(": ", wxConvLocal) + mRecordSource;

   mRecord->Clear();
   for (i = 0; i < inMaps.size(); i++) {
      if (index == inMaps[i].hostIndex) {
         device   = MakeDeviceSourceString(&inMaps[i]);
         devindex = mRecord->Append(device);
         // We need to const cast here because SetClientData is a wx function
         // It is okay beause the original variable is non-const.
         mRecord->SetClientData(devindex, const_cast<DeviceSourceMap *>(&inMaps[i]));
         if (device == recDevice) {  /* if this is the default device, select it */
            mRecord->SetSelection(devindex);
         }
      }
   }

   mPlay->Clear();
   for (i = 0; i < outMaps.size(); i++) {
      if (index == outMaps[i].hostIndex) {
         device   = MakeDeviceSourceString(&outMaps[i]);
         devindex = mPlay->Append(device);
         mPlay->SetClientData(devindex, const_cast<DeviceSourceMap *>(&outMaps[i]));
         if (device == mPlayDevice) {  /* if this is the default device, select it */
            mPlay->SetSelection(devindex);
         }
      }
   }

   /* deal with not having any devices at all */
   if (mPlay->GetCount() == 0) {
      playnames.Add(_("No devices found"));
      mPlay->Append(playnames[0], (void *) NULL);
      mPlay->SetSelection(0);
   }
   if (mRecord->GetCount() == 0) {
      recordnames.Add(_("No devices found"));
      mRecord->Append(recordnames[0], (void *) NULL);
      mRecord->SetSelection(0);
   }

   /* what if we have no device selected? we should choose the default on
    * this API, as defined by PortAudio. We then fall back to using 0 only if
    * that fails */
   if (mPlay->GetCount() && mPlay->GetSelection() == wxNOT_FOUND) {
      DeviceSourceMap *defaultMap = DeviceManager::Instance()->GetDefaultOutputDevice(index);
      if (defaultMap)
         mPlay->SetStringSelection(MakeDeviceSourceString(defaultMap));

      if (mPlay->GetSelection() == wxNOT_FOUND) {
         mPlay->SetSelection(0);
      }
   }

   if (mRecord->GetCount() && mRecord->GetSelection() == wxNOT_FOUND) {
      DeviceSourceMap *defaultMap = DeviceManager::Instance()->GetDefaultInputDevice(index);
      if (defaultMap)
         mRecord->SetStringSelection(MakeDeviceSourceString(defaultMap));

      if (mPlay->GetSelection() == wxNOT_FOUND) {
         mPlay->SetSelection(0);
      }
   }

   ShuttleGui S(this, eIsCreating);
   S.SetSizeHints(mPlay, mPlay->GetStrings());
   S.SetSizeHints(mRecord, mRecord->GetStrings());
   OnDevice(e);
}
示例#29
0
void PaAudioDevice::chooseWiselyAndCreateNicely(){
	PaError err= Pa_Initialize();

	if(err != paNoError)
		throw global::Exception("AudioDevice::chooseWiselyAndCreateNicely(): PortAudio init failed: %s",  Pa_GetErrorText( err ));

	int32 host_api_count= Pa_GetHostApiCount();
	if (host_api_count < 1)
		throw global::Exception("PortAudio host api count: %i", host_api_count);

	// Look for all audio devices
	int32 num_devices;
	num_devices = Pa_GetDeviceCount();
	if(num_devices < 0) {
		throw global::Exception("AudioDevice::chooseWiselyAndCreateNicely(): Pa_GetDeviceCount failed: %s", Pa_GetErrorText(num_devices));
	} else if (num_devices == 0) {
		throw global::Exception("No audio devices");
	} else {
		print(debug::Ch::Audio, debug::Vb::Trivial, "Available audio devices:");
		const PaDeviceInfo *device_info;

		for(int32 i=0; i<num_devices; i++) {
			device_info = Pa_GetDeviceInfo(i);

			print(debug::Ch::Audio, debug::Vb::Trivial, "	 %s", device_info->name);
			print(debug::Ch::Audio, debug::Vb::Trivial, "		 Low latency: %f", device_info->defaultLowOutputLatency);
			print(debug::Ch::Audio, debug::Vb::Trivial, "		 High latency: %f", device_info->defaultHighOutputLatency);
		}

		util::DynArray<int32> device_ids;
		defaultDeviceDId= -1;

		PaStreamParameters output_params= getDefaultStreamParameters();

		util::DynArray<util::Str8> preferred;
		util::Str8 user_preference= global::g_env.cfg->get<util::Str8>("hardware::audioDevice", "");
		if (!user_preference.empty())
			preferred.pushBack(user_preference);

		preferred.pushBack("default");
		preferred.pushBack("Microsoft Sound Mapper - Output");

		// Find supported devices
		for (int32 i=0; i<num_devices; i++) {
			device_info= Pa_GetDeviceInfo(i);
			output_params.device= i;

			err = Pa_IsFormatSupported(0, &output_params, defaultSampleRate);
			if(err == paFormatIsSupported) {
				device_ids.pushBack(i);
			}
		}

		// Find preferred out of supported
		for (auto& m : preferred){
			auto it=
				std::find_if(device_ids.begin(), device_ids.end(),
					[&m](int32 id){
						if(util::Str8(Pa_GetDeviceInfo(id)->name).lowerCased() == m.lowerCased())
							return true;
						return false;
					}
				);

			if (it != device_ids.end()){
				defaultDeviceDId= *it;
				break;
			}
		}

		// Pick first if no match
		if (defaultDeviceDId == -1){
			for (int32 i : device_ids){
				defaultDeviceDId= i;
				break;
			}
		}

		// Error if no supported devices
		if (defaultDeviceDId == -1)
			throw global::Exception("Sufficient audio device not found");

		device_info= Pa_GetDeviceInfo(defaultDeviceDId);

		print(debug::Ch::Audio, debug::Vb::Trivial, "-> %s\n	With suggested latency: %ims",
					device_info->name,
					(int)(output_params.suggestedLatency*1000));
	}
}
示例#30
0
static int open_output(void)
{
	double rate;
	int n, nrates, include_enc, exclude_enc, ret;
	PaSampleFormat SampleFormat, nativeSampleFormats;
	
	if( dpm.name != NULL)
		ret = sscanf(dpm.name, "%d", &opt_pa_device_id);
	if (dpm.name == NULL || ret == 0 || ret == EOF)
		opt_pa_device_id = -2;
	
#ifdef AU_PORTAUDIO_DLL
#if PORTAUDIO_V19
  {
		if(&dpm == &portaudio_asio_play_mode){
			HostApiTypeId = paASIO;
		} else if(&dpm == &portaudio_win_ds_play_mode){
			HostApiTypeId = paDirectSound;
		} else if(&dpm == &portaudio_win_wmme_play_mode){
			HostApiTypeId = paMME;
		} else {
			return -1;
		}
		if(load_portaudio_dll(0))
				return -1;
  }
#else
  {
		if(&dpm == &portaudio_asio_play_mode){
			if(load_portaudio_dll(PA_DLL_ASIO))
				return -1;
		} else if(&dpm == &portaudio_win_ds_play_mode){
			if(load_portaudio_dll(PA_DLL_WIN_DS))
				return -1;
		} else if(&dpm == &portaudio_win_wmme_play_mode){
			if(load_portaudio_dll(PA_DLL_WIN_WMME))
				return -1;
		} else {
			return -1;
		}
  }
#endif
#endif
	/* if call twice Pa_OpenStream causes paDeviceUnavailable error  */
	if(pa_active == 1) return 0; 
	if(pa_active == 0){
		err = Pa_Initialize();
		if( err != paNoError ) goto error;
		pa_active = 1;
	}

	if (opt_pa_device_id == -1){
		print_device_list();
		goto error2;
	}
#ifdef PORTAUDIO_V19
#ifdef AU_PORTAUDIO_DLL
       {	
        PaHostApiIndex i, ApiCount;
	i = 0;
	ApiCount = Pa_GetHostApiCount();
	do{
		HostApiInfo=Pa_GetHostApiInfo(i);
		if( HostApiInfo->type == HostApiTypeId ) break;
		i++;
	}while ( i < ApiCount );
	if ( i == ApiCount ) goto error;
	
	DeviceIndex = HostApiInfo->defaultOutputDevice;
	if(DeviceIndex==paNoDevice) goto error;
        }
#else
	DeviceIndex = Pa_GetDefaultOutputDevice();
	if(DeviceIndex==paNoDevice) goto error;
#endif
	DeviceInfo = Pa_GetDeviceInfo( DeviceIndex);
	if(DeviceInfo==NULL) goto error;

	if(opt_pa_device_id != -2){
		const PaDeviceInfo *id_DeviceInfo;
    	id_DeviceInfo=Pa_GetDeviceInfo((PaDeviceIndex)opt_pa_device_id);
		if(id_DeviceInfo==NULL) goto error;
		if( DeviceInfo->hostApi == id_DeviceInfo->hostApi){
			DeviceIndex=(PaDeviceIndex)opt_pa_device_id;
			DeviceInfo = id_DeviceInfo;
		}
    }


	if (dpm.encoding & PE_24BIT) {
		SampleFormat = paInt24;
	}else if (dpm.encoding & PE_16BIT) {
		SampleFormat = paInt16;
	}else {
		SampleFormat = paInt8;
	}

	stereo = (dpm.encoding & PE_MONO) ? 1 : 2;
	data_nbyte = (dpm.encoding & PE_16BIT) ? 2 : 1;
	data_nbyte = (dpm.encoding & PE_24BIT) ? 3 : data_nbyte;
	
	pa_data.samplesToGo = 0;
	pa_data.bufpoint = pa_data.buf;
	pa_data.bufepoint = pa_data.buf;
//	firsttime = 1;
	numBuffers = 1; //Pa_GetMinNumBuffers( framesPerBuffer, dpm.rate );
	framesPerInBuffer = numBuffers * framesPerBuffer;
	if (framesPerInBuffer < 4096) framesPerInBuffer = 4096;
	bytesPerInBuffer = framesPerInBuffer * data_nbyte * stereo;

	/* set StreamParameters */
	StreamParameters.device = DeviceIndex;
	StreamParameters.channelCount = stereo;
	if(ctl->id_character != 'r' && ctl->id_character != 'A' && ctl->id_character != 'W' && ctl->id_character != 'P'){
		StreamParameters.suggestedLatency = DeviceInfo->defaultHighOutputLatency;
	}else{
		StreamParameters.suggestedLatency = DeviceInfo->defaultLowOutputLatency;
	}
	StreamParameters.hostApiSpecificStreamInfo = NULL;
	
	if( SampleFormat == paInt16){
		StreamParameters.sampleFormat = paInt16;
		if( paFormatIsSupported != Pa_IsFormatSupported( NULL , 
							&StreamParameters,(double) dpm.rate )){
			StreamParameters.sampleFormat = paInt32;
			conv16_32 = 1;
		} else {
			StreamParameters.sampleFormat = paInt16;
			conv16_32 = 0;
		}
	}else{
		StreamParameters.sampleFormat = SampleFormat;
	}
	err = Pa_IsFormatSupported( NULL ,
                             &StreamParameters,
							(double) dpm.rate );
	if ( err != paNoError) goto error;
	err = Pa_OpenStream(    
		& stream,			/* passes back stream pointer */
		NULL,			 	/* inputStreamParameters */
		&StreamParameters,	/* outputStreamParameters */
		(double) dpm.rate,	/* sample rate */
		paFramesPerBufferUnspecified,	/* frames per buffer */
		paFramesPerBufferUnspecified,	/* PaStreamFlags */
		paCallback,			/* specify our custom callback */
		&pa_data			/* pass our data through to callback */
		);
//		Pa_Sleeep(1);
	if ( err != paNoError) goto error;
	return 0;
	
#else
	if(opt_pa_device_id == -2){
		DeviceID = Pa_GetDefaultOutputDeviceID();
	    if(DeviceID==paNoDevice) goto error2;
	}else{
		DeviceID = opt_pa_device_id;
	}
	DeviceInfo = Pa_GetDeviceInfo( DeviceID);	
	if(DeviceInfo==NULL) goto error2;
	nativeSampleFormats = DeviceInfo->nativeSampleFormats;

	exclude_enc = PE_ULAW | PE_ALAW | PE_BYTESWAP;
	include_enc = PE_SIGNED;
	if (!(nativeSampleFormats & paInt16) && !(nativeSampleFormats & paInt32)) {exclude_enc |= PE_16BIT;}
	if (!(nativeSampleFormats & paInt24)) {exclude_enc |= PE_24BIT;}
    dpm.encoding = validate_encoding(dpm.encoding, include_enc, exclude_enc);

	if (dpm.encoding & PE_24BIT) {
		SampleFormat = paInt24;
	}else if (dpm.encoding & PE_16BIT) {
		if(nativeSampleFormats & paInt16) SampleFormat = paInt16;
		else{
			SampleFormat = paInt32;
			conv16_32 = 1;
		}
	}else {
		SampleFormat = paInt8;
	}

	stereo = (dpm.encoding & PE_MONO) ? 1 : 2;
	data_nbyte = (dpm.encoding & PE_16BIT) ? 2 : 1;
	data_nbyte = (dpm.encoding & PE_24BIT) ? 3 : data_nbyte;

	nrates = DeviceInfo->numSampleRates;
	if (nrates == -1) {	/* range supported */
		rate = dpm.rate;
		if (dpm.rate < DeviceInfo->sampleRates[0]) rate = DeviceInfo->sampleRates[0];
		if (dpm.rate > DeviceInfo->sampleRates[1]) rate = DeviceInfo->sampleRates[1];
	} else {
		rate = DeviceInfo->sampleRates[nrates-1];
		for (n = nrates - 1; n >= 0; n--) {	/* find nearest sample rate */
			if (dpm.rate <= DeviceInfo->sampleRates[n]) rate=DeviceInfo->sampleRates[n];
		}
	}
	dpm.rate = (int32)rate;
	
	pa_data.samplesToGo = 0;
	pa_data.bufpoint = pa_data.buf;
	pa_data.bufepoint = pa_data.buf;
//	firsttime = 1;
	numBuffers = Pa_GetMinNumBuffers( framesPerBuffer, dpm.rate );
	framesPerInBuffer = numBuffers * framesPerBuffer;
	if (framesPerInBuffer < 4096) framesPerInBuffer = 4096;
	bytesPerInBuffer = framesPerInBuffer * data_nbyte * stereo;
//	printf("%d\n",framesPerInBuffer);
//	printf("%d\n",dpm.rate);
	err = Pa_OpenDefaultStream(
    	&stream,        /* passes back stream pointer */
    	0,              /* no input channels */
    	stereo,              /* 2:stereo 1:mono output */
    	SampleFormat,      /* 24bit 16bit 8bit output */
		(double)dpm.rate,          /* sample rate */
    	framesPerBuffer,            /* frames per buffer */
    	numBuffers,              /* number of buffers, if zero then use default minimum */
    	paCallback, /* specify our custom callback */
    	&pa_data);   /* pass our data through to callback */
	if ( err != paNoError && err != paHostError) goto error;
	return 0;

#endif

error:
	ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "PortAudio error: %s\n", Pa_GetErrorText( err ) );
error2:
	Pa_Terminate(); pa_active = 0;
#ifdef AU_PORTAUDIO_DLL
#ifndef PORTAUDIO_V19
  free_portaudio_dll();
#endif
#endif

	return -1;
}