Ejemplo n.º 1
0
static VALUE Mixer_s_driverName(VALUE mod)
{
    char driver_name[512];
    if(SDL_AudioDriverName(driver_name, sizeof(driver_name)) == NULL)
        rb_raise(eSDLError, "No driver has been initialized: %s", SDL_GetError());
    return rb_str_new2(driver_name);
}
Ejemplo n.º 2
0
/**
 * @brief Prints the current and compiled SDL_Mixer versions.
 */
static void print_MixerVersion (void)
{
   int frequency;
   Uint16 format;
   int channels;
   SDL_version compiled;
   const SDL_version *linked;
   char device[PATH_MAX];

   /* Query stuff. */
   Mix_QuerySpec(&frequency, &format, &channels);
   MIX_VERSION(&compiled);
   linked = Mix_Linked_Version();
   SDL_AudioDriverName(device, PATH_MAX);

   /* Version itself. */
   DEBUG("SDL_Mixer Started: %d Hz %s", frequency,
         (channels == 2) ? "Stereo" : "Mono" );
   /* Check if major/minor version differ. */
   if ((linked->major*100 + linked->minor) > compiled.major*100 + compiled.minor)
      WARN("SDL_Mixer is newer than compiled version");
   if ((linked->major*100 + linked->minor) < compiled.major*100 + compiled.minor)
      WARN("SDL_Mixer is older than compiled version.");
   /* Print other debug info. */
   DEBUG("Renderer: %s",device);
   DEBUG("Version: %d.%d.%d [compiled: %d.%d.%d]", 
         compiled.major, compiled.minor, compiled.patch,
         linked->major, linked->minor, linked->patch);
   DEBUG();
}
Ejemplo n.º 3
0
static int configure(int rate,int channels,int format){

	/* SDL Audio Specifications */
	SDL_AudioSpec aspec, obtained;
	char drv_name[80];

	ao_data.channels=channels;
	ao_data.samplerate=rate;
	ao_data.format=format;

	ao_data.bps=channels*rate;
	if(format != AUDIO_U8 && format != AUDIO_S8)
	  ao_data.bps*=2;

	aspec.format   = format;

	/* The desired audio frequency in samples-per-second. */
	aspec.freq     = rate;

	/* Number of channels (mono/stereo) */
	aspec.channels = channels;

	/* The desired size of the audio buffer in samples. This number should be a power of two, and may be adjusted by the audio driver to a value more suitable for the hardware. Good values seem to range between 512 and 8192 inclusive, depending on the application and CPU speed. Smaller values yield faster response time, but can lead to underflow if the application is doing heavy processing and cannot fill the audio buffer in time. A stereo sample consists of both right and left channels in LR ordering. Note that the number of samples is directly related to time by the following formula: ms = (samples*1000)/freq */
	aspec.samples  = SAMPLESIZE;

	/* This should be set to a function that will be called when the audio device is ready for more data. It is passed a pointer to the audio buffer, and the length in bytes of the audio buffer. This function usually runs in a separate thread, and so you should protect data structures that it accesses by calling SDL_LockAudio and SDL_UnlockAudio in your code. The callback prototype is:
void callback(void *userdata, Uint8 *stream, int len); userdata is the pointer stored in userdata field of the SDL_AudioSpec. stream is a pointer to the audio buffer you want to fill with information and len is the length of the audio buffer in bytes. */
	aspec.callback = outputaudio;

	/* This pointer is passed as the first parameter to the callback function. */
	aspec.userdata = NULL;

	/* initialize the SDL Audio system */
        if (SDL_Init (SDL_INIT_AUDIO/*|SDL_INIT_NOPARACHUTE*/)) {
  //              MSG_ERR("SDL: Initializing of SDL Audio failed: %s.\n", SDL_GetError());
                return 0;
        }

	/* Open the audio device and start playing sound! */
	if(SDL_OpenAudio(&aspec, &obtained) < 0) {
    //    	MSG_ERR("SDL: Unable to open audio: %s\n", SDL_GetError());
        	return(0);
	}

	/* did we got what we wanted ? */
	ao_data.channels=obtained.channels;
	ao_data.samplerate=obtained.freq;

	ao_data.buffersize=obtained.size;

	printf("audio format %d\n",obtained.format);
	printf("audio samples %d\n",obtained.samples);

	SDL_AudioDriverName(drv_name, sizeof(drv_name));

	SDL_PauseAudio(0);

	return 1;
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
	char name[32];

	/* Load the SDL library */
	if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(1);
	}
	if ( argv[1] == NULL ) {
		argv[1] = "sample.wav";
	}
	/* Load the wave file into memory */
	if ( SDL_LoadWAV(argv[1],
			&wave.spec, &wave.sound, &wave.soundlen) == NULL ) {
		fprintf(stderr, "Couldn't load %s: %s\n",
						argv[1], SDL_GetError());
		quit(1);
	}

	wave.spec.callback = fillerup;
#if HAVE_SIGNAL_H
	/* Set the signals */
#ifdef SIGHUP
	signal(SIGHUP, poked);
#endif
	signal(SIGINT, poked);
#ifdef SIGQUIT
	signal(SIGQUIT, poked);
#endif
	signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */

	/* Initialize fillerup() variables */
	if ( SDL_OpenAudio(&wave.spec, NULL) < 0 ) {
		fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
		SDL_FreeWAV(wave.sound);
		quit(2);
	}
	SDL_PauseAudio(0);

	/* Let the audio run */
	printf("Using audio driver: %s\n", SDL_AudioDriverName(name, 32));
	while ( ! done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING) )
#ifdef __amigaos4__	
	{
//		__check_abort();
#endif		
		SDL_Delay(1000);
#ifdef __amigaos4__
	}
#endif			

	/* Clean up on signal */
	SDL_CloseAudio();
	SDL_FreeWAV(wave.sound);
	SDL_Quit();
	return(0);
}
Ejemplo n.º 5
0
adv_error soundb_sdl_init(int sound_id, unsigned* rate, adv_bool stereo_flag, double buffer_time)
{
	char name[64];

	log_std(("sound:sdl: soundb_sdl_init(id:%d, rate:%d, stereo:%d, buffer_time:%g)\n", (unsigned)sound_id, (unsigned)*rate, (int)stereo_flag, (double)buffer_time));

	if (!os_internal_sdl_get()) {
		error_set("Unsupported without the SDL library.\n");
		return -1;
	}

	if (!sdl_option.initialized) {
		soundb_sdl_default();
	}

	sdl_state.underflow_flag = 0;
	sdl_state.fifo_pos = 0;
	sdl_state.fifo_mac = 0;
	sdl_state.volume = SDL_VOLUME_BASE;

	if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
		error_set("Function SDL_InitSubSystem(SDL_INIT_AUDIO) failed, %s.\n", SDL_GetError());
		goto err;
	}

	if (SDL_AudioDriverName(name, sizeof(name))) {
		log_std(("sound:sdl: driver %s\n", name));
	}

	sdl_state.info.freq = *rate;
	sdl_state.info.format = AUDIO_S16LSB;
	sdl_state.info.channels = stereo_flag ? 2 : 1;
	sdl_state.info.samples = sdl_option.samples;
	sdl_state.info.callback = soundb_sdl_callback;
	sdl_state.info.userdata = &sdl_state;

	log_std(("sound:sdl: request fragment size %d [samples]\n", sdl_state.info.samples));

	if (SDL_OpenAudio(&sdl_state.info, 0) != 0) {
		error_set("Function SDL_OpenAudio(%d, AUDIO_S16LSB, %d, %d) failed, %s.\n", (unsigned)sdl_state.info.freq, (unsigned)sdl_state.info.channels, (unsigned)sdl_state.info.samples, SDL_GetError());
		goto err_quit;
	}

	log_std(("sound:sdl: result fragment size %d [samples], buffer size %d [bytes]\n", sdl_state.info.samples, sdl_state.info.size));

	*rate = sdl_state.info.freq;

	sdl_state.active_flag = 1;

	return 0;

err_quit:
	SDL_QuitSubSystem(SDL_INIT_AUDIO);
err:
	return -1;
}
Ejemplo n.º 6
0
/* API */
void es_audioDriverName(sdl_data *sd, int len, char *bp)
{
  int sendlen = 0;
    
  bp = sdl_get_temp_buff(sd, 256);
  if (SDL_AudioDriverName(bp, 256) != NULL) {
      sendlen = (int) strlen(bp);
  }
  sdl_send(sd, sendlen);
}
Ejemplo n.º 7
0
// Инициализация библиотеки эмулятора
void InitEGraph()
{
char pcCaption[80];
if (strlen(szVideoDriver)!=0)
  {
  strcpy(pcCaption, "SDL_VIDEODRIVER=");
  strcat(pcCaption,szVideoDriver);
  putenv(pcCaption);
  }
if (strlen(szAudioDriver)!=0)
  {
  strcpy(pcCaption, "SDL_AUDIODRIVER=");
  strcat(pcCaption,szAudioDriver);
  putenv(pcCaption);
  }
//putenv("SDL_VIDEODRIVER=windib");
//putenv("SDL_AUDIODRIVER=waveout");
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
if (!bMute)
  bMute=SDL_InitSubSystem(SDL_INIT_AUDIO);

char pcDrvName[20];
strcpy(pcCaption, "Emu80/SDL v. 3.14 development (video: ");
SDL_VideoDriverName(pcDrvName, 20);
strcat(pcCaption,pcDrvName);
if (!bMute)
  {
  strcat(pcCaption,", audio: ");
  SDL_AudioDriverName(pcDrvName, 20);
  strcat(pcCaption,pcDrvName);
  }
strcat(pcCaption,"), F10 - menu");

//SDL_WM_SetCaption("Emu80 / SDL", 0);
SDL_WM_SetCaption(pcCaption, 0);

atexit(SDL_Quit);

//semDraw=SDL_CreateSemaphore(1);

/*sfScreen = SDL_SetVideoMode(640, 480, 8,
                            SDL_HWSURFACE |
                            SDL_HWPALETTE);*/
pcScreenBuf=new char[160*64];
ClearScreen();
LoadFonts();

SetVideoMode(vmText30);
//ChangeResolution();

//SDL_ShowCursor(SDL_DISABLE);
ClearScreen();

InitAudio();
}
Ejemplo n.º 8
0
bool AudioSystem::init(int frequency, bool use16bit, unsigned int numOutputChannels, unsigned int bufferSize, unsigned int maxNumSampleChannels)
{
	if (isInit) {
		Mix_CloseAudio();
		isInit = false;
	} else {
		if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
			std::cout << "SDL audio initialization failed: " << SDL_GetError() << std::endl;
			return false;
		}

		ResourceManager::getInstance()->addResourceLoader(new GenericResourceLoader<Sample, Resource::SAMPLE>());
		ResourceManager::getInstance()->addResourceLoader(new GenericResourceLoader<Music, Resource::MUSIC>());
	}

	Uint16 format = use16bit ? AUDIO_S16SYS : AUDIO_S8;
	if (Mix_OpenAudio(frequency, format, numOutputChannels, bufferSize) < 0) {
		Mix_CloseAudio();
		std::cout << "failed to init sdl audio system: " << SDL_GetError() << std::endl;
		return false;
	}

	Mix_AllocateChannels(maxNumSampleChannels);

	int audio_frq, audio_channels;
	unsigned short audio_format;
	// print out some info on the audio device and stream
	Mix_QuerySpec(&audio_frq, &audio_format, &audio_channels);
    int bits = audio_format&0xFF;

	std::string audio_channels_name;
	if (audio_channels > 3) {
		audio_channels_name = "surround";
	} else if (audio_channels > 1) {
		audio_channels_name = "stereo";
	} else {
		audio_channels_name = "mono";
	}

	const int audioDriverNameBufferSize=256;
	char audioDriverNameBuffer[audioDriverNameBufferSize];

	std::cout << "Audio System" << std::endl;
	std::cout << "  Drivername: "	<< SDL_AudioDriverName(audioDriverNameBuffer, audioDriverNameBufferSize) << std::endl;
	std::cout << "  Frequency: "	<< audio_frq << " Hz" << std::endl;
	std::cout << "  Sample Rate: "	<< bits << " bits" << std::endl;
	std::cout << "  Output channels: " << audio_channels << " (" << audio_channels_name << ")" << std::endl;
	std::cout << "  Buffersize: "	<< bufferSize << " bytes (latency: " << ((float)bufferSize/audio_frq*1000) << "ms)" << std::endl;

	isInit = true;

	return true;
}
Ejemplo n.º 9
0
void SdlMixerManager::init() {
	// Start SDL Audio subsystem
	if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
		error("Could not initialize SDL: %s", SDL_GetError());
	}

	const int maxNameLen = 20;
	char sdlDriverName[maxNameLen];
	sdlDriverName[0] = '\0';
	SDL_AudioDriverName(sdlDriverName, maxNameLen);
	debug(1, "Using SDL Audio Driver \"%s\"", sdlDriverName);

	// Get the desired audio specs
	SDL_AudioSpec desired = getAudioSpec(SAMPLES_PER_SEC);

	// Needed as SDL_OpenAudio as of SDL-1.2.14 mutates fields in
	// "desired" if used directly.
	SDL_AudioSpec fmt = desired;

	// Start SDL audio with the desired specs
	if (SDL_OpenAudio(&fmt, &_obtained) != 0) {
		warning("Could not open audio device: %s", SDL_GetError());

		_mixer = new Audio::MixerImpl(g_system, desired.freq);
		assert(_mixer);
		_mixer->setReady(false);
	} else {
		debug(1, "Output sample rate: %d Hz", _obtained.freq);
		if (_obtained.freq != desired.freq)
			warning("SDL mixer output sample rate: %d differs from desired: %d", _obtained.freq, desired.freq);

		debug(1, "Output buffer size: %d samples", _obtained.samples);
		if (_obtained.samples != desired.samples)
			warning("SDL mixer output buffer size: %d differs from desired: %d", _obtained.samples, desired.samples);

		if (_obtained.format != desired.format)
			warning("SDL mixer sound format: %d differs from desired: %d", _obtained.format, desired.format);

#ifndef __SYMBIAN32__
		// The SymbianSdlMixerManager does stereo->mono downmixing,
		// but otherwise we require stereo output.
		if (_obtained.channels != 2)
			error("SDL mixer output requires stereo output device");
#endif

		_mixer = new Audio::MixerImpl(g_system, _obtained.freq);
		assert(_mixer);
		_mixer->setReady(true);

		startAudio();
	}
}
Ejemplo n.º 10
0
bool Sound_initialization(void)
{
    char SoundcardName[256];
	int audio_rate = 44100;
	int audio_channels = 2;
	int audio_bufsize = AUDIO_BUFFER;
	Uint16 audio_format = AUDIO_S16;
	SDL_version compile_version;

	sound_enabled=true;
	fprintf (stderr, "Initializing SDL_mixer.\n");

	int flags = MIX_INIT_OGG | MIX_INIT_MOD;
	int initted = Mix_Init(flags);
	if (initted & flags != flags) {
		printf("Mix_Init: Failed to init required ogg and mod support!\n");
		printf("Mix_Init: %s\n", Mix_GetError());
		sound_enabled = false;
		return false;
	}

	if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_bufsize))  {
	  fprintf (stderr, "Unable to open audio: %s\n", Mix_GetError());
	  sound_enabled=false;
	  fprintf (stderr, "Running the game without audio.\n");
	  return false;	
	} /* if */ 

	SDL_AudioDriverName (SoundcardName, sizeof (SoundcardName));
	Mix_QuerySpec (&audio_rate, &audio_format, &audio_channels);
	fprintf (stderr, "    opened %s at %d Hz %d bit %s, %d bytes audio buffer\n",
			 SoundcardName, audio_rate, audio_format & 0xFF,
			 audio_channels > 1 ? "stereo" : "mono", audio_bufsize);
	MIX_VERSION (&compile_version);
	fprintf (stderr, "    compiled with SDL_mixer version: %d.%d.%d\n",
			 compile_version.major,
			 compile_version.minor,
			 compile_version.patch);
	fprintf (stderr, "    running with SDL_mixer version: %d.%d.%d\n",
			 Mix_Linked_Version()->major,
			 Mix_Linked_Version()->minor,
			 Mix_Linked_Version()->patch);

	Sound_Init();
	Mix_HookMusic(myMusicPlayer, 0);

	return true;
} /* Sound_init */ 
Ejemplo n.º 11
0
void Sound::info()
{
    SDL_version compiledVersion;
    const SDL_version *linkedVersion;
    char driver[40] = "Unknown";
    const char *format = "Unknown";
    int rate = 0;
    uint16_t audioFormat = 0;
    int channels = 0;

    MIX_VERSION(&compiledVersion);
    linkedVersion = Mix_Linked_Version();

    SDL_AudioDriverName(driver, 40);

    Mix_QuerySpec(&rate, &audioFormat, &channels);
    switch (audioFormat)
    {
        case AUDIO_U8: format = "U8"; break;
        case AUDIO_S8: format = "S8"; break;
        case AUDIO_U16LSB: format = "U16LSB"; break;
        case AUDIO_S16LSB: format = "S16LSB"; break;
        case AUDIO_U16MSB: format = "U16MSB"; break;
        case AUDIO_S16MSB: format = "S16MSB"; break;
        default: break;
    }

    logger->log("Sound::info() SDL_mixer: %i.%i.%i (compiled)",
            compiledVersion.major,
            compiledVersion.minor,
            compiledVersion.patch);
    if (linkedVersion)
    {
        logger->log("Sound::info() SDL_mixer: %i.%i.%i (linked)",
            linkedVersion->major,
            linkedVersion->minor,
            linkedVersion->patch);
    }
    else
    {
        logger->log1("Sound::info() SDL_mixer: unknown");
    }
    logger->log("Sound::info() Driver: %s", driver);
    logger->log("Sound::info() Format: %s", format);
    logger->log("Sound::info() Rate: %i", rate);
    logger->log("Sound::info() Channels: %i", channels);
}
Ejemplo n.º 12
0
bool wxSoundBackendSDL::OpenAudio()
{
    if (!m_audioOpen)
    {
        if (!m_evtHandler)
            m_evtHandler = new wxSoundBackendSDLEvtHandler(this);

        m_spec.silence = 0;
        m_spec.samples = 4096;
        m_spec.size = 0;
        m_spec.callback = wx_sdl_audio_callback;
        m_spec.userdata = (void*)this;

        wxLogTrace(wxT("sound"), wxT("opening SDL audio..."));
        if (SDL_OpenAudio(&m_spec, NULL) >= 0)
        {
#if wxUSE_LOG_DEBUG
            char driver[256];
#if SDL_MAJOR_VERSION == 1
            SDL_AudioDriverName(driver, 256);
#elif SDL_MAJOR_VERSION > 1            
            strncpy(driver, SDL_GetCurrentAudioDriver(), 256);
#endif
            wxLogTrace(wxT("sound"), wxT("opened audio, driver '%s'"),
                       wxString(driver, wxConvLocal).c_str());
#endif
            m_audioOpen = true;
            return true;
        }
        else
        {
            wxString err(SDL_GetError(), wxConvLocal);
            wxLogError(_("Couldn't open audio: %s"), err.c_str());
            return false;
        }
    }
    return true;
}
Ejemplo n.º 13
0
//============================================================
//  sdl_init
//============================================================
static int sdl_init(running_machine &machine)
{
	int         n_channels = 2;
	int         audio_latency;
	SDL_AudioSpec   aspec, obtained;
	char audio_driver[16] = "";

	if (initialized_audio)
	{
		sdl_cleanup_audio(machine);
	}

	mame_printf_verbose("Audio: Start initialization\n");
#if (SDLMAME_SDL2)
	strncpy(audio_driver, SDL_GetCurrentAudioDriver(), sizeof(audio_driver));
#else
	SDL_AudioDriverName(audio_driver, sizeof(audio_driver));
#endif
	mame_printf_verbose("Audio: Driver is %s\n", audio_driver);

	initialized_audio = 0;

	sdl_xfer_samples = SDL_XFER_SAMPLES;
	stream_in_initialized = 0;
	stream_loop = 0;

	// set up the audio specs
	aspec.freq = machine.sample_rate();
	aspec.format = AUDIO_S16SYS;    // keep endian independent
	aspec.channels = n_channels;
	aspec.samples = sdl_xfer_samples;
	aspec.callback = sdl_callback;
	aspec.userdata = 0;

	if (SDL_OpenAudio(&aspec, &obtained) < 0)
		goto cant_start_audio;

	initialized_audio = 1;
	snd_enabled = 1;

	mame_printf_verbose("Audio: frequency: %d, channels: %d, samples: %d\n",
						obtained.freq, obtained.channels, obtained.samples);

	sdl_xfer_samples = obtained.samples;

	audio_latency = downcast<sdl_options &>(machine.options()).audio_latency();

	// pin audio latency
	if (audio_latency > MAX_AUDIO_LATENCY)
	{
		audio_latency = MAX_AUDIO_LATENCY;
	}
	else if (audio_latency < 1)
	{
		audio_latency = 1;
	}

	// compute the buffer sizes
	stream_buffer_size = machine.sample_rate() * 2 * sizeof(INT16) * audio_latency / MAX_AUDIO_LATENCY;
	stream_buffer_size = (stream_buffer_size / 1024) * 1024;
	if (stream_buffer_size < 1024)
		stream_buffer_size = 1024;

	// create the buffers
	if (sdl_create_buffers())
		goto cant_create_buffers;

	mame_printf_verbose("Audio: End initialization\n");
	return 0;

	// error handling
cant_create_buffers:
cant_start_audio:
	mame_printf_verbose("Audio: Initialization failed. SDL error: %s\n", SDL_GetError());

	return 0;
}
Ejemplo n.º 14
0
sint32 
mixSDL_Init (audio_Driver *driver, sint32 flags)
{
	int i;
	char devicename[256];
	SDL_AudioSpec desired, obtained;
	mixer_Quality quality;
	TFB_DecoderFormats formats =
	{
		MIX_IS_BIG_ENDIAN, MIX_WANT_BIG_ENDIAN,
		audio_FORMAT_MONO8, audio_FORMAT_STEREO8,
		audio_FORMAT_MONO16, audio_FORMAT_STEREO16
	};

	log_add (log_Info, "Initializing SDL audio subsystem.");
	if ((SDL_InitSubSystem(SDL_INIT_AUDIO)) == -1)
	{
		log_add (log_Error, "Couldn't initialize audio subsystem: %s",
				SDL_GetError());
		return -1;
	}
	log_add (log_Info, "SDL audio subsystem initialized.");
		
	if (flags & audio_QUALITY_HIGH)
	{
		quality = MIX_QUALITY_HIGH;
		desired.freq = 44100;
		desired.samples = 4096;
	}
	else if (flags & audio_QUALITY_LOW)
	{
		quality = MIX_QUALITY_LOW;
#ifdef __SYMBIAN32__
		desired.freq = 11025;
		desired.samples = 4096;
#else
		desired.freq = 22050;
		desired.samples = 2048;
#endif		
	}
	else
	{
		quality = MIX_QUALITY_DEFAULT;
		desired.freq = 44100;
		desired.samples = 4096;
	}

	desired.format = AUDIO_S16SYS;
	desired.channels = 2;
	desired.callback = audioCallback;
	
	log_add (log_Info, "Opening SDL audio device.");
	if (SDL_OpenAudio (&desired, &obtained) < 0)
	{
		log_add (log_Error, "Unable to open audio device: %s",
				SDL_GetError ());
		SDL_QuitSubSystem (SDL_INIT_AUDIO);
		return -1;
	}
	if (obtained.format != desired.format ||
		(obtained.channels != 1 && obtained.channels != 2))
	{
		log_add (log_Error, "Unable to obtain desired audio format.");
		SDL_CloseAudio ();
		SDL_QuitSubSystem (SDL_INIT_AUDIO);
		return -1;
	}

	SDL_AudioDriverName (devicename, sizeof (devicename));
	log_add (log_Info, "    using %s at %d Hz 16 bit %s, "
			"%d samples audio buffer",
			devicename, obtained.freq,
			obtained.channels > 1 ? "stereo" : "mono",
			obtained.samples);

	log_add (log_Info, "Initializing mixer.");
	if (!mixer_Init (obtained.freq, MIX_FORMAT_MAKE (2, obtained.channels),
			quality, 0))
	{
		log_add (log_Error, "Mixer initialization failed: %x",
				mixer_GetError ());
		SDL_CloseAudio ();
		SDL_QuitSubSystem (SDL_INIT_AUDIO);
		return -1;
	}
	log_add (log_Info, "Mixer initialized.");

	log_add (log_Info, "Initializing sound decoders.");
	if (SoundDecoder_Init (flags, &formats))
	{
		log_add (log_Error, "Sound decoders initialization failed.");
		SDL_CloseAudio ();
		mixer_Uninit ();
		SDL_QuitSubSystem (SDL_INIT_AUDIO);
		return -1;
	}
	log_add (log_Info, "Sound decoders initialized.");

	*driver = mixSDL_Driver;
	for (i = 0; i < NUM_SOUNDSOURCES; ++i)
	{
		audio_GenSources (1, &soundSource[i].handle);		
		soundSource[i].stream_mutex = CreateMutex ("MixSDL stream mutex", SYNC_CLASS_AUDIO);
	}

	if (InitStreamDecoder ())
	{
		log_add (log_Error, "Stream decoder initialization failed.");
		// TODO: cleanup source mutexes [or is it "muti"? :) ]
		SDL_CloseAudio ();
		SoundDecoder_Uninit ();
		mixer_Uninit ();
		SDL_QuitSubSystem (SDL_INIT_AUDIO);
		return -1;
	}

	SDL_PauseAudio (0);
		
	return 0;
}
Ejemplo n.º 15
0
int sound_sdl::init(const osd_options &options)
{
	int         n_channels = 2;
	int         audio_latency;
	SDL_AudioSpec   aspec, obtained;
	char audio_driver[16] = "";

	if (LOG_SOUND)
		sound_log = fopen(SDLMAME_SOUND_LOG, "w");

	// skip if sound disabled
	if (sample_rate() != 0)
	{
		if (SDL_InitSubSystem(SDL_INIT_AUDIO)) {
			osd_printf_error("Could not initialize SDL %s\n", SDL_GetError());
			return -1;
		}

		osd_printf_verbose("Audio: Start initialization\n");
	#if (SDLMAME_SDL2)
		strncpy(audio_driver, SDL_GetCurrentAudioDriver(), sizeof(audio_driver));
	#else
		SDL_AudioDriverName(audio_driver, sizeof(audio_driver));
	#endif
		osd_printf_verbose("Audio: Driver is %s\n", audio_driver);

		sdl_xfer_samples = SDL_XFER_SAMPLES;
		stream_in_initialized = 0;
		stream_loop = 0;

		// set up the audio specs
		aspec.freq = sample_rate();
		aspec.format = AUDIO_S16SYS;    // keep endian independent
		aspec.channels = n_channels;
		aspec.samples = sdl_xfer_samples;
		aspec.callback = sdl_callback;
		aspec.userdata = this;

		if (SDL_OpenAudio(&aspec, &obtained) < 0)
			goto cant_start_audio;

		osd_printf_verbose("Audio: frequency: %d, channels: %d, samples: %d\n",
							obtained.freq, obtained.channels, obtained.samples);

		sdl_xfer_samples = obtained.samples;

		// pin audio latency
		audio_latency = MAX(MIN(m_audio_latency, MAX_AUDIO_LATENCY), 1);

		// compute the buffer sizes
		stream_buffer_size = (sample_rate() * 2 * sizeof(INT16) * (2 + audio_latency)) / 30;
		stream_buffer_size = (stream_buffer_size / 1024) * 1024;
		if (stream_buffer_size < 1024)
			stream_buffer_size = 1024;

		// create the buffers
		if (sdl_create_buffers())
			goto cant_create_buffers;

		// set the startup volume
		set_mastervolume(attenuation);
		osd_printf_verbose("Audio: End initialization\n");
		return 0;

		// error handling
	cant_create_buffers:
	cant_start_audio:
		osd_printf_verbose("Audio: Initialization failed. SDL error: %s\n", SDL_GetError());

		return -1;
	}

	return 0;
}
Ejemplo n.º 16
0
/*
===============
SNDDMA_Init
===============
*/
qboolean SNDDMA_Init(void)
{
	char drivername[128];
	SDL_AudioSpec desired;
	SDL_AudioSpec obtained;
	int tmp;

	if (snd_inited)
		return qtrue;

	if (!s_sdlBits) {
		s_sdlBits = Cvar_Get("s_sdlBits", "16", CVAR_ARCHIVE);
		s_sdlSpeed = Cvar_Get("s_sdlSpeed", "0", CVAR_ARCHIVE);
		s_sdlChannels = Cvar_Get("s_sdlChannels", "2", CVAR_ARCHIVE);
		s_sdlDevSamps = Cvar_Get("s_sdlDevSamps", "0", CVAR_ARCHIVE);
		s_sdlMixSamps = Cvar_Get("s_sdlMixSamps", "0", CVAR_ARCHIVE);
	}

	Com_Printf( "SDL_Init( SDL_INIT_AUDIO )... " );

	if (!SDL_WasInit(SDL_INIT_AUDIO))
	{
		if (SDL_Init(SDL_INIT_AUDIO) == -1)
		{
			Com_Printf( "FAILED (%s)\n", SDL_GetError( ) );
			return qfalse;
		}
	}

	Com_Printf( "OK\n" );

	if (SDL_AudioDriverName(drivername, sizeof (drivername)) == NULL)
		strcpy(drivername, "(UNKNOWN)");
	Com_Printf("SDL audio driver is \"%s\".\n", drivername);

	memset(&desired, '\0', sizeof (desired));
	memset(&obtained, '\0', sizeof (obtained));

	tmp = ((int) s_sdlBits->value);
	if ((tmp != 16) && (tmp != 8))
		tmp = 16;

	desired.freq = (int) s_sdlSpeed->value;
	if(!desired.freq) desired.freq = 44100;
	desired.format = ((tmp == 16) ? AUDIO_S16SYS : AUDIO_U8);

	// I dunno if this is the best idea, but I'll give it a try...
	//  should probably check a cvar for this...
	if (s_sdlDevSamps->value)
		desired.samples = s_sdlDevSamps->value;
	else
	{
		// just pick a sane default.
		if (desired.freq <= 11025)
			desired.samples = 256;
		else if (desired.freq <= 22050)
			desired.samples = 512;
		else if (desired.freq <= 44100)
			desired.samples = 1024;
		else
			desired.samples = 2048;  // (*shrug*)
	}

	desired.channels = (int) s_sdlChannels->value;
	desired.callback = SNDDMA_AudioCallback;

	if (SDL_OpenAudio(&desired, &obtained) == -1)
	{
		Com_Printf("SDL_OpenAudio() failed: %s\n", SDL_GetError());
		SDL_QuitSubSystem(SDL_INIT_AUDIO);
		return qfalse;
	}

	SNDDMA_PrintAudiospec("SDL_AudioSpec", &obtained);

	// dma.samples needs to be big, or id's mixer will just refuse to
	//  work at all; we need to keep it significantly bigger than the
	//  amount of SDL callback samples, and just copy a little each time
	//  the callback runs.
	// 32768 is what the OSS driver filled in here on my system. I don't
	//  know if it's a good value overall, but at least we know it's
	//  reasonable...this is why I let the user override.
	tmp = s_sdlMixSamps->value;
	if (!tmp)
		tmp = (obtained.samples * obtained.channels) * 10;

	if (tmp & (tmp - 1))  // not a power of two? Seems to confuse something.
	{
		int val = 1;
		while (val < tmp)
			val <<= 1;

		tmp = val;
	}

	dmapos = 0;
	dma.samplebits = obtained.format & 0xFF;  // first byte of format is bits.
	dma.channels = obtained.channels;
	dma.samples = tmp;
	dma.submission_chunk = 1;
	dma.speed = obtained.freq;
	dmasize = (dma.samples * (dma.samplebits/8));
	dma.buffer = calloc(1, dmasize);

	Com_Printf("Starting SDL audio callback...\n");
	SDL_PauseAudio(0);  // start callback.

	Com_Printf("SDL audio initialized.\n");
	snd_inited = qtrue;
	return qtrue;
}
Ejemplo n.º 17
0
/**
 * @sa S_Shutdown
 * @sa S_Restart_f
 */
void S_Init (void)
{
    SDL_version version;
    char drivername[MAX_VAR];

    Com_Printf("\n------- sound initialization -------\n");

    OBJZERO(s_env);

    snd_init = Cvar_Get("snd_init", "1", CVAR_ARCHIVE, "Should the sound renderer get initialized");
    snd_init->modified = false; /* don't restart right away */
    Cmd_AddCommand("snd_restart", S_Restart_f, "Restart the sound renderer");

    if (!snd_init->integer) {
        Com_Printf("not initializing.\n");
        Cmd_AddCommand("music_change", Cmd_Dummy_f, "Dummy command if sound is disabled");
        Cvar_Get("snd_music", "PsymongN3", 0, "Background music track");
        return;
    }

    cl_soundSysPool = Mem_CreatePool("Client: Sound system");

    snd_distance_scale = Cvar_Get("snd_distance_scale", "0.1", 0, "Sound distance scale");
    snd_volume = Cvar_Get("snd_volume", "0.7", CVAR_ARCHIVE, "Sound volume - default is 0.7");
    snd_rate = Cvar_Get("snd_rate", "44100", CVAR_ARCHIVE, "Hz value for sound renderer - default is 44100");
    snd_chunkbufsize = Cvar_Get("snd_chunkbufsize", "1024", CVAR_ARCHIVE, "The sound buffer chunk size");
    /* set volumes to be changed so they are applied again for next sound/music playing */
    /** @todo implement the volume change for already loaded sample chunks */
    snd_volume->modified = true;

    Cmd_AddCommand("snd_play", S_Play_f, "Plays a sound fx file. Pass path relative to base/sound without file extension");
    Cmd_AddParamCompleteFunction("snd_play", S_CompleteSounds);

    if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
        if (SDL_Init(SDL_INIT_AUDIO) < 0) {
            Com_Printf("S_Init: %s.\n", SDL_GetError());
            return;
        }
    }

    MIX_VERSION(&version)
    Com_Printf("SDL_mixer version: %d.%d.%d\n", version.major, version.minor, version.patch);
    Com_Printf("... requested audio rate: %i\n", snd_rate->integer);

    if (Mix_OpenAudio(snd_rate->integer, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, snd_chunkbufsize->integer) == -1) {
        Com_Printf("S_Init: %s\n", Mix_GetError());
        return;
    }

    if (Mix_QuerySpec(&s_env.rate, &s_env.format, &s_env.numChannels) == 0) {
        Com_Printf("S_Init: %s\n", Mix_GetError());
        return;
    }

    if (SDL_AudioDriverName(drivername, sizeof(drivername)) == NULL)
        Q_strncpyz(drivername, "(UNKNOWN)", sizeof(drivername));
    Com_Printf("... driver: '%s'\n", drivername);

    if (Mix_AllocateChannels(MAX_CHANNELS) != MAX_CHANNELS) {
        Com_Printf("S_Init: %s\n", Mix_GetError());
        return;
    }

    Mix_ChannelFinished(S_FreeChannel);

    Com_Printf("... audio rate: %i\n", s_env.rate);
    Com_Printf("... audio channels: %i\n", s_env.numChannels);

#if COMPARE_VERSION(1, 2, 10)
    if (!(Mix_Init(MIX_INIT_OGG) & MIX_INIT_OGG))
        Com_Printf("... could not load ogg vorbis support\n");
    else
        Com_Printf("... loaded ogg vorbis support\n");
#endif

    s_env.initialized = true;

    M_Init();
    S_MumbleInit();
}
Ejemplo n.º 18
0
/**
 * Initialize the audio subsystem.
 */
int InitSound() 
{
    int sound, soundrate, soundbufsize, soundvolume, soundtrianglevolume,
            soundsquare1volume, soundsquare2volume, soundnoisevolume,
            soundpcmvolume, soundq, lowpass, samples;


    FCEUI_printf("Initializing audio...\n");

    g_config->getOption("SDL.Sound", &sound);
    if (!sound) return 0;

    memset(&spec, 0, sizeof(spec));
    if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
        puts(SDL_GetError());
        KillSound();
        return(0);
    }
    char driverName[8];
    SDL_AudioDriverName(driverName, 8);
    
    fprintf(stderr, "Loading SDL sound with %s driver...\n", driverName);

    // load configuration variables
    g_config->getOption("SDL.Sound.Rate", &soundrate);
    g_config->getOption("SDL.Sound.BufSize", &soundbufsize);
    g_config->getOption("SDL.Sound.Volume", &soundvolume);
    g_config->getOption("SDL.Sound.Quality", &soundq);
    g_config->getOption("SDL.Sound.TriangleVolume", &soundtrianglevolume);
    g_config->getOption("SDL.Sound.Square1Volume", &soundsquare1volume);
    g_config->getOption("SDL.Sound.Square2Volume", &soundsquare2volume);
    g_config->getOption("SDL.Sound.NoiseVolume", &soundnoisevolume);
    g_config->getOption("SDL.Sound.PCMVolume", &soundpcmvolume);
    g_config->getOption("SDL.Sound.LowPass", &lowpass);

    spec.freq = soundrate;
    spec.format = AUDIO_S16;
    spec.channels = 2;
    spec.samples = 512;
    spec.callback = fillaudio;
    spec.userdata = 0;

    while(spec.samples < (soundrate / 60) * 1) spec.samples <<= 1;

    s_BufferSize = spec.samples * 4;

    s_Buffer = (int16 *) malloc(sizeof(int16) * s_BufferSize);
    if (!s_Buffer) return 0;

    s_BufferRead = s_BufferWrite = s_BufferIn = 0;

    printf("SDL Size: %d, Internal size: %d\n", spec.samples, s_BufferSize);

    if(SDL_OpenAudio(&spec, 0) < 0) {
        puts(SDL_GetError());
        KillSound();
        return(0);
    }

    SDL_PauseAudio(0);

    FCEUI_SetSoundVolume(soundvolume);
    FCEUI_SetSoundQuality(soundq);
    FCEUI_Sound(soundrate);
    FCEUI_SetTriangleVolume(soundtrianglevolume);
    FCEUI_SetSquare1Volume(soundsquare1volume);
    FCEUI_SetSquare2Volume(soundsquare2volume);
    FCEUI_SetNoiseVolume(soundnoisevolume);
    FCEUI_SetPCMVolume(soundpcmvolume);
    FCEUI_SetLowPass(lowpass);

    return (1);
}
Ejemplo n.º 19
0
void SdlMixerManager::init() {
	// Start SDL Audio subsystem
	if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
		error("Could not initialize SDL: %s", SDL_GetError());
	}

#if SDL_VERSION_ATLEAST(2, 0, 0)
	const char *sdlDriverName = SDL_GetCurrentAudioDriver();
#else
	const int maxNameLen = 20;
	char sdlDriverName[maxNameLen];
	sdlDriverName[0] = '\0';
	SDL_AudioDriverName(sdlDriverName, maxNameLen);
#endif
	debug(1, "Using SDL Audio Driver \"%s\"", sdlDriverName);

	// Get the desired audio specs
	SDL_AudioSpec desired = getAudioSpec(SAMPLES_PER_SEC);

	// Needed as SDL_OpenAudio as of SDL-1.2.14 mutates fields in
	// "desired" if used directly.
	SDL_AudioSpec fmt = desired;

	// Start SDL audio with the desired specs
	if (SDL_OpenAudio(&fmt, &_obtained) != 0) {
		warning("Could not open audio device: %s", SDL_GetError());

		// The mixer is not marked as ready
		_mixer = new Audio::MixerImpl(g_system, desired.freq);
		return;
	}

	// The obtained sample format is not supported by the mixer, call
	// SDL_OpenAudio again with NULL as the second argument to force
	// SDL to do resampling to the desired audio spec.
	if (_obtained.format != desired.format) {
		debug(1, "SDL mixer sound format: %d differs from desired: %d", _obtained.format, desired.format);
		SDL_CloseAudio();

		if (SDL_OpenAudio(&fmt, NULL) != 0) {
			warning("Could not open audio device: %s", SDL_GetError());

			// The mixer is not marked as ready
			_mixer = new Audio::MixerImpl(g_system, desired.freq);
			return;
		}

		_obtained = desired;
	}

	debug(1, "Output sample rate: %d Hz", _obtained.freq);
	if (_obtained.freq != desired.freq)
		debug(1, "SDL mixer output sample rate: %d differs from desired: %d", _obtained.freq, desired.freq);

	debug(1, "Output buffer size: %d samples", _obtained.samples);
	if (_obtained.samples != desired.samples)
		debug(1, "SDL mixer output buffer size: %d differs from desired: %d", _obtained.samples, desired.samples);

#ifndef __SYMBIAN32__
	// The SymbianSdlMixerManager does stereo->mono downmixing,
	// but otherwise we require stereo output.
	if (_obtained.channels != 2)
		error("SDL mixer output requires stereo output device");
#endif

	_mixer = new Audio::MixerImpl(g_system, _obtained.freq);
	assert(_mixer);
	_mixer->setReady(true);

	startAudio();
}
Ejemplo n.º 20
0
const char *SDL_GetCurrentAudioDriver( void )
{
	static char driverName[ 128 ];
	return SDL_AudioDriverName( driverName, sizeof( driverName ) );
}
Ejemplo n.º 21
0
bool SNDDMA_Init( void *hwnd, bool verbose )
{
	char drivername[128];
	SDL_AudioSpec desired;
	SDL_AudioSpec obtained;
	int tmp;

	if( snd_inited )
		return 1;

	if( verbose )
		Com_Printf( "SDL Audio driver initializing...\n" );

	if( !s_bits ) {
		s_bits = trap_Cvar_Get( "s_bits", "16", CVAR_ARCHIVE | CVAR_LATCH_SOUND );
		s_channels = trap_Cvar_Get( "s_channels", "2", CVAR_ARCHIVE | CVAR_LATCH_SOUND );
	}

	if( !SDL_WasInit( SDL_INIT_AUDIO ) ) {
		if( verbose )
			Com_Printf( "Calling SDL_Init(SDL_INIT_AUDIO)...\n" );
		if( SDL_Init( SDL_INIT_AUDIO ) == -1 ) {
			Com_Printf( "SDL_Init(SDL_INIT_AUDIO) failed: %s\n", SDL_GetError() );
			return false;
		}
		if( verbose )
			Com_Printf( "SDL_Init(SDL_INIT_AUDIO) passed.\n" );
	}

#if SDL_VERSION_ATLEAST( 2, 0, 0 )
	if( SDL_GetCurrentAudioDriver() ) {
		Q_strncpyz( drivername, SDL_GetCurrentAudioDriver(), sizeof( drivername ) );
	} else {
		Q_strncpyz( drivername, "(UNKNOWN)", sizeof( drivername ) );
	}
#else
	if( SDL_AudioDriverName( drivername, sizeof( drivername ) ) == NULL )
		Q_strncpyz( drivername, "(UNKNOWN)", sizeof( drivername ) );
#endif

	if( verbose )
		Com_Printf( "SDL audio driver is \"%s\"\n", drivername );

	memset( &desired, '\0', sizeof( desired ) );
	memset( &obtained, '\0', sizeof( obtained ) );

	if( s_khz->integer == 44 )
		desired.freq = 44100;
	else if( s_khz->integer == 22 )
		desired.freq = 22050;
	else
		desired.freq = 11025;

	desired.format = ( ( s_bits->integer != 16 ) ? AUDIO_U8 : AUDIO_S16SYS );

	// I dunno if this is the best idea, but I'll give it a try...
	//  should probably check a cvar for this...
	// just pick a sane default.
	if( desired.freq <= 11025 )
		desired.samples = 256;
	else if( desired.freq <= 22050 )
		desired.samples = 512;
	else if( desired.freq <= 44100 )
		desired.samples = 1024;
	else
		desired.samples = 2048; // (*shrug*)

	desired.channels = s_channels->integer;
	desired.callback = sdl_audio_callback;

	if( SDL_OpenAudio( &desired, &obtained ) == -1 ) {
		Com_Printf( "SDL_OpenAudio() failed: %s\n", SDL_GetError() );
		SDL_QuitSubSystem( SDL_INIT_AUDIO );
		return false;
	}

	if( verbose ) {
		print_audiospec( "Format we requested from SDL audio device", &desired );
		print_audiospec( "Format we actually got", &obtained );
	}

	// dma.samples needs to be big, or id's mixer will just refuse to
	//  work at all; we need to keep it significantly bigger than the
	//  amount of SDL callback samples, and just copy a little each time
	//  the callback runs.
	// 32768 is what the OSS driver filled in here on my system. I don't
	//  know if it's a good value overall, but at least we know it's
	//  reasonable...this is why I let the user override.
	tmp = ( obtained.samples * obtained.channels ) * 4;

	if( tmp & ( tmp - 1 ) ) // not a power of two? Seems to confuse something.
	{
		int val = 1;
		while( val < tmp )
			val <<= 1;

		val >>= 1;
		if( verbose )
			Com_Printf( "WARNING: sdlmixsamps wasn't a power of two (%d), so we made it one (%d).\n", tmp, val );
		tmp = val;
	}
Ejemplo n.º 22
0
/**
 * Initialize the audio subsystem.
 */
int
InitSound()
{
	int sound, soundrate, soundbufsize, soundvolume, soundtrianglevolume, soundsquare1volume, soundsquare2volume, soundnoisevolume, soundpcmvolume, soundq;
	SDL_AudioSpec spec;

	g_config->getOption("SDL.Sound", &sound);
	if(!sound) {
		return 0;
	}

	memset(&spec, 0, sizeof(spec));
	if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
		puts(SDL_GetError());
		KillSound();
		return 0;
	}
	char driverName[8];
#if SDL_VERSION_ATLEAST(2, 0, 0)
	// TODO - SDL 2
#else
	SDL_AudioDriverName(driverName, 8);
	fprintf(stderr, "Loading SDL sound with %s driver...\n", driverName);
#endif

	// load configuration variables
	g_config->getOption("SDL.Sound.Rate", &soundrate);
	g_config->getOption("SDL.Sound.BufSize", &soundbufsize);
	g_config->getOption("SDL.Sound.Volume", &soundvolume);
	g_config->getOption("SDL.Sound.Quality", &soundq);
	g_config->getOption("SDL.Sound.TriangleVolume", &soundtrianglevolume);
	g_config->getOption("SDL.Sound.Square1Volume", &soundsquare1volume);
	g_config->getOption("SDL.Sound.Square2Volume", &soundsquare2volume);
	g_config->getOption("SDL.Sound.NoiseVolume", &soundnoisevolume);
	g_config->getOption("SDL.Sound.PCMVolume", &soundpcmvolume);

	spec.freq = soundrate;
	spec.format = AUDIO_S16SYS;
	spec.channels = 1;
	spec.samples = 512;
	spec.callback = fillaudio;
	spec.userdata = 0;

	s_BufferSize = soundbufsize * soundrate / 1000;

	// For safety, set a bare minimum:
	if (s_BufferSize < spec.samples * 2)
	s_BufferSize = spec.samples * 2;

	s_Buffer = (int *)FCEU_dmalloc(sizeof(int) * s_BufferSize);
	if (!s_Buffer)
		return 0;
	s_BufferRead = s_BufferWrite = s_BufferIn = 0;

	if(SDL_OpenAudio(&spec, 0) < 0)
	{
		puts(SDL_GetError());
		KillSound();
		return 0;
    }
	SDL_PauseAudio(0);

	FCEUI_SetSoundVolume(soundvolume);
	FCEUI_SetSoundQuality(soundq);
	FCEUI_Sound(soundrate);
	FCEUI_SetTriangleVolume(soundtrianglevolume);
	FCEUI_SetSquare1Volume(soundsquare1volume);
	FCEUI_SetSquare2Volume(soundsquare2volume);
	FCEUI_SetNoiseVolume(soundnoisevolume);
	FCEUI_SetPCMVolume(soundpcmvolume);
	return 1;
}
Ejemplo n.º 23
0
int Sound_initialization(int nc, int nrc)
{
	char SoundcardName[256];
	int audio_rate = 44100;
	int audio_channels = 2;
	int audio_bufsize = AUDIO_BUFFER;
	Uint16 audio_format = AUDIO_S16;
	SDL_version compile_version;
	n_channels = 8;

	sound_enabled = true;
#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Initializing SDL_mixer.\n");
#endif

	if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_bufsize)) {
		sound_enabled = false;
#ifdef F1SPIRIT_DEBUG_MESSAGES

		output_debug_message("Unable to open audio: %s\n", Mix_GetError());
		output_debug_message("Running the game without audio.\n");
#endif

		return -1;
	} 

	SDL_AudioDriverName (SoundcardName, sizeof (SoundcardName));

	Mix_QuerySpec (&audio_rate, &audio_format, &audio_channels);

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("    opened %s at %d Hz %d bit %s, %d bytes audio buffer\n",
	                     SoundcardName, audio_rate, audio_format & 0xFF,
	                     audio_channels > 1 ? "stereo" : "mono", audio_bufsize);

#endif

	MIX_VERSION (&compile_version);

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("    compiled with SDL_mixer version: %d.%d.%d\n",
	                     compile_version.major,
	                     compile_version.minor,
	                     compile_version.patch);

	output_debug_message("    running with SDL_mixer version: %d.%d.%d\n",
	                     Mix_Linked_Version()->major,
	                     Mix_Linked_Version()->minor,
	                     Mix_Linked_Version()->patch);

#endif

	if (nc > 0)
		n_channels = Mix_AllocateChannels(nc);

	if (nrc > 0)
		Mix_ReserveChannels(nrc);

	return n_channels;
} /* Sound_init */
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{
    int use_audio, use_video;
    int fullscreen;
    int scalesize;
    int scale_width, scale_height;
    int loop_play;
    int i, pause;
    int volume;
    Uint32 seek;
    float skip;
    int bilinear_filtering;
    SDL_Surface *screen = NULL;
    SMPEG *mpeg;
    SMPEG_Info info;
    char *basefile;
    const char *title = NULL;
    SDL_version sdlver;
    SMPEG_version smpegver;
    int fd;
    char buf[32];
    int status;

    /* Get the command line options */
    use_audio = 1;
    use_video = 1;
    fullscreen = 0;
    scalesize = 1;
    scale_width = 0;
    scale_height = 0;
    loop_play = 0;
    volume = 100;
    seek = 0;
    skip = 0;
    bilinear_filtering = 0;
    fd = 0;
    for ( i=1; argv[i] && (argv[i][0] == '-') && (argv[i][1] != 0); ++i ) {
        if ( (strcmp(argv[i], "--noaudio") == 0) ||
                (strcmp(argv[i], "--nosound") == 0) ) {
            use_audio = 0;
        } else if ( strcmp(argv[i], "--novideo") == 0 ) {
            use_video = 0;
        } else if ( strcmp(argv[i], "--fullscreen") == 0 ) {
            fullscreen = 1;
        } else if ((strcmp(argv[i], "--double") == 0)||(strcmp(argv[i], "-2") == 0)) {
            scalesize = 2;
        } else if ((strcmp(argv[i], "--loop") == 0) || (strcmp(argv[i], "-l") == 0)) {
            loop_play = 1;
        } else if ( strcmp(argv[i], "--bilinear") == 0 ) {
            bilinear_filtering = 1;
        } else if ((strcmp(argv[i], "--seek") == 0)||(strcmp(argv[i], "-S") == 0)) {
            ++i;
            if ( argv[i] ) {
                seek = atol(argv[i]);
            }
        } else if ((strcmp(argv[i], "--skip") == 0)||(strcmp(argv[i], "-k") == 0)) {
            ++i;
            if ( argv[i] ) {
                skip = (float)atof(argv[i]);
            }
        } else if ((strcmp(argv[i], "--volume") == 0)||(strcmp(argv[i], "-v") == 0)) {
            ++i;
            if (i >= argc)
            {
                fprintf(stderr, "Please specify volume when using --volume or -v\n");
                return(1);
            }
            if ( argv[i] ) {
                volume = atoi(argv[i]);
            }
            if ( ( volume < 0 ) || ( volume > 100 ) ) {
                fprintf(stderr, "Volume must be between 0 and 100\n");
                volume = 100;
            }
        } else if ((strcmp(argv[i], "--title") == 0)||(strcmp(argv[i], "-t") == 0)) {
            ++i;
            if (i >= argc)
            {
                fprintf(stderr, "Please specify title when using --title or -t\n");
                return(1);
            }
            if ( argv[i] ) {
                title = argv[i];
            }
        } else if ((strcmp(argv[i], "--version") == 0) ||
                   (strcmp(argv[i], "-V") == 0)) {
            sdlver = *SDL_Linked_Version();
            SMPEG_VERSION(&smpegver);
            printf("SDL version: %d.%d.%d\n"
                   "SMPEG version: %d.%d.%d\n",
                   sdlver.major, sdlver.minor, sdlver.patch,
                   smpegver.major, smpegver.minor, smpegver.patch);
            return(0);
        } else if ((strcmp(argv[i], "--scale") == 0)||(strcmp(argv[i], "-s") == 0)) {
            ++i;
            if ( argv[i] ) {
                sscanf(argv[i], "%dx%d", &scale_width, &scale_height);
            }
        } else if ((strcmp(argv[i], "--help") == 0) || (strcmp(argv[i], "-h") == 0)) {
            usage(argv[0]);
            return(0);
        } else {
            fprintf(stderr, "Warning: Unknown option: %s\n", argv[i]);
        }
    }
    /* If there were no arguments just print the usage */
    if (argc == 1) {
        usage(argv[0]);
        return(0);
    }

#if defined(linux) || defined(__FreeBSD__) /* Plaympeg doesn't need a mouse */
    putenv("SDL_NOMOUSE=1");
#endif

    /* Play the mpeg files! */
    status = 0;
    for ( ; argv[i]; ++i ) {
        /* Initialize SDL */
        if ( use_video ) {
            if ((SDL_Init(SDL_INIT_VIDEO) < 0) || !SDL_VideoDriverName(buf, 1)) {
                fprintf(stderr, "Warning: Couldn't init SDL video: %s\n",
                        SDL_GetError());
                fprintf(stderr, "Will ignore video stream\n");
                use_video = 0;
            }
        }

        if ( use_audio ) {
            if ((SDL_Init(SDL_INIT_AUDIO) < 0) || !SDL_AudioDriverName(buf, 1)) {
                fprintf(stderr, "Warning: Couldn't init SDL audio: %s\n",
                        SDL_GetError());
                fprintf(stderr, "Will ignore audio stream\n");
                use_audio = 0;
            }
        }

        /* Allow Ctrl-C when there's no video output */
        signal(SIGINT, next_movie);

        /* Create the MPEG stream */
#ifdef NET_SUPPORT
#ifdef RAW_SUPPORT
        /* Check if source is an IP address and port*/
        if((fd = raw_open(argv[i])) != 0)
            mpeg = SMPEG_new_descr(fd, &info, use_audio);
        else
#endif
#ifdef HTTP_SUPPORT
            /* Check if source is an http URL */
            if((fd = http_open(argv[i])) != 0)
                mpeg = SMPEG_new_descr(fd, &info, use_audio);
            else
#endif
#ifdef FTP_SUPPORT
                /* Check if source is an http URL */
                if((fd = ftp_open(argv[i])) != 0)
                    mpeg = SMPEG_new_descr(fd, &info, use_audio);
                else
#endif
#endif
#ifdef VCD_SUPPORT
                    /* Check if source is a CDROM device */
                    if((fd = vcd_open(argv[i])) != 0)
                        mpeg = SMPEG_new_descr(fd, &info, use_audio);
                    else
#endif
                    {
                        if(strcmp(argv[i], "-") == 0) /* Use stdin for input */
                            mpeg = SMPEG_new_descr(0, &info, use_audio);
                        else
                            mpeg = SMPEG_new(argv[i], &info, use_audio);
                    }

        if ( SMPEG_error(mpeg) ) {
            fprintf(stderr, "%s: %s\n", argv[i], SMPEG_error(mpeg));
            SMPEG_delete(mpeg);
            status = -1;
            continue;
        }
        SMPEG_enableaudio(mpeg, use_audio);
        SMPEG_enablevideo(mpeg, use_video);
        SMPEG_setvolume(mpeg, volume);

        /* Enable software bilinear filtering, if desired */
        if ( bilinear_filtering ) {
            SMPEG_Filter *filter;

            filter = SMPEGfilter_bilinear();
            filter = SMPEG_filter( mpeg, filter );
            filter->destroy(filter);
        }

        /* Print information about the video */
        basefile = strrchr(argv[i], '/');
        if ( basefile ) {
            ++basefile;
        } else {
            basefile = argv[i];
        }
        if ( info.has_audio && info.has_video ) {
            printf("%s: MPEG system stream (audio/video)\n", basefile);
        } else if ( info.has_audio ) {
            printf("%s: MPEG audio stream\n", basefile);
        } else if ( info.has_video ) {
            printf("%s: MPEG video stream\n", basefile);
        }
        if ( info.has_video ) {
            printf("\tVideo %dx%d resolution\n", info.width, info.height);
        }
        if ( info.has_audio ) {
            printf("\tAudio %s\n", info.audio_string);
        }
        if ( info.total_size ) {
            printf("\tSize: %d\n", info.total_size);
        }
        if ( info.total_time ) {
            printf("\tTotal time: %f\n", info.total_time);
        }

        /* Set up video display if needed */
        if ( info.has_video && use_video ) {
            const SDL_VideoInfo *video_info;
            Uint32 video_flags;
            int video_bpp;
            int width, height;

            /* Get the "native" video mode */
            video_info = SDL_GetVideoInfo();
            switch (video_info->vfmt->BitsPerPixel) {
            case 16:
            case 24:
            case 32:
                video_bpp = video_info->vfmt->BitsPerPixel;
                break;
            default:
                video_bpp = 16;
                break;
            }
            if ( scale_width ) {
                width = scale_width;
            } else {
                width = info.width;
            }
            width *= scalesize;
            if ( scale_height ) {
                height = scale_height;
            } else {
                height = info.height;
            }
            height *= scalesize;
            video_flags = SDL_SWSURFACE;
            if ( fullscreen ) {
                video_flags = SDL_FULLSCREEN|SDL_DOUBLEBUF|SDL_HWSURFACE;
            }
            video_flags |= SDL_ASYNCBLIT;
            video_flags |= SDL_RESIZABLE;
            screen = SDL_SetVideoMode(width, height, video_bpp, video_flags);
            if ( screen == NULL ) {
                fprintf(stderr, "Unable to set %dx%d video mode: %s\n",
                        width, height, SDL_GetError());
                continue;
            }
            if (title != NULL) {
                SDL_WM_SetCaption(title, title);
            } else {
                SDL_WM_SetCaption(argv[i], "plaympeg");
            }
            if ( screen->flags & SDL_FULLSCREEN ) {
                SDL_ShowCursor(0);
            }
            SMPEG_setdisplay(mpeg, screen, NULL, update);
            SMPEG_scaleXY(mpeg, screen->w, screen->h);
        } else {
            SDL_QuitSubSystem(SDL_INIT_VIDEO);
            use_video = 0;
        }

        /* Set any special playback parameters */
        if ( loop_play ) {
            SMPEG_loop(mpeg, 1);
        }

        /* Seek starting position */
        if(seek) SMPEG_seek(mpeg, seek);

        /* Skip seconds to starting position */
        if(skip) SMPEG_skip(mpeg, skip);

        /* Play it, and wait for playback to complete */
        SMPEG_play(mpeg);
        done = 0;
        pause = 0;
        while ( ! done && ( pause || (SMPEG_status(mpeg) == SMPEG_PLAYING) ) ) {
            SDL_Event event;

            while ( use_video && SDL_PollEvent(&event) ) {
                switch (event.type) {
                case SDL_VIDEORESIZE: {
                    SDL_Surface *old_screen = screen;
                    SMPEG_pause(mpeg);
                    screen = SDL_SetVideoMode(event.resize.w, event.resize.h, screen->format->BitsPerPixel, screen->flags);
                    if ( old_screen != screen ) {
                        SMPEG_setdisplay(mpeg, screen, NULL, update);
                    }
                    SMPEG_scaleXY(mpeg, screen->w, screen->h);
                    SMPEG_pause(mpeg);
                }
                break;
                case SDL_KEYDOWN:
                    if ( (event.key.keysym.sym == SDLK_ESCAPE) || (event.key.keysym.sym == SDLK_q) ) {
                        // Quit
                        done = 1;
                    } else if ( event.key.keysym.sym == SDLK_RETURN ) {
                        // toggle fullscreen
                        if ( event.key.keysym.mod & KMOD_ALT ) {
                            SDL_WM_ToggleFullScreen(screen);
                            fullscreen = (screen->flags & SDL_FULLSCREEN);
                            SDL_ShowCursor(!fullscreen);
                        }
                    } else if ( event.key.keysym.sym == SDLK_UP ) {
                        // Volume up
                        if ( volume < 100 ) {
                            if ( event.key.keysym.mod & KMOD_SHIFT ) {   // 10+
                                volume += 10;
                            } else if ( event.key.keysym.mod & KMOD_CTRL ) { // 100+
                                volume = 100;
                            } else {                                     // 1+
                                volume++;
                            }
                            if ( volume > 100 )
                                volume = 100;
                            SMPEG_setvolume(mpeg, volume);
                        }
                    } else if ( event.key.keysym.sym == SDLK_DOWN ) {
                        // Volume down
                        if ( volume > 0 ) {
                            if ( event.key.keysym.mod & KMOD_SHIFT ) {
                                volume -= 10;
                            } else if ( event.key.keysym.mod & KMOD_CTRL ) {
                                volume = 0;
                            } else {
                                volume--;
                            }
                            if ( volume < 0 )
                                volume = 0;
                            SMPEG_setvolume(mpeg, volume);
                        }
                    } else if ( event.key.keysym.sym == SDLK_PAGEUP ) {
                        // Full volume
                        volume = 100;
                        SMPEG_setvolume(mpeg, volume);
                    } else if ( event.key.keysym.sym == SDLK_PAGEDOWN ) {
                        // Volume off
                        volume = 0;
                        SMPEG_setvolume(mpeg, volume);
                    } else if ( event.key.keysym.sym == SDLK_SPACE ) {
                        // Toggle play / pause
                        if ( SMPEG_status(mpeg) == SMPEG_PLAYING ) {
                            SMPEG_pause(mpeg);
                            pause = 1;
                        } else {
                            SMPEG_play(mpeg);
                            pause = 0;
                        }
                    } else if ( event.key.keysym.sym == SDLK_RIGHT ) {
                        // Forward
                        if ( event.key.keysym.mod & KMOD_SHIFT ) {
                            SMPEG_skip(mpeg, 100);
                        } else if ( event.key.keysym.mod & KMOD_CTRL ) {
                            SMPEG_skip(mpeg, 50);
                        } else {
                            SMPEG_skip(mpeg, 5);
                        }
                    } else if ( event.key.keysym.sym == SDLK_LEFT ) {
                        // Reverse
                        if ( event.key.keysym.mod & KMOD_SHIFT ) {

                        } else if ( event.key.keysym.mod & KMOD_CTRL ) {

                        } else {

                        }
                    } else if ( event.key.keysym.sym == SDLK_KP_MINUS ) {
                        // Scale minus
                        if ( scalesize > 1 ) {
                            scalesize--;
                        }
                    } else if ( event.key.keysym.sym == SDLK_KP_PLUS ) {
                        // Scale plus
                        scalesize++;
                    } else if ( event.key.keysym.sym == SDLK_f ) {
                        // Toggle filtering on/off
                        if ( bilinear_filtering ) {
                            SMPEG_Filter *filter = SMPEGfilter_null();
                            filter = SMPEG_filter( mpeg, filter );
                            filter->destroy(filter);
                            bilinear_filtering = 0;
                        } else {
                            SMPEG_Filter *filter = SMPEGfilter_bilinear();
                            filter = SMPEG_filter( mpeg, filter );
                            filter->destroy(filter);
                            bilinear_filtering = 1;
                        }
                    }
                    break;
                case SDL_QUIT:
                    done = 1;
                    break;
                default:
                    break;
                }
            }
            SDL_Delay(1000/2);
        }
        SMPEG_delete(mpeg);
    }
    SDL_Quit();

#if defined(RAW_SUPPORT) || defined(HTTP_SUPPORT) || defined(FTP_SUPPORT) || \
    defined(VCD_SUPPORT)
    if(fd) close(fd);
#endif

    return(status);
}
Ejemplo n.º 25
0
//============================================================
//	sdl_init
//============================================================
static int sdl_init(running_machine *machine)
{
    int			n_channels = 2;
    int			audio_latency;
    SDL_AudioSpec 	aspec, obtained;
    char audio_driver[16];

    if (initialized_audio)
    {
        sdl_cleanup_audio(machine);
    }

    initialized_audio = 0;

    sdl_xfer_samples = SDL_XFER_SAMPLES;
    stream_in_initialized = 0;
    stream_loop = 0;

    // set up the audio specs
    aspec.freq = machine->sample_rate;
    aspec.format = AUDIO_S16SYS;	// keep endian independant
    aspec.channels = n_channels;
    aspec.samples = sdl_xfer_samples;
    aspec.callback = sdl_callback;
    aspec.userdata = 0;

    if (SDL_OpenAudio(&aspec, &obtained) < 0)
        goto cant_start_audio;

    initialized_audio = 1;
    snd_enabled = 1;

#if (SDL_VERSION_ATLEAST(1,3,0))
    strncpy(audio_driver, SDL_GetCurrentAudioDriver(), sizeof(audio_driver));
#else
    SDL_AudioDriverName(audio_driver, sizeof(audio_driver));
#endif
    mame_printf_verbose("Audio initialized - driver: %s, frequency: %d, "
                        "channels: %d, samples: %d\n", audio_driver,
                        obtained.freq, obtained.channels, obtained.samples);

    sdl_xfer_samples = obtained.samples;

    audio_latency = options_get_int(mame_options(), SDLOPTION_AUDIO_LATENCY);

    // pin audio latency
    if (audio_latency > MAX_AUDIO_LATENCY)
    {
        audio_latency = MAX_AUDIO_LATENCY;
    }
    else if (audio_latency < 1)
    {
        audio_latency = 1;
    }

    // compute the buffer sizes
    stream_buffer_size = machine->sample_rate * 2 * sizeof(INT16) * audio_latency / MAX_AUDIO_LATENCY;
    stream_buffer_size = (stream_buffer_size / 1024) * 1024;
    if (stream_buffer_size < 1024)
        stream_buffer_size = 1024;

    // create the buffers
    if (sdl_create_buffers())
        goto cant_create_buffers;

    return 0;

    // error handling
cant_create_buffers:
cant_start_audio:
    return 0;
}