예제 #1
0
void SND_BACKEND_OPENAL_GetDeviceList( void )
{
	char deviceName[ 256 ];
	
	//my_strlcpy( deviceName, s_device->string, sizeof( deviceName ) );
	if( alcIsExtensionPresent( NULL,"ALC_ENUMERATION_EXT") == AL_TRUE ) 
	{	
		// try out enumeration extension
		deviceList = (char *)alcGetString( NULL, ALC_DEVICE_SPECIFIER );
		
        Log_Printf("OpenAL SND_GetDeviceList.\n",deviceList);
        
		for( numSoundDevices = 0 ; numSoundDevices < 12 ; ++numSoundDevices ) 
		{
			sound_devices[ numSoundDevices ] = NULL;
		}
		
		for( numSoundDevices = 0 ; numSoundDevices < 12 ; ++numSoundDevices )
		{
			sound_devices[ numSoundDevices ] = deviceList;
			if( strcmp( sound_devices[ numSoundDevices ], deviceName ) == 0 )
			{
				numDefaultSoundDevice = numSoundDevices;
			}
			deviceList += strlen( deviceList );
			if( deviceList[ 0 ] == 0 )
			{
				if( deviceList[ 1 ] == 0 )
				{
					break;
				} 
				else 
				{
					deviceList += 1;
				}
			}
			
			
		} // End for numSoundDevices = 0 ; numSoundDevices < 12 ; ++numSoundDevices
	}
	
}
예제 #2
0
ALCdevice* InitOpenALCaptureDevice(ALCuint sample_frequency, ALCenum al_format, ALCsizei max_buffer_size)
{
	ALCdevice* al_capture_device;
	
	if(!IsOpenALCaptureExtensionAvailable())
	{
		return NULL;
	}
	const char* default_device = alcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
	fprintf(stderr, "default device=%s", default_device);
	al_capture_device = alcCaptureOpenDevice(default_device, sample_frequency, al_format, max_buffer_size);
	if(NULL == al_capture_device)
	{
		printf("Failed to get capture device\n");
		return NULL;
	}
	
	//	printf("Finished initializing AL capture\n");
	return al_capture_device;
}
예제 #3
0
ALboolean ALFWInitOpenAL()
{
	ALDeviceList *pDeviceList = NULL;
	ALCcontext *pContext = NULL;
	ALCdevice *pDevice = NULL;
	ALint i;
	ALboolean bReturn = AL_FALSE;

	pDeviceList = new ALDeviceList();
	if ((pDeviceList) && (pDeviceList->GetNumDevices()))
	{
		ALFWprintf("\nSelect OpenAL Device:\n");
		for (i = 0; i < pDeviceList->GetNumDevices(); i++) 
			ALFWprintf("%d. %s%s\n", i + 1, pDeviceList->GetDeviceName(i), i == pDeviceList->GetDefaultDevice() ? "(DEFAULT)" : "");
	
		do {
			ALchar ch = _getch();
			i = atoi(&ch);
		} while ((i < 1) || (i > pDeviceList->GetNumDevices()));

		pDevice = alcOpenDevice(pDeviceList->GetDeviceName(i - 1));
		if (pDevice)
		{
			pContext = alcCreateContext(pDevice, NULL);
			if (pContext)
			{
				ALFWprintf("\nOpened %s Device\n", alcGetString(pDevice, ALC_DEVICE_SPECIFIER));
				alcMakeContextCurrent(pContext);
				bReturn = AL_TRUE;
			}
			else
			{
				alcCloseDevice(pDevice);
			}
		}

		delete pDeviceList;
	}

	return bReturn;
}
예제 #4
0
void csSndSysRendererOpenAL::Update()
{
  // Listener is created on open, but EventHandler is setup at init,
  // so, in some cases we can get here without the listener having been
  // created yet.
  if (!m_Listener)
    return;
  // Get exclusive access to the OpenAL context.
  ScopedRendererLock lock (*this);

  // Make sure the context, not really necessary as we requested a async
  // context, but documentation recommends it, in case async contexts are not
  // supported.
  //alcProcessContext (m_Context);

  // Update the listeners state.
  bool ExternalUpdates = m_Listener->Update();

  // Update the sources
  size_t iMax = m_Sources.GetSize();
  for (size_t i=0;i<iMax;i++)
  {
    m_Sources[i]->PerformUpdate( ExternalUpdates );
	if (m_Sources[i]->GetStream()->GetPauseState() == CS_SNDSYS_STREAM_PAUSED &&
        m_Sources[i]->GetStream()->GetAutoUnregisterRequested() == true) // sound has finished and is not looping
	{
	  RemoveStream(m_Sources[i]->GetStream());
	  RemoveSource(m_Sources[i]);
	  i--;    // changing the vector in mid-loop means we back up here
	  iMax--; // array is also one shorter now
	}
  }
  // Check for any errors
  ALCenum err = alcGetError (m_Device);
  if (err != ALC_NO_ERROR)
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "An OpenAL error occured: %s", alcGetString (m_Device, err));
    CS_ASSERT (err == ALC_NO_ERROR);
  }

}
예제 #5
0
파일: al_linux.c 프로젝트: turol/webquake2
/*
 =================
 AL_StartOpenAL
 =================
*/
static qboolean AL_StartOpenAL ()
{
	// Initialize our QAL dynamic bindings
	if (!QAL_Init())
		return false;

	// Get device list
	if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))
		alConfig.deviceList = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
	else
		alConfig.deviceList = "DirectSound3D\0DirectSound\0MMSYSTEM\0\0";

	// Initialize the device, context, etc...
	if (AL_InitDriver())
		return true;

	// Shutdown QAL
	QAL_Shutdown();

	return false;
}
예제 #6
0
bool
QALContext::reset()
{
    ALCenum error;
    if ((error = alcGetError(d->alcDevice)) != ALC_NO_ERROR) {
        qWarning() << Q_FUNC_INFO << "Error before trying to destroy the context:" << alcGetString(d->alcDevice, error);
    };

    alcDestroyContext(d->alcContext);
    if ((error = alcGetError(d->alcDevice)) != ALC_NO_ERROR) {
        qWarning() << Q_FUNC_INFO << "Failed to destroy the context:" << alcGetString(d->alcDevice, error);
        return false;
    };

    d->alcContext = 0;

    alcCloseDevice(d->alcDevice);
    d->alcDevice = 0;

    return true;
}
예제 #7
0
FSoundManager::FSoundManager( UI32 iMaxSoundHash, I32 iDelState  ) : iMaxHash( iMaxSoundHash ), iMaxSources( 0 ), lpSources( NULL ), lpSoundHash( NULL ), lpDevice( NULL ), lpContext( NULL ), iDelState( iDelState )
{
    const ALCchar * lpDevices = alcGetString( NULL, ALC_DEVICE_SPECIFIER );
    NSLog( @"Dev: %s", lpDevices );
    
    lpDevice = alcOpenDevice( lpDevices );
    if( lpDevice )
    {
        lpContext = alcCreateContext( lpDevice, NULL );
        alcMakeContextCurrent( lpContext );
    }
    
    const ALCchar * lpName = "alBufferDataStatic";
    alBufferDataStatic = (alBufferDataStaticProcPtr)alcGetProcAddress( lpDevice, lpName );
    
    lpSoundHash = (Node **)malloc( sizeof( Node * )*iMaxHash );
    for( I32 i = 0;i < iMaxHash;i++ )
        lpSoundHash[i] = NULL;
    
    CreateSources();
}
예제 #8
0
    void AudioEngine::enumerateDevices(std::vector<std::string>& enumerated)
    {
        if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))
        {
            size_t len = 0;
            const ALCchar* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
            const ALCchar *device = devices, *next = devices + 1;

            while (device && *device != '\0' && next && *next != '\0')
            {
                enumerated.push_back(device);

                len = strlen(device);
                device += (len + 1);
                next += (len + 2);
            }
        }

        if (enumerated.empty())
            enumerated.push_back(std::string());  // empty string is default device
    }
예제 #9
0
//--------------------------------------------------------------------------
// openal_error_string()
//
// Returns the human readable error string if there is an error or NULL if not
//
const char *openal_error_string(int get_alc)
{
	int i;

	if (get_alc) {
		ALCdevice *device = alcGetContextsDevice( alcGetCurrentContext() );

		i = alcGetError(device);

		if ( i != ALC_NO_ERROR )
			return (const char*) alcGetString(device, i);
	}
	else {
		i = alGetError();

		if ( i != AL_NO_ERROR )
			return (const char*)alGetString(i);
	}

	return NULL;
}
예제 #10
0
	bool SoundEngineOpenAL::init(std::string device)
	{
		// Create logger
		FileLogger *logger = new FileLogger;
		if (logger->init("RaumKlang.htm"))
		{
			setLogger(logger);
		}
		else
		{
			delete logger;
			setLogger(new ConsoleLogger());
		}
		// Get default device
		if (device == "")
		{
			device = alcGetString(0, ALC_DEFAULT_DEVICE_SPECIFIER);
		}
		// Setup OpenAL context
		ALCdevice *dev = alcOpenDevice(device.c_str());
		if (!dev)
			return false;
		ALCcontext *context = alcCreateContext(dev, 0);
		alcMakeContextCurrent(context);
		if (alcGetError(dev) != ALC_NO_ERROR)
			return false;
		// Startup message
		getLogger()->writeLine(ELL_Information, "RaumKlang 0.0.1 (OpenAL)");
		getLogger()->writeLine(ELL_Information,
			std::string("Device: ") + device);
		// Create listener
		listener = new ListenerOpenAL();
		// Add stream loaders
		initStreamLoaders();
		// Start update thread
		running = true;
		threadstopped = false;
		startUpdateThread();
		return true;
	}
예제 #11
0
static void
gst_openal_sink_get_property (GObject * object, guint prop_id, GValue * value,
    GParamSpec * pspec)
{
  GstOpenALSink *sink = GST_OPENAL_SINK (object);
  const ALCchar *device_name = sink->device_name;
  ALCdevice *device = sink->default_device;
  ALCcontext *context = sink->default_context;
  ALuint source = sink->default_source;

  switch (prop_id) {
    case PROP_DEVICE_NAME:
      device_name = "";
      if (device)
        device_name = alcGetString (device, ALC_DEVICE_SPECIFIER);
      /* fall-through */
    case PROP_DEVICE:
      g_value_set_string (value, device_name);
      break;
    case PROP_USER_DEVICE:
      if (!device)
        device = sink->user_device;
      g_value_set_pointer (value, device);
      break;
    case PROP_USER_CONTEXT:
      if (!context)
        context = sink->user_context;
      g_value_set_pointer (value, context);
      break;
    case PROP_USER_SOURCE:
      if (!source)
        source = sink->user_source;
      g_value_set_uint (value, source);
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}
예제 #12
0
static PP_Bool Instance_DidCreate(PP_Instance instance,
                                  uint32_t argc,
                                  const char* argn[],
                                  const char* argv[]) {
  g_MyState.instance = instance;
  g_MyState.ready = 0;
  g_MyStateIsValid = 1;

  /* This sets up OpenAL with PPAPI info. */
  alSetPpapiInfo(instance, g_get_browser_interface);

  const ALCchar* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
  setenv("ALSOFT_LOGLEVEL", "3", 0);
  printf("Audio devices available:\n");
  while (devices[0] != '\0') {
    printf("\t%s\n", devices);
    devices = devices + strlen(devices) + 1;
  }

  InitializeOpenAL();

  ogg_file_contents = (char*)malloc(BUFFER_READ_SIZE);
  ogg_file_alloced = BUFFER_READ_SIZE;

  PP_Resource request = g_MyState.request_interface->Create(instance);
  g_MyState.request_interface->SetProperty(
      request, PP_URLREQUESTPROPERTY_URL,
      g_MyState.var_interface->VarFromUtf8(OGG_FILE, strlen(OGG_FILE)));

  PP_Resource loader = g_MyState.loader_interface->Create(instance);
  struct PP_CompletionCallback cb =
      PP_MakeCompletionCallback(OpenCallback, (void*)loader);
  int32_t open_ret = g_MyState.loader_interface->Open(loader, request, cb);
  assert(open_ret == PP_OK_COMPLETIONPENDING);
  if (open_ret != PP_OK_COMPLETIONPENDING)
    return PP_FALSE;

  return PP_TRUE;
}
예제 #13
0
////////////////////////////////////////////////////////////
/// R�cup�re la liste des noms des devices disponibles
///
/// \param Devices : Tableau de cha�nes � remplir avec les noms des devices
///
////////////////////////////////////////////////////////////
void GetDevices(std::vector<std::string>& Devices)
{
    // Vidage de la liste
    Devices.clear();

    // R�cup�ration des devices disponibles
    const ALCchar* DeviceList = alcGetString(NULL, ALC_DEVICE_SPECIFIER);

    if (DeviceList)
    {
        // Extraction des devices contenus dans la cha�ne renvoy�e
        while (strlen(DeviceList) > 0)
        {
            Devices.push_back(DeviceList);
            DeviceList += strlen(DeviceList) + 1;
        }
    }
    else
    {
        std::cerr << "Impossible de r�cup�rer la liste des devices" << std::endl;
    }
}
예제 #14
0
	bool cAudioCapture::initOpenALDevice()
	{
		cAudioMutexBasicLock lock(Mutex);
		if(CaptureDevice)
			shutdownOpenALDevice();
		if(DeviceName.empty())
			CaptureDevice = alcCaptureOpenDevice(NULL, Frequency, convertAudioFormatEnum(Format), InternalBufferSize / SampleSize);
		else
			CaptureDevice = alcCaptureOpenDevice(toUTF8(DeviceName), Frequency, convertAudioFormatEnum(Format), InternalBufferSize / SampleSize);
		if(CaptureDevice)
		{
			DeviceName = fromUTF8(alcGetString(CaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
			Ready = true;
			checkError();
			getLogger()->logDebug("AudioCapture", "OpenAL Capture Device Opened.");

			return true;
		}
		checkError();

		return false;
	}
예제 #15
0
    SoundManager() {
        error = 0;
        read_buf_size = 44000;
        play_buf_size = 44000;
        play_buf[0] = 0;

        // Инициализируем OpenAL и создаем всякие штучки
        out_device = alcOpenDevice (0);
        context = alcCreateContext(out_device, 0);
        alcMakeContextCurrent(context);

        const char * szDefaultCaptureDevice = alcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
	/*
		while(*szDefaultCaptureDevice)
		{
 		ALFWprintf("%s\n", pDeviceList);
        	pDeviceList += strlen(pDeviceList) + 1;
		std::cout<<"Capture devices:  "<< szDefaultCaptureDevice <<std::endl ;
		szDefaultCaptureDevice += strlen(szDefaultCaptureDevice) + 1; //next device
		}
	*/
        in_device = alcCaptureOpenDevice (szDefaultCaptureDevice, 44100, AL_FORMAT_STEREO16, read_buf_size);
        if( (error=  alcGetError(in_device)) != AL_NO_ERROR)
            std::cout<<error<<" alcCaptureOpenDevice "<<__LINE__<<"\n";
        alGenSources(1, &al_source);
        alGenBuffers(BUF_COUNT, al_buffers);

        // Заполняем первую очередь
        for (int i = 0; i < BUF_COUNT; ++i) {
            alBufferData(al_buffers[i], AL_FORMAT_MONO16, play_buf, play_buf_size * sizeof(ALshort), play_buf_size);
        }
        // Здесь начинаем запись и воспроизведение
        alSourceQueueBuffers(al_source, BUF_COUNT, al_buffers);
        alSourcePlay(al_source);
        alcCaptureStart(in_device);
        if( (error=  alcGetError(in_device)) != AL_NO_ERROR)
            std::cout<<error<<" alcCaptureStart "<<__LINE__<<"\n";
    }
예제 #16
0
// virtual
bool LLAudioEngine_OpenAL::init(const S32 num_channels, void* userdata)
{
	mWindGen = NULL;
	LLAudioEngine::init(num_channels, userdata);

	if(!alutInit(NULL, NULL))
	{
		LL_WARNS("OpenAL") << "LLAudioEngine_OpenAL::init() ALUT initialization failed: " << alutGetErrorString (alutGetError ()) << LL_ENDL;
		return false;
	}

	LL_INFOS("OpenAL") << "LLAudioEngine_OpenAL::init() OpenAL successfully initialized" << LL_ENDL;

	LL_INFOS("OpenAL") << "OpenAL version: "
		<< ll_safe_string(alGetString(AL_VERSION)) << LL_ENDL;
	LL_INFOS("OpenAL") << "OpenAL vendor: "
		<< ll_safe_string(alGetString(AL_VENDOR)) << LL_ENDL;
	LL_INFOS("OpenAL") << "OpenAL renderer: "
		<< ll_safe_string(alGetString(AL_RENDERER)) << LL_ENDL;

	ALint major = alutGetMajorVersion ();
	ALint minor = alutGetMinorVersion ();
	LL_INFOS("OpenAL") << "ALUT version: " << major << "." << minor << LL_ENDL;

	ALCdevice *device = alcGetContextsDevice(alcGetCurrentContext());

	alcGetIntegerv(device, ALC_MAJOR_VERSION, 1, &major);
	alcGetIntegerv(device, ALC_MAJOR_VERSION, 1, &minor);
	LL_INFOS("OpenAL") << "ALC version: " << major << "." << minor << LL_ENDL;

	LL_INFOS("OpenAL") << "ALC default device: "
		<< ll_safe_string(alcGetString(device,
					       ALC_DEFAULT_DEVICE_SPECIFIER))
		<< LL_ENDL;

	return true;
}
예제 #17
0
		Mixer::Mixer ()
		{
			const ALCchar * device_name = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);

			AudioError::reset();
			_audio_device = _default_audio_device();
			_audio_context = alcCreateContext(_audio_device, NULL);
			AudioError::check("Initializing Audio Context");

			bool result = alcMakeContextCurrent(_audio_context);

			LogBuffer buffer;
			buffer << "OpenAL Context Initialized..." << std::endl;
			buffer << "OpenAL Vendor: " << alGetString(AL_VENDOR) << " " << alGetString(AL_VERSION) << std::endl;
			buffer << "OpenAL Device: '" << device_name << "'" << std::endl;
			logger()->log(LOG_INFO, buffer);

			//al_distance_model(AL_LINEAR_DISTANCE);
			set_listener_position(0);
			set_listener_velocity(0);
			set_listener_orientation(Vec3(0.0, 0.0, -1.0), Vec3(0.0, 1.0, 0.0));

			DREAM_ASSERT(result && "Failed to initialize audio hardware!?");
		}
예제 #18
0
av_session_t *av_init_session()
{
    av_session_t *_retu = malloc(sizeof(av_session_t));

    /* Initialize our mutex */
    pthread_mutex_init ( &_retu->_mutex, NULL );

    _retu->_messenger = tox_new(1);

    if ( !_retu->_messenger ) {
        fprintf ( stderr, "tox_new() failed!\n" );
        return NULL;
    }

    _retu->_friends = NULL;


    const ALchar *_device_list = alcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
    int i = 0;
    const ALchar *device_names[20];

    if ( _device_list ) {
        INFO("\nAvailable Capture Devices are:");

        while (*_device_list ) {
            device_names[i] = _device_list;
            INFO("%d) %s", i, device_names[i]);
            _device_list += strlen( _device_list ) + 1;
            ++i;
        }
    }

    INFO("Enter capture device number");

    char dev[2];
    char *left;
    char *warned_ = fgets(dev, 2, stdin);
    (void)warned_;
    long selection = strtol(dev, &left, 10);

    if ( *left ) {
        printf("'%s' is not a number!", dev);
        fflush(stdout);
        exit(EXIT_FAILURE);
    } else {
        INFO("Selected: %d ( %s )", selection, device_names[selection]);
    }

    _retu->audio_capture_device =
        (struct ALCdevice *)alcCaptureOpenDevice(
            device_names[selection], AUDIO_SAMPLE_RATE, AL_FORMAT_MONO16, AUDIO_FRAME_SIZE * 4);


    if (alcGetError((ALCdevice *)_retu->audio_capture_device) != AL_NO_ERROR) {
        printf("Could not start capture device! %d\n", alcGetError((ALCdevice *)_retu->audio_capture_device));
        return 0;
    }

    uint16_t height = 0, width = 0;
#ifdef TOX_FFMPEG
    avdevice_register_all();
    avcodec_register_all();
    av_register_all();

    _retu->video_input_format = av_find_input_format(VIDEO_DRIVER);

    if (avformat_open_input(&_retu->video_format_ctx, DEFAULT_WEBCAM, _retu->video_input_format, NULL) != 0) {
        fprintf(stderr, "Opening video_input_format failed!\n");
        //return -1;
        goto failed_init_ffmpeg;
    }

    avformat_find_stream_info(_retu->video_format_ctx, NULL);
    av_dump_format(_retu->video_format_ctx, 0, DEFAULT_WEBCAM, 0);

    for (i = 0; i < _retu->video_format_ctx->nb_streams; ++i) {
        if (_retu->video_format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            _retu->video_stream = i;
            break;
        }
    }

    _retu->webcam_decoder_ctx = _retu->video_format_ctx->streams[_retu->video_stream]->codec;
    _retu->webcam_decoder = avcodec_find_decoder(_retu->webcam_decoder_ctx->codec_id);

    if (_retu->webcam_decoder == NULL) {
        fprintf(stderr, "Unsupported codec!\n");
        //return -1;
        goto failed_init_ffmpeg;
    }

    if (_retu->webcam_decoder_ctx == NULL) {
        fprintf(stderr, "Init webcam_decoder_ctx failed!\n");
        //return -1;
        goto failed_init_ffmpeg;
    }

    if (avcodec_open2(_retu->webcam_decoder_ctx, _retu->webcam_decoder, NULL) < 0) {
        fprintf(stderr, "Opening webcam decoder failed!\n");
        //return -1;
        goto failed_init_ffmpeg;
    }

    width = _retu->webcam_decoder_ctx->width;
    height = _retu->webcam_decoder_ctx->height;

failed_init_ffmpeg: ;
#endif
    uint8_t _byte_address[TOX_FRIEND_ADDRESS_SIZE];
    tox_get_address(_retu->_messenger, _byte_address );
    fraddr_to_str( _byte_address, _retu->_my_public_id );


    _retu->av = toxav_new(_retu->_messenger, width, height);

    /* ------------------ */

    toxav_register_callstate_callback(callback_call_started, av_OnStart, _retu->av);
    toxav_register_callstate_callback(callback_call_canceled, av_OnCancel, _retu->av);
    toxav_register_callstate_callback(callback_call_rejected, av_OnReject, _retu->av);
    toxav_register_callstate_callback(callback_call_ended, av_OnEnd, _retu->av);
    toxav_register_callstate_callback(callback_recv_invite, av_OnInvite, _retu->av);

    toxav_register_callstate_callback(callback_recv_ringing, av_OnRinging, _retu->av);
    toxav_register_callstate_callback(callback_recv_starting, av_OnStarting, _retu->av);
    toxav_register_callstate_callback(callback_recv_ending, av_OnEnding, _retu->av);

    toxav_register_callstate_callback(callback_recv_error, av_OnError, _retu->av);
    toxav_register_callstate_callback(callback_requ_timeout, av_OnRequestTimeout, _retu->av);

    /* ------------------ */

    return _retu;
}
예제 #19
0
파일: Sound.cpp 프로젝트: 304471720/spring
__FORCE_ALIGN_STACK__
void CSound::StartThread(int maxSounds)
{
	{
		boost::recursive_mutex::scoped_lock lck(soundMutex);

		// alc... will create its own thread it will copy the name from the current thread.
		// Later we finally rename `our` audio thread.
		Threading::SetThreadName("openal");

		// NULL -> default device
		const ALchar* deviceName = NULL;
		std::string configDeviceName = "";

		// we do not want to set a default for snd_device,
		// so we do it like this ...
		if (configHandler->IsSet("snd_device"))
		{
			configDeviceName = configHandler->GetString("snd_device");
			deviceName = configDeviceName.c_str();
		}

		ALCdevice* device = alcOpenDevice(deviceName);

		if ((device == NULL) && (deviceName != NULL))
		{
			LOG_L(L_WARNING,
					"Could not open the sound device \"%s\", trying the default device ...",
					deviceName);
			configDeviceName = "";
			deviceName = NULL;
			device = alcOpenDevice(deviceName);
		}

		if (device == NULL)
		{
			LOG_L(L_ERROR, "Could not open a sound device, disabling sounds");
			CheckError("CSound::InitAL");
			return;
		}
		else
		{
			ALCcontext *context = alcCreateContext(device, NULL);
			if (context != NULL)
			{
				alcMakeContextCurrent(context);
				CheckError("CSound::CreateContext");
			}
			else
			{
				alcCloseDevice(device);
				LOG_L(L_ERROR, "Could not create OpenAL audio context");
				return;
			}
		}
		maxSounds = GetMaxMonoSources(device, maxSounds);

		LOG("OpenAL info:");
		if(alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))
		{
			LOG("  Available Devices:");
			const char* deviceSpecifier = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
			while (*deviceSpecifier != '\0') {
				LOG("              %s", deviceSpecifier);
				while (*deviceSpecifier++ != '\0')
					;
			}
			LOG("  Device:     %s", (const char*)alcGetString(device, ALC_DEVICE_SPECIFIER));
		}
		LOG("  Vendor:         %s", (const char*)alGetString(AL_VENDOR));
		LOG("  Version:        %s", (const char*)alGetString(AL_VERSION));
		LOG("  Renderer:       %s", (const char*)alGetString(AL_RENDERER));
		LOG("  AL Extensions:  %s", (const char*)alGetString(AL_EXTENSIONS));
		LOG("  ALC Extensions: %s", (const char*)alcGetString(device, ALC_EXTENSIONS));

		// Init EFX
		efx = new CEFX(device);

		// Generate sound sources
		for (int i = 0; i < maxSounds; i++)
		{
			CSoundSource* thenewone = new CSoundSource();
			if (thenewone->IsValid()) {
				sources.push_back(thenewone);
			} else {
				maxSounds = std::max(i-1, 0);
				LOG_L(L_WARNING,
						"Your hardware/driver can not handle more than %i soundsources",
						maxSounds);
				delete thenewone;
				break;
			}
		}
		LOG("  Max Sounds: %i", maxSounds);

		// Set distance model (sound attenuation)
		alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
		alDopplerFactor(0.2f);

		alListenerf(AL_GAIN, masterVolume);
	}

	Threading::SetThreadName("audio");
	Watchdog::RegisterThread(WDT_AUDIO);

	while (!soundThreadQuit) {
		boost::this_thread::sleep(boost::posix_time::millisec(50)); //! 20Hz
		Watchdog::ClearTimer(WDT_AUDIO);
		Update();
	}

	Watchdog::DeregisterThread(WDT_AUDIO);

	sources.clear(); // delete all sources
	delete efx; // must happen after sources and before context
	efx = NULL;
	ALCcontext* curcontext = alcGetCurrentContext();
	ALCdevice* curdevice = alcGetContextsDevice(curcontext);
	alcMakeContextCurrent(NULL);
	alcDestroyContext(curcontext);
	alcCloseDevice(curdevice);
}
예제 #20
0
//*
// =======================================================================================================================
// =======================================================================================================================
//
bool sound_InitLibrary(void)
{
    int err;
    const ALfloat listenerVel[3] = { 0.0, 0.0, 0.0 };
    const ALfloat listenerOri[6] = { 0.0, 0.0, 1.0, 0.0, 1.0, 0.0 };
    char buf[512];
    const ALCchar *deviceName;

#if 0
    // This code is disabled because enumerating devices apparently crashes PulseAudio on Fedora12

    /* Get the available devices and print them.
     * Devices are separated by NUL chars ('\0') and the list of devices is
     * terminated by two NUL chars.
     */
    deviceName = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
    while (deviceName != NULL && *deviceName != '\0')
    {
        debug(LOG_SOUND, "available OpenAL device(s) are: %s", deviceName);
        deviceName += strlen(deviceName) + 1;
    }
#endif

#ifdef WZ_OS_WIN
    /* HACK: Select the "software" OpenAL device on Windows because it
     *       provides 256 sound sources (unlike most Creative's default
     *       which provides only 16), causing our lack of source-management
     *       to be significantly less noticeable.
     */
    device = alcOpenDevice("Generic Software");

    // If the software device isn't available, fall back to default
    if (!device)
#endif
    {
        // Open default device
        device = alcOpenDevice(NULL);
    }

    if (!device)
    {
        debug(LOG_ERROR, "Couldn't open audio device.");
        return false;
    }

    // Print current device name and add it to dump info
    deviceName = alcGetString(device, ALC_DEVICE_SPECIFIER);
    debug(LOG_SOUND, "Current audio device: %s", deviceName);
    ssprintf(buf, "OpenAL Device Name: %s", deviceName);
    addDumpInfo(buf);

    context = alcCreateContext(device, NULL);		//NULL was contextAttributes
    if (!context)
    {
        debug(LOG_ERROR, "Couldn't open audio context.");
        return false;
    }

    alcMakeContextCurrent(context);

    err = sound_GetContextError(device);
    if (err != ALC_NO_ERROR)
    {
        debug(LOG_ERROR, "Couldn't initialize audio context: %s", alcGetString(device, err));
        return false;
    }

    // Dump Open AL device info (depends on context)
    // to the crash handler for the dump file and debug log
    ssprintf(buf, "OpenAL Vendor: %s", alGetString(AL_VENDOR));
    addDumpInfo(buf);
    debug(LOG_SOUND, "%s", buf);

    ssprintf(buf, "OpenAL Version: %s", alGetString(AL_VERSION));
    addDumpInfo(buf);
    debug(LOG_SOUND, "%s", buf);

    ssprintf(buf, "OpenAL Renderer: %s", alGetString(AL_RENDERER));
    addDumpInfo(buf);
    debug(LOG_SOUND, "%s", buf);

    ssprintf(buf, "OpenAL Extensions: %s", alGetString(AL_EXTENSIONS));
    addDumpInfo(buf);
    debug(LOG_SOUND, "%s", buf);

    openal_initialized = true;

    // Clear Error Codes
    alGetError();
    alcGetError(device);

    alListener3f(AL_POSITION, 0.f, 0.f, 0.f);
    alListenerfv(AL_VELOCITY, listenerVel);
    alListenerfv(AL_ORIENTATION, listenerOri);
    alDistanceModel(AL_NONE);
    sound_GetError();

    return true;
}
예제 #21
0
/* 
 * Init call
 */
ALDeviceList::ALDeviceList()
{
	ALDEVICEINFO	ALDeviceInfo;
	char *devices;
	s32 index;
	const char *defaultDeviceName = NULL;
	const char *actualDeviceName = NULL;

	// DeviceInfo vector stores, for each enumerated device, it's device name, selection status, spec version #, and extension support
	vDeviceInfo.empty();
	vDeviceInfo.reserve(10);

	defaultDeviceIndex = 0;

	// grab function pointers for 1.0-API functions, and if successful proceed to enumerate all devices
	//if (LoadOAL10Library(NULL, &ALFunction) == TRUE) {
		if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))
		{
			devices = (char *)alcGetString(NULL, ALC_DEVICE_SPECIFIER);
			defaultDeviceName = (char *)alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
			index = 0;
			// go through device list (each device terminated with a single NULL, list terminated with double NULL)
			while (devices != NULL && strlen(devices) > 0) 
			{
				if (strcmp(defaultDeviceName, devices) == 0) 
				{
					defaultDeviceIndex = index;
				}
				ALCdevice *device = alcOpenDevice(devices);
				if (device) 
				{
					ALCcontext *context = alcCreateContext(device, NULL);
					if (context) 
					{
						alcMakeContextCurrent(context);
						// if new actual device name isn't already in the list, then add it...
						actualDeviceName = alcGetString(device, ALC_DEVICE_SPECIFIER);
						bool bNewName = true;
						for (s32 i = 0; i < GetNumDevices(); i++) 
						{
							if (strcmp(GetDeviceName(i), actualDeviceName) == 0) 
							{
								bNewName = false;
							}
						}
						if ((bNewName) && (actualDeviceName != NULL) && (strlen(actualDeviceName) > 0)) 
						{
							ALDeviceInfo.bSelected = true;
							ALDeviceInfo.strDeviceName = actualDeviceName;
							alcGetIntegerv(device, ALC_MAJOR_VERSION, sizeof(s32), &ALDeviceInfo.iMajorVersion);
							alcGetIntegerv(device, ALC_MINOR_VERSION, sizeof(s32), &ALDeviceInfo.iMinorVersion);

							ALDeviceInfo.pvstrExtensions = new vector<string>;

							// Check for ALC Extensions
							if (alcIsExtensionPresent(device, "ALC_EXT_CAPTURE") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("ALC_EXT_CAPTURE");
							if (alcIsExtensionPresent(device, "ALC_EXT_EFX") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("ALC_EXT_EFX");

							// Check for AL Extensions
							if (alIsExtensionPresent("AL_EXT_OFFSET") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("AL_EXT_OFFSET");

							if (alIsExtensionPresent("AL_EXT_LINEAR_DISTANCE") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("AL_EXT_LINEAR_DISTANCE");
							if (alIsExtensionPresent("AL_EXT_EXPONENT_DISTANCE") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("AL_EXT_EXPONENT_DISTANCE");
							
							if (alIsExtensionPresent("EAX2.0") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("EAX2.0");
							if (alIsExtensionPresent("EAX3.0") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("EAX3.0");
							if (alIsExtensionPresent("EAX4.0") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("EAX4.0");
							if (alIsExtensionPresent("EAX5.0") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("EAX5.0");

							if (alIsExtensionPresent("EAX-RAM") == AL_TRUE)
								ALDeviceInfo.pvstrExtensions->push_back("EAX-RAM");

							// Get Source Count
							ALDeviceInfo.uiSourceCount = GetMaxNumSources();

							vDeviceInfo.push_back(ALDeviceInfo);
						}
						alcMakeContextCurrent(NULL);
						alcDestroyContext(context);
					}
					alcCloseDevice(device);
				}
				devices += strlen(devices) + 1;
				index += 1;
			}
		}
	//}

	ResetFilters();
}
예제 #22
0
void fs_emu_audio_openal_init(void)
{
    fs_log("fs_emu_audio_openal_init\n");
    register_functions();

    // select the "preferred device"
    g_device = alcOpenDevice(NULL);
    if (g_device) {
        fs_log("[OPENAL] Opened device: %s\n",
               alcGetString(g_device, ALC_DEVICE_SPECIFIER));
    } else {
        fs_log("[OPENAL] NULL from alcOpenDevice\n");
        ALenum error_code = alGetError();
        fs_log("[OPENAL] Error code %d\n", error_code);
        if (alGetString(error_code)) {
            fs_log("[OPENAL] %s\n", alGetString(error_code));
        }
        fs_emu_warning("OPENAL: Could not open audio device");
    }
    if (!g_device) {
        return;
    }
    log_openal_info();
    log_openal_devices();

    int frequencies[] = { 48000, 44100, 0 };
    if (fs_config_get_int("audio_frequency") != FS_CONFIG_NONE) {
        frequencies[0] = fs_config_get_int("audio_frequency");
    }

    for (int i = 0; frequencies[i]; i++) {
        int frequency = frequencies[i];
        fs_log("OPENAL: trying frequency %d\n", frequency);
        ALCint attributes[] = {
            ALC_MONO_SOURCES, 0,
            ALC_STEREO_SOURCES, 2,
            ALC_FREQUENCY, frequency,
            0
        };

        g_context = alcCreateContext(g_device, attributes);
        if (g_context) {
            g_audio_out_frequency = frequency;
            break;
        }
    }

    if (g_context) {
        fs_log("OPENAL: created context\n");
        alcMakeContextCurrent(g_context);
        check_al_error("alcMakeContextCurrent");
        fs_log("OPENAL: made context current\n");
    } else {
        fs_emu_warning("OpenAL: no context created\n");
        //check_al_error("alcCreateContext");
    }

    int stereo_sources;
    alcGetIntegerv(g_device, ALC_STEREO_SOURCES, 1, &stereo_sources);
    fs_log("openal: number of stereo sources is %d\n", stereo_sources);

    // FIXME: configure elsewhere
    int abt = fs_config_get_int_clamped("audio_buffer_target_size",
                                        1, 100);
    if (abt == FS_CONFIG_NONE) {
        if (fs_config_get_int("audio_buffer_target_bytes") != FS_CONFIG_NONE) {
            fs_emu_warning("Use audio_buffer_target_size instead\n");
        }
        abt = 40;
#if 0
        if (abt == FS_CONFIG_NONE) {
            abt = 40;
        } else {
            abt = (int) (abt / 1000.0 * (options->frequency * 2 * 2));
        }
#endif
    }
    fs_log("AUDIO: Buffer target size (ms) = %d\n", abt);
    //abt = (int) (abt / 1000.0 * (options->frequency * 2 * 2));
    // fs_log("AUDIO: Buffer target size (bytes) = %d\n", abt);
    /* Specifying fill target in microseconds */
    g_default_fill_target = abt * 1000;
}
예제 #23
0
파일: openal.c 프로젝트: AmesianX/RosWine
const ALCchar* CDECL wine_alcGetString(ALCdevice *device, ALCenum param)
{
    return alcGetString(device, param);
}
예제 #24
0
void MFSound_InitModulePlatformSpecific(int *pSoundDataSize, int *pVoiceDataSize)
{
	MFCALLSTACK;

	gDevices.Init(sizeof(AudioDevice), 8, 8);

	ALCint minor, major;
	alcGetIntegerv(NULL, ALC_MAJOR_VERSION, 1, &major);
	alcGetIntegerv(NULL, ALC_MINOR_VERSION, 1, &minor);
	gAPIVersion = major*100 + minor;

	bool bCanEnumerate, bHasCapture;
	if(gAPIVersion >= 101)
	{
		bCanEnumerate = true;
		bHasCapture = true;
	}
	else
	{
		bCanEnumerate = alcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT") == AL_TRUE;
		bHasCapture = alcIsExtensionPresent(NULL, "ALC_EXT_CAPTURE") == AL_TRUE;
	}

	if(bCanEnumerate)
	{
		const char *pDevices = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
		const char *pDefault = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
		while(pDevices && *pDevices)
		{
			bool bIsDefault = !MFString_Compare(pDevices, pDefault);
			MFDebug_Log(2, MFStr("OpenAL: found output device '%s'%s", pDevices, bIsDefault ? " (default)" : ""));

			MFDevice *pDevice = MFDevice_AllocDevice(MFDT_AudioRender, &DestroyDevice);
			pDevice->pInternal = gDevices.AllocAndZero();
			pDevice->state = MFDevState_Ready;

			AudioDevice &device = *(AudioDevice*)pDevice->pInternal;
			MFString_CopyN(pDevice->strings[MFDS_ID], pDevices, sizeof(pDevice->strings[MFDS_ID])-1);
			pDevice->strings[MFDS_ID][sizeof(pDevice->strings[MFDS_ID])-1] = 0;
			device.pDevice = NULL;

			if(bIsDefault)
					MFDevice_SetDefaultDevice(MFDT_AudioRender, MFDDT_All, pDevice);

			pDevices += MFString_Length(pDevices) + 1;
		}

		if(!MFDevice_GetDefaultDevice(MFDT_AudioRender, MFDDT_Default))
		{
			MFDebug_Warn(2, "OpenAL: No default output device?");

			// HACK: set it to the first one...
			MFDevice *pDevice = MFDevice_GetDeviceByIndex(MFDT_AudioRender, 0);
			MFDevice_SetDefaultDevice(MFDT_AudioRender, MFDDT_All, pDevice);
		}

		if(bHasCapture)
		{
			pDevices = alcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
			pDefault = alcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
			while(pDevices && *pDevices)
			{
				bool bIsDefault = !MFString_Compare(pDevices, pDefault);
				MFDebug_Log(2, MFStr("OpenAL: found capture device '%s'%s", pDevices, bIsDefault ? " (default)" : ""));

				MFDevice *pDevice = MFDevice_AllocDevice(MFDT_AudioCapture, &DestroyDevice);
				pDevice->pInternal = gDevices.AllocAndZero();
				pDevice->state = MFDevState_Ready;

				AudioDevice &device = *(AudioDevice*)pDevice->pInternal;
				MFString_CopyN(pDevice->strings[MFDS_ID], pDevices, sizeof(pDevice->strings[MFDS_ID])-1);
				pDevice->strings[MFDS_ID][sizeof(pDevice->strings[MFDS_ID])-1] = 0;
				device.pDevice = NULL;

				if(bIsDefault)
					MFDevice_SetDefaultDevice(MFDT_AudioCapture, MFDDT_All, pDevice);

				pDevices += MFString_Length(pDevices) + 1;
			}

			if(!MFDevice_GetDefaultDevice(MFDT_AudioCapture, MFDDT_Default))
				MFDebug_Warn(2, "OpenAL: No default capture device?");
		}
	}

	// create a context
	Context *pContext = CreateContext(MFDevice_GetDefaultDevice(MFDT_AudioRender, MFDDT_Default));
	MakeCurrent(pContext);

	// we need to return the size of the internal structures so the platform independant
	// code can make the correct allocations..
	*pSoundDataSize = sizeof(MFSoundDataInternal);
	*pVoiceDataSize = sizeof(MFVoiceDataInternal);
}
예제 #25
0
value lime_alc_get_string (value device, value param) {

    ALCdevice* alcDevice = (ALCdevice*)(intptr_t)val_float (device);
    return alloc_string (alcGetString (alcDevice, val_int (param)));

}
예제 #26
0
파일: openal.c 프로젝트: DAOWAce/pcsxr
void SetupSound()
{
    unsigned char buf[BUFFER_SIZE];
    int i;
    
    // Get handle to device.
    pDevice = alcOpenDevice(NULL);
    if(checkALCError())
    {
        fprintf(stderr, "[SPU] alcOpenDevice failed.\n");
        return;
    }
    
    // ALC info.
    const ALCubyte* UNUSED_VARIABLE deviceName = (ALCubyte*)alcGetString(pDevice, ALC_DEVICE_SPECIFIER);
    //printf("[SPU] ALC_DEVICE_SPECIFIER = %s.\n", deviceName);
    
    const ALCubyte* UNUSED_VARIABLE extensionList = (ALCubyte*)alcGetString(pDevice, ALC_EXTENSIONS);
    //printf("[SPU] ALC_EXTENSIONS = %s.\n", extensionList);
    
    // Create audio context.
    pContext = alcCreateContext(pDevice, NULL);
    if(checkALCError())
    {
        fprintf(stderr, "[SPU] alcCreateContext failed.\n");
        return;
    }
    
    // Set active context.
    alcMakeContextCurrent( pContext );
    if( checkALCError() )
    {
        fprintf(stderr, "[SPU] alcMakeContextCurrent failed.\n");
        return;
    }
    
    // AL info.
    const ALubyte* UNUSED_VARIABLE version = (ALubyte*)alGetString(AL_VERSION);
    //printf("[SPU] AL_VERSION = %s.\n", version);
    
    const ALubyte* UNUSED_VARIABLE renderer = (ALubyte*)alGetString(AL_RENDERER);
    //printf("[SPU] AL_RENDERER = %s.\n", renderer);

    const ALubyte* UNUSED_VARIABLE vendor = (ALubyte*)alGetString(AL_VENDOR);
    //printf("[SPU] AL_VENDOR = %s.\n", vendor);
    
    // Create buffers.
    alGenBuffers(BUFFER_QUANTITY, buffers);
    checkALError();
    
    // Load sound data into a buffer.
    memset(buf, 0x00, BUFFER_SIZE);
    for(i = 0; i < BUFFER_QUANTITY; ++i)
    {
        alBufferData(buffers[i], format, buf, BUFFER_SIZE, sampleRate);
    }
    checkALError();
    
    // Create source.
    alGenSources(1, &source);
    checkALError();
    
    // Bind buffer with a source.
    alSourcef (source, AL_PITCH,           1.0f     );
    alSourcef (source, AL_GAIN,            1.0f     );
    alSourcefv(source, AL_POSITION,        SourcePos);
    alSourcefv(source, AL_VELOCITY,        SourceVel);
    alSourcefv(source, AL_DIRECTION,       SourceDir);
    alSourcei (source, AL_SOURCE_RELATIVE, AL_TRUE  );
    alSourcei (source, AL_LOOPING,         AL_FALSE );
    
    // Listener properties.
    alListenerfv(AL_POSITION,    ListenerPos);
    alListenerfv(AL_VELOCITY,    ListenerVel);
    alListenerfv(AL_ORIENTATION, ListenerOri);
    
    // Add buffers to queue.
    alSourceQueueBuffers(source, BUFFER_QUANTITY, buffers);
    checkALError();
    
    // Enable playing.
    alSourcePlay(source);
    checkALError();
}
예제 #27
0
bool AudioEngine::SingletonInitialize()
{
    if(!AUDIO_ENABLE)
        return true;

    const ALCchar *best_device = 0; // Will store the name of the 'best' device for audio playback
    ALCint highest_version = 0; // The highest version number found
    CheckALError(); // Clears errors
    CheckALCError(); // Clears errors

    // Find the highest-version device available, if the extension for device enumeration is present
    if(alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE) {
        const ALCchar *device_list = 0;
        device_list = alcGetString(0, ALC_DEVICE_SPECIFIER); // Get list of all devices (terminated with two '0')
        if(CheckALCError() == true) {
            IF_PRINT_WARNING(AUDIO_DEBUG) << "failed to retrieve the list of available audio devices: " << CreateALCErrorString() << std::endl;
        }


        while(*device_list != 0) {  // Check all the detected devices
            ALCint major_v = 0, minor_v = 0;

            // Open a temporary device for reading in its version number
            ALCdevice *temp_device = alcOpenDevice(device_list);
            if(CheckALCError() || temp_device == NULL) {  // If we couldn't open the device, just move on to the next
                IF_PRINT_WARNING(AUDIO_DEBUG) << "couldn't open device for version checking: " << device_list << std::endl;
                device_list += strlen(device_list) + 1;
                continue;
            }

            // Create a temporary context for the device
            ALCcontext *temp_context = alcCreateContext(temp_device, 0);
            if(CheckALCError() || temp_context == NULL) {  // If we couldn't create the context, move on to the next device
                IF_PRINT_WARNING(AUDIO_DEBUG) << "couldn't create a temporary context for device: " << device_list << std::endl;
                alcCloseDevice(temp_device);
                device_list += strlen(device_list) + 1;
                continue;
            }

            // Retrieve the version number for the device
            alcMakeContextCurrent(temp_context);

            alcGetIntegerv(temp_device, ALC_MAJOR_VERSION, sizeof(ALCint), &major_v);
            alcGetIntegerv(temp_device, ALC_MINOR_VERSION, sizeof(ALCint), &minor_v);
            alcMakeContextCurrent(0); // Disable the temporary context
            alcDestroyContext(temp_context); // Destroy the temporary context
            alcCloseDevice(temp_device); // Close the temporary device

            // Check if a higher version device was found
            if(highest_version < (major_v * 10 + minor_v)) {
                highest_version = (major_v * 10 + minor_v);
                best_device = device_list;
            }
            device_list += strlen(device_list) + 1; // Go to the next device name in the list
        } // while (*device_name != 0)
    } // if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE)

    // Open the 'best' device we found above. If no devices were previously found,
    // it will try opening the default device (= 0)
    _device = alcOpenDevice(best_device);
    if(CheckALCError() || _device == NULL) {
        PRINT_ERROR << "failed to open an OpenAL audio device: " << CreateALCErrorString() << std::endl;
        return false;
    }

    // Create an OpenAL context
    _context = alcCreateContext(_device, NULL);
    if(CheckALCError() || _context == NULL) {
        PRINT_ERROR << "failed to create an OpenAL context: " << CreateALCErrorString() << std::endl;
        alcCloseDevice(_device);
        return false;
    }

    alcMakeContextCurrent(_context);
    CheckALError(); // Clear errors
    CheckALCError(); // Clear errors

    // Create as many sources as possible (we fix an upper bound of MAX_DEFAULT_AUDIO_SOURCES)
    ALuint source;
    for(uint16 i = 0; i < _max_sources; i++) {
        alGenSources(1, &source);
        if(CheckALError() == true) {
            _max_sources = i;
            _max_cache_size = i / 4;
            break;
        }
        _audio_sources.push_back(new private_audio::AudioSource(source));
    }

    if(_max_sources == 0) {
        PRINT_ERROR << "failed to create at least one OpenAL audio source" << std::endl;
        return false;
    }

    return true;
} // bool AudioEngine::SingletonInitialize()
예제 #28
0
bool alutInit(ALint *argc,ALbyte **argv) 
{
	ALenum errori=alGetError();
	alGetError();
	alGetError();
	alGetError();
	alGetError();

	ALCcontext *Context;
	ALCdevice *Device;
	
	errori=alGetError();
	if(errori != AL_NO_ERROR){
		return false;
	}

	errori=alGetError();
	if(errori != AL_NO_ERROR){
		return false;

	}


	Device=alcOpenDevice(NULL);

	Context=alcCreateContext(Device,NULL);
	
	//Set active context
	alcMakeContextCurrent(Context);

	char* t=(char*)alcGetString(Device,ALC_DEVICE_SPECIFIER);
	

	#ifdef _WIN32
	if(t==NULL){
		logs().audio.write("HARDWARESTRING:''");
		return false;
	}

	String lol;

	while(t[1]!=NULL){
		lol+=t;
		t+=lol.size()+1;
	}

	logs().audio.write("HARDWARESTRING:'"+lol+"'");

	if(lol=="" || lol==" "){
		//no AL hardware
		return false;
	}
	
	#else
		//os x doesn't give us a hardware string? so ignore
	#endif

	int majorVersion=0;
	int minorVersion=0;

	alcGetIntegerv(Device,ALC_MAJOR_VERSION,sizeof(majorVersion),&majorVersion);
	alcGetIntegerv(Device,ALC_MINOR_VERSION,sizeof(minorVersion),&minorVersion);

	String version=String(majorVersion)+"."+String(minorVersion);

	logs().audio.write("HARDWAREVERSION:'"+version+"'");

	if(version!="1.1"){
		logs().audio.write("Error, openal not version 1.1");

		//try to fallback on the software implementation

		alcDestroyContext(Context);
		alcCloseDevice(Device);

		logs().audio.write("searching for software dll");

		ALCdevice *DeviceSoftware;

		DeviceSoftware=alcOpenDevice("Generic Software");

		if(DeviceSoftware==NULL){
			logs().audio.write("device not found!");
			return false;
		}

		ALCcontext *ContextSoftware=alcCreateContext(DeviceSoftware,NULL);

		if(ContextSoftware==NULL){
			logs().audio.write("bad context!");
			return false;
		}

		//Set active context
		alcMakeContextCurrent(ContextSoftware);

		int majorVersionS=0;
		int minorVersionS=0;

		alcGetIntegerv(DeviceSoftware,ALC_MAJOR_VERSION,sizeof(majorVersionS),&majorVersionS);
		alcGetIntegerv(DeviceSoftware,ALC_MINOR_VERSION,sizeof(minorVersionS),&minorVersionS);

		String versionS=String(majorVersionS)+"."+String(minorVersionS);

		logs().audio.write("HARDWAREVERSION_SOFTWARE:'"+versionS+"'");

		
	

		#ifdef _WIN32
		char* t=(char*)alcGetString(DeviceSoftware,ALC_DEVICE_SPECIFIER);
		
		if(t==NULL){
			logs().audio.write("HARDWARESTRING_SOFTWARE:''");
			return false;
		}

		String lol;

		while(t[1]!=NULL){
			lol+=t;
			t+=lol.size()+1;
		}

		logs().audio.write("HARDWARESTRING_SOFTWARE:'"+lol+"'");

		if(lol=="" || lol==" "){
			//no AL hardware
			return false;
		}
		
		#else
			//os x doesn't give us a hardware string? so ignore
		#endif

		if(versionS!="1.1"){
			logs().audio.write("error, software version still too old");
			return false;
		}

		//w0000 $$$$$$$$$$$$
		return true;
	}

	errori=alGetError();
	if(errori != AL_NO_ERROR){
		return false;
	}

	t=(char*)alcGetString(Device,ALC_DEVICE_SPECIFIER);

	return true;
}
예제 #29
0
/**
 * Initializes the audio device and creates sources.
 *
 * @warning:
 *
 * @return TRUE if initialization was successful, FALSE otherwise
 */
bool FALAudioDevice::InitializeHardware( void )
{
	// Make sure no interface classes contain any garbage
	Effects = NULL;
	DLLHandle = NULL;

	// Default to sensible channel count.
	if( MaxChannels < 1 )
	{
		MaxChannels = 32;
	}
	// Load ogg and vorbis dlls if they haven't been loaded yet
	//LoadVorbisLibraries();

	// Open device
	HardwareDevice = alcOpenDevice(nullptr);
	if( !HardwareDevice )
	{
		UE_LOG(LogALAudio, Log, TEXT( "ALAudio: no OpenAL devices found." ) );
		return  false  ;
	}

	// Display the audio device that was actually opened
	const ALCchar* OpenedDeviceName = alcGetString( HardwareDevice, ALC_DEVICE_SPECIFIER );
	UE_LOG(LogALAudio, Log, TEXT("ALAudio device opened : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(OpenedDeviceName)).Get());

	// Create a context
	int Caps[] =
	{
		ALC_FREQUENCY, 44100,
		ALC_STEREO_SOURCES, 4,
		0, 0
	};
#if PLATFORM_HTML5_WIN32 || PLATFORM_LINUX
	SoundContext = alcCreateContext( HardwareDevice, Caps );
#elif PLATFORM_HTML5
	SoundContext = alcCreateContext( HardwareDevice, 0 );
#endif

	if( !SoundContext )
	{
		return false ;
	}

	alcMakeContextCurrent(SoundContext);

	// Make sure everything happened correctly
	if( alError( TEXT( "Init" ) ) )
	{
		UE_LOG(LogALAudio, Warning, TEXT("ALAudio: alcMakeContextCurrent failed."));
		return false ;
	}

	UE_LOG(LogALAudio, Log, TEXT("AL_VENDOR      : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_VENDOR))).Get());
	UE_LOG(LogALAudio, Log, TEXT("AL_RENDERER    : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_RENDERER))).Get());
	UE_LOG(LogALAudio, Log, TEXT("AL_VERSION     : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_VERSION))).Get());
	UE_LOG(LogALAudio, Log, TEXT("AL_EXTENSIONS  : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_EXTENSIONS))).Get());

	// Get the enums for multichannel support
#if !PLATFORM_HTML5
	Surround40Format = alGetEnumValue( "AL_FORMAT_QUAD16" );
	Surround51Format = alGetEnumValue( "AL_FORMAT_51CHN16" );
	Surround61Format = alGetEnumValue( "AL_FORMAT_61CHN16" );
	Surround71Format = alGetEnumValue( "AL_FORMAT_71CHN16" );
#endif
	// Initialize channels.
	alError( TEXT( "Emptying error stack" ), 0 );
	for( int i = 0; i < (( MaxChannels >  MAX_AUDIOCHANNELS ) ? MAX_AUDIOCHANNELS : MaxChannels); i++ )
	{
		ALuint SourceId;
		alGenSources( 1, &SourceId );
		if( !alError( TEXT( "Init (creating sources)" ), 0 ) )
		{
			FALSoundSource* Source = new FALSoundSource( this );
			Source->SourceId = SourceId;
			Sources.Add( Source );
			FreeSources.Add( Source );
		}
		else
		{
			break;
		}
	}

	if( Sources.Num() < 1 )
	{
		UE_LOG(LogALAudio, Warning, TEXT("ALAudio: couldn't allocate any sources"));
		return false ;
	}

	// Update MaxChannels in case we couldn't create enough sources.
	MaxChannels = Sources.Num();
	UE_LOG(LogALAudio, Verbose, TEXT("ALAudioDevice: Allocated %i sources"), MaxChannels);

	// Use our own distance model.
	alDistanceModel( AL_NONE );

	// Set up a default (nop) effects manager
	Effects = new FAudioEffectsManager( this );

	return true ;
}
예제 #30
0
AUD_OpenALDevice::AUD_OpenALDevice(AUD_DeviceSpecs specs, int buffersize)
{
	// cannot determine how many channels or which format OpenAL uses, but
	// it at least is able to play 16 bit stereo audio
	specs.channels = AUD_CHANNELS_STEREO;
	specs.format = AUD_FORMAT_S16;

#if 0
	if(alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE)
	{
		ALCchar* devices = const_cast<ALCchar*>(alcGetString(NULL, ALC_DEVICE_SPECIFIER));
		printf("OpenAL devices (standard is: %s):\n", alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER));

		while(*devices)
		{
			printf("%s\n", devices);
			devices += strlen(devices) + 1;
		}
	}
#endif

	m_device = alcOpenDevice(NULL);

	if(!m_device)
		AUD_THROW(AUD_ERROR_OPENAL, open_error);

	// at least try to set the frequency
	ALCint attribs[] = { ALC_FREQUENCY, specs.rate, 0 };
	ALCint* attributes = attribs;
	if(specs.rate == AUD_RATE_INVALID)
		attributes = NULL;

	m_context = alcCreateContext(m_device, attributes);
	alcMakeContextCurrent(m_context);

	alcGetIntegerv(m_device, ALC_FREQUENCY, 1, (ALCint*)&specs.rate);

	// check for specific formats and channel counts to be played back
	if(alIsExtensionPresent("AL_EXT_FLOAT32") == AL_TRUE)
		specs.format = AUD_FORMAT_FLOAT32;

	m_useMC = alIsExtensionPresent("AL_EXT_MCFORMATS") == AL_TRUE;

	alGetError();
	alcGetError(m_device);

	m_specs = specs;
	m_buffersize = buffersize;
	m_playing = false;

//	m_bufferedFactories = new std::list<AUD_OpenALBufferedFactory*>();

	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);

	pthread_mutex_init(&m_mutex, &attr);

	pthread_mutexattr_destroy(&attr);

	start(false);
}