Example #1
1
int SOUND_OpenAudio(int freq, int format, int channels, int samples)
{
   if (g_fAudioOpened) {
      return 0;
   }

   // Set the audio format
   audio_spec.freq = freq;
   audio_spec.format = format;
   audio_spec.channels = channels; // 1 = mono, 2 = stereo
   audio_spec.samples = samples;
   audio_spec.callback = SOUND_FillAudio;
   audio_spec.userdata = nullptr;

   // Open the audio device, forcing the desired format
   if (SDL_OpenAudio(&audio_spec, nullptr) < 0) {
      fprintf(stderr, "WARNING: Couldn't open audio: %s\n", SDL_GetError());
      return -1;
   } else {
      g_fAudioOpened = true;
      return 0;
   }
}
Example #2
1
const char* Sync_Audio::start( long sample_rate, int chan_count, int latency )
{
	stop();
	
	write_buf = 0;
	write_pos = 0;
	read_buf = 0;
	
	long sample_latency = latency * sample_rate * chan_count / 1000;
	buf_count = sample_latency / buf_size;
	if ( buf_count < 2 )
		buf_count = 2;
	
	bufs = (sample_t*) malloc( (long) buf_size * buf_count * sizeof *bufs );
	if ( !bufs )
		return "Out of memory";
	
	free_sem = SDL_CreateSemaphore( buf_count - 1 );
	if ( !free_sem )
		return sdl_error( "Couldn't create semaphore" );
	
	SDL_AudioSpec as;
	as.freq = sample_rate;
	as.format = AUDIO_S16SYS;
	as.channels = chan_count;
	as.silence = 0;
	as.samples = buf_size / chan_count;
	as.size = 0;
	as.callback = fill_buffer_;
	as.userdata = this;
	if ( SDL_OpenAudio( &as, 0 ) < 0 )
		return sdl_error( "Couldn't open SDL audio" );
	SDL_PauseAudio( 0 );
	sound_open = 1;
	
	return 0; // success
}
Example #3
0
int shr::SDLAudio::Open(unsigned freq, unsigned samples, void *buf) {
  int res;

  udata = buf;
  
  fmt.freq = freq; 
  fmt.format = AUDIO_S16LSB;
  fmt.channels = 2;
  fmt.samples = samples;
  fmt.callback = cb;
  fmt.userdata = this;

  res = SDL_OpenAudio(&fmt, NULL);
  if(res < 0) {
    std::cerr << "SDLAudio::Open failed, "
      << SDL_GetError() << std::endl;
    return -1;
  }

  SDL_LockMutex(mut);

  return 0;
}
Example #4
0
const char* Sound_Queue::start( long sample_rate, int chan_count )
{
	assert( !bufs ); // can only be initialized once
	
	write_buf = 0;
	write_pos = 0;
	read_buf = 0;
	
#ifndef DREAMCAST
	bufs = new sample_t [(long) buf_size * buf_count];
#else
    bufs = (sample_t *)std::malloc((long) buf_size * buf_count); 
#endif	
    if ( !bufs )
		return "Out of memory";
	currently_playing_ = bufs;
	
	free_sem = SDL_CreateSemaphore( buf_count - 1 );
	if ( !free_sem )
		return sdl_error( "Couldn't create semaphore" );
	
	SDL_AudioSpec as;
	as.freq = sample_rate;
	as.format = AUDIO_S16SYS;
	as.channels = chan_count;
	as.silence = 0;
	as.samples = buf_size / chan_count;
	as.size = 0;
	as.callback = fill_buffer_;
	as.userdata = this;
	if ( SDL_OpenAudio( &as, NULL ) < 0 )
		return sdl_error( "Couldn't open SDL audio" );
	SDL_PauseAudio( false );
	sound_open = true;
	
	return NULL;
}
Example #5
0
static void init_sdl() {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0) {
    exit(11);
  }

  //SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  //SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  //SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  //SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  //SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);

  /* Set the video mode */
  int videoFlags = SDL_OPENGL;
  if (fullscreen)
    videoFlags |= SDL_FULLSCREEN;

  SDL_Surface *surface = SDL_SetVideoMode(scrWidth, scrHeight, scrBPP,
					  videoFlags);
  if (!surface) {
    SDL_Quit();
    exit(12);
  }

  SDL_WM_SetCaption("Latheific!", "Latheific!");

  SDL_AudioSpec aspec;
  aspec.freq = 44100;
  aspec.format = AUDIO_S16;
  aspec.channels = 1;
  aspec.samples = 2048;
  aspec.callback = audio_callback;
  aspec.userdata = 0;
  if (SDL_OpenAudio(&aspec, NULL) != 0) {
    SDL_Quit();
    exit(13);
  }
}
Example #6
0
int main(int argc, char **argv) {

    SDL_AudioSpec spec_voulue;
    spec_voulue.freq = 44100;
    spec_voulue.format = AUDIO_S16; /* Tableau d'entiers 16-bit */
    spec_voulue.channels = 2;    /* 1 = mono, 2 = stereo */
    spec_voulue.samples = 1024;  /* Une puissance de 2 sympa (pas plus de 4096) */
    spec_voulue.callback = remplir_audio;
    spec_voulue.userdata = NULL;
    if(SDL_OpenAudio(&spec_voulue, NULL) < 0) {
        fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    if(argc <= 1) {
        fprintf(stderr, "Usage: %s <music.wav>\n", argv[0]);
        return EXIT_FAILURE;
    }
    SDL_AudioSpec wav_spec = spec_voulue;
    if(!SDL_LoadWAV(argv[1], &wav_spec, &son_samples, &son_taille)) {
        fprintf(stderr, "Could not open `%s': %s\n", argv[1], SDL_GetError());
        return EXIT_FAILURE;
    }
    son_curseur = son_samples;

    SDL_PauseAudio(0);

    /* On attend 1/10 de seconde de manière répétée
     * tant que le son n'a pas fini de jouer. */
    while(son_curseur < son_samples+son_taille)
        SDL_Delay(100);

    SDL_FreeWAV(son_samples);
    SDL_CloseAudio();

    return EXIT_SUCCESS;
}
Example #7
0
void AudioEngine::init(const AudioParams& ap, float volume) 
{
    m_Volume = volume;
    if (!m_bInitialized) {
        m_bInitialized = true;
        m_AP = ap;
        Dynamics<float, 2>* pLimiter = new Dynamics<float, 2>(float(m_AP.m_SampleRate));
        pLimiter->setThreshold(0.f); // in dB
        pLimiter->setAttackTime(0.f); // in seconds
        pLimiter->setReleaseTime(0.05f); // in seconds
        pLimiter->setRmsTime(0.f); // in seconds
        pLimiter->setRatio(std::numeric_limits<float>::infinity());
        pLimiter->setMakeupGain(0.f); // in dB
        m_pLimiter = pLimiter;

        SDL_AudioSpec desired;
        desired.freq = m_AP.m_SampleRate;
        desired.format = AUDIO_S16SYS;
        desired.channels = m_AP.m_Channels;
        desired.silence = 0;
        desired.samples = m_AP.m_OutputBufferSamples;
        desired.callback = audioCallback;
        desired.userdata = this;

        int err = SDL_OpenAudio(&desired, 0);
        if (err < 0) {
            static bool bWarned = false;
            if (!bWarned) {
                AVG_TRACE(Logger::category::CONFIG, Logger::severity::WARNING,
                        "Can't open audio: " << SDL_GetError());
                bWarned = true;
            }
        }
    } else {
        SDL_PauseAudio(0);
    }
}
Example #8
0
/**
 * audio_sdl_init(): Initialize the SDL audio subsystem.
 * @return 0 on success; non-zero on error.
 */
static int audio_sdl_init(void)
{
	if (audio_initialized)
		return -1;
	
	// Make sure sound is shut down first.
	audio_sdl_end();
	
	// Attempt to initialize SDL audio.
	if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
		return -1;
	
	// Set up the SDL audio specification.
	SDL_AudioSpec spec;
	spec.freq = audio_get_sound_rate();
	spec.format = AUDIO_S16SYS;
	spec.channels = !(audio_get_stereo()) ? 1 : 2; // TODO: Initializing 1 channel seems to double-free if it's later changed...
	spec.samples = 1024;
	spec.callback = audio_sdl_callback;
	spec.userdata = NULL;
	
	// Initialize the audio buffer.
	audio_sdl_audiobuf = (unsigned char*)(calloc(1, (spec.samples * spec.channels * 2 * 4) * sizeof(short)));
	
	if (SDL_OpenAudio(&spec, 0) != 0)
	{
		// Could not open audio.
		free(audio_sdl_audiobuf);
		audio_sdl_audiobuf = NULL;
		return -2;
	}
	SDL_PauseAudio(0);
	
	// Sound is initialized.
	audio_initialized = TRUE;
	return 0;
}
Example #9
0
int osd_start_audio_stream(int stereo)
{
	stream_cache_channels = (stereo?2:1);

	if (options.force_stereo) stream_cache_channels=2;

	/* determine the number of samples per frame */
	//Fix for games like galaxian that have fractional fps
	if(Machine->drv->frames_per_second > 60) 
	{
		samples_per_frame = Machine->sample_rate / (int)Machine->drv->frames_per_second;
	} 
	else 
	{
		samples_per_frame = Machine->sample_rate / Machine->drv->frames_per_second;
	}
	bytes_per_frame = (samples_per_frame * stream_cache_channels * sizeof(int16_t));

	//Sound switched off?
	if (Machine->sample_rate == 0) return samples_per_frame;

	// attempt to initialize SDL
	SDL_AudioSpec spec;
	SDL_zero(spec);
	spec.freq = Machine->sample_rate;
	spec.format = AUDIO_S16SYS;
	spec.channels = stream_cache_channels;
	spec.samples = 1024;
	if (SDL_OpenAudio(&spec, NULL) < 0) {
		logerror("Couldn't open audio: %s\n", SDL_GetError());
		Machine->sample_rate = 0;
		return samples_per_frame;
	}
	SDL_PauseAudioDevice(audio_device, 0);

	return samples_per_frame;
}
Example #10
0
/**
 * Initialise audio.
 */
void openAudio () {

	SDL_AudioSpec asDesired;

#if defined(USE_MODPLUG)
	musicFile = NULL;
#elif defined(USE_XMP)
	xmpC = xmp_create_context();
#endif


	// Set up SDL audio

	asDesired.freq = SOUND_FREQ;
	asDesired.format = AUDIO_S16;
	asDesired.channels = 2;
#if defined(GP2X) || defined(PSP) || defined(_3DS)
	asDesired.samples = 512;
#else
	asDesired.samples = 2048;
#endif
	asDesired.callback = audioCallback;
	asDesired.userdata = NULL;

	if (SDL_OpenAudio(&asDesired, &audioSpec) < 0)
		logError("Unable to open audio", SDL_GetError());


	// Load sounds

	if (loadSounds("SOUNDS.000") != E_NONE) sounds = NULL;

	// Start audio for sfx to work
	SDL_PauseAudio(0);
	return;

}
Example #11
0
int CSound::Init()
{
	m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();
	m_pStorage = Kernel()->RequestInterface<IStorage>();
	
	SDL_AudioSpec Format;
	
	m_SoundLock = lock_create();
	
	if(!g_Config.m_SndEnable)
		return 0;
	
	m_MixingRate = g_Config.m_SndRate;

	// Set 16-bit stereo audio at 22Khz
	Format.freq = g_Config.m_SndRate; // ignore_convention
	Format.format = AUDIO_S16; // ignore_convention
	Format.channels = 2; // ignore_convention
	Format.samples = g_Config.m_SndBufferSize; // ignore_convention
	Format.callback = SdlCallback; // ignore_convention
	Format.userdata = NULL; // ignore_convention

	// Open the audio device and start playing sound!
	if(SDL_OpenAudio(&Format, NULL) < 0)
	{
		dbg_msg("client/sound", "unable to open audio: %s", SDL_GetError());
		return -1;
	}
	else
		dbg_msg("client/sound", "sound init successful");

	SDL_PauseAudio(0);
	
	m_SoundEnabled = 1;
	Update(); // update the volume
	return 0;
}
Example #12
0
/* InitSound:
 *  Initialise le module de streaming audio.
 */
void
InitSound(void)
{
  SDL_AudioSpec desired;
  SDL_AudioSpec obtained;

  memset(&obtained,0,sizeof(SDL_AudioSpec));
  memset(&desired,0,sizeof(SDL_AudioSpec));

# if 0
  desired.freq     = SDL_SOUND_FREQ;
  desired.format   = AUDIO_U8;
  desired.samples  = SDL_SOUND_BUFFER_SIZE;
  desired.channels = 1;
  desired.callback = loc_SoundCallback;
# else
  desired.freq     = SDL_SOUND_FREQ; // 44100
  desired.format   = AUDIO_S16;
  desired.samples  = SDL_SOUND_BUFFER_SIZE;
  desired.channels = 2;
  desired.callback = loc_SoundCallback;
# endif

  if (SDL_OpenAudio(&desired, &obtained) < 0) {
    fprintf(stderr, "Could not open audio: %s\n", SDL_GetError());
    exit(1);
  }
# if 0 //LUDO: FOR_DEBUG
  fprintf(stdout, "freq=%d\n", obtained.freq);
  fprintf(stdout, "format=%d\n", obtained.format);
  fprintf(stdout, "samples=%d\n", obtained.samples);
  fprintf(stdout, "channels=%d\n", obtained.channels);
# endif
  memset(sdl_sound_buffer, 0x0, SDL_SOUND_BUFFER_BYTES);
  SDL_PauseAudio(0);
  THOM.thom_sound_mute = 0;
}
Example #13
0
int sound_init_sdl() {
	
	SDL_AudioSpec fmt;

	ordenador.sign=0;
	ordenador.format=1; //16 bit LE
	ordenador.channels=2; //stereo
	ordenador.freq=48000;
	ordenador.buffer_len=4096;
	
	 /* Set 16-bit stereo audio at 48Khz */
    fmt.freq = ordenador.freq;
    fmt.format = AUDIO_S16SYS; //signed Little endian/Big endian
    fmt.channels = ordenador.channels;
    fmt.samples = ordenador.buffer_len; //number of samples
    fmt.callback = sdlcallback;
    fmt.userdata = NULL;
	
	started_sound_sdl=0;

    /* Open the audio device and start playing sound! */
    if (SDL_OpenAudio(&fmt, NULL) < 0 ) return -1;
	
	printf("SDL audio initiated\n");
	
	ordenador.freq = fmt.freq;
    ordenador.channels = fmt.channels;
    ordenador.buffer_len = fmt.samples; //number of samples
	
	printf("freq = %d\n",fmt.freq);
	printf("channels = %d\n",fmt.channels);
	printf("buffer_len = %d\n",fmt.samples);
	printf("format = %x\n",fmt.format);

	return 0;
}
void HWInitialise(void)
{
    unsigned int i,xs,ys;
    char Msg[128];
    Screen = ScreenBuffer = NULL;

    for (i = 0;i < 16;i++) FromHW[i]=-1;          /* Create HW->Logical table */
    for (i = 0;i < 16;i++) FromHW[ToHW[i]] = i;

    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)   /* Try to start up SDL */
                                        == -1) MERROR(); 
    atexit(SDL_Quit);                             /* What happens on exit */

    Screen = SDL_SetVideoMode(Glo.xSize,Glo.ySize,Glo.Depth,SDL_SWSURFACE);
    if (Screen == NULL) MERROR();

    ScreenBuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,
                                        Screen->w,Screen->h,
                                        Screen->format->BytesPerPixel*8,0,0,0,0);
    if (ScreenBuffer == NULL) MERROR();
    SDL_EnableUNICODE(1);
    sprintf(Msg,"Football Manager %s",VERSION);
    SDL_WM_SetCaption(Msg,NULL);
    xs = Glo.xSize/256;ys = Glo.ySize/192;        /* Calculate working scale */
    Scale = (xs > ys) ? ys : xs;
    xOffset = (Glo.xSize-256*Scale)/2;            /* And frame */
    yOffset = (Glo.ySize-192*Scale)/2;

    AudioSpec.freq = 11025;                       /* Audio frequency */
    AudioSpec.format = AUDIO_U8;
    AudioSpec.channels = 1;
    AudioSpec.samples = 1024;
    AudioSpec.callback = HWFillAudio;
    AudioSpec.userdata = NULL;
    AudioFound = (SDL_OpenAudio(&AudioSpec,NULL) >= 0);
}
Example #15
0
bool SoundSDL::init()
{
	SDL_AudioSpec audio;
	audio.freq = SDL_SAMPLE_RATE;
	audio.format = AUDIO_S16SYS;
	audio.channels = 2;
	audio.samples = 1024;
	audio.callback = soundCallback;
	audio.userdata = this;

	if(SDL_OpenAudio(&audio, NULL))
	{
		fprintf(stderr,"Failed to open audio: %s\n", SDL_GetError());
		return false;
	}

	_rbuf.reset(_delay * SDL_SAMPLE_RATE * 2);

	_cond  = SDL_CreateCond();
	_mutex = SDL_CreateMutex();
	_initialized = true;

	return true;
}
Example #16
0
void init_audio_platform(struct config_info *conf)
{
  SDL_AudioSpec desired_spec =
  {
    0,
    AUDIO_S16SYS,
    2,
    0,
    conf->buffer_size,
    0,
    0,
    sdl_audio_callback,
    NULL
  };

  desired_spec.freq = audio.output_frequency;

  SDL_OpenAudio(&desired_spec, &audio_settings);
  audio.mix_buffer = cmalloc(audio_settings.size * 2);
  audio.buffer_samples = audio_settings.samples;

  // now set the audio going
  SDL_PauseAudio(0);
}
Example #17
0
  void Audio_Init(void) {
    Sound_Init(); // Init SDL_Sound
    // output_decoders();

    SDL_AudioSpec* spec = new SDL_AudioSpec;
//    spec->freq = 22050;
    spec->freq = 48000;
//    spec->format = AUDIO_S16SYS;
    spec->format = AUDIO_S16LSB;
    spec->channels = 2;
    spec->samples = 1024;

    sound = new Sound::System(spec);

    spec->userdata = sound;
    spec->callback = sound->GetCallback();

		SDL_AudioSpec obtained;

    if(SDL_OpenAudio( spec, &obtained ) != 0) {
      fprintf(stderr, "[error] %s\n", SDL_GetError());
      sound->SetStatus(Sound::eUninitialized);
    } else {
      sound->SetStatus(Sound::eInitialized);
			/*
			fprintf(stderr, "[sound] frequency: %d\n", obtained.freq);
			fprintf(stderr, "[sound] format: %d\n", obtained.format);
			fprintf(stderr, "[sound] channels: %d\n", obtained.channels);
			fprintf(stderr, "[sound] silence: %d\n", obtained.silence);
			fprintf(stderr, "[sound] buffer in samples: %d\n", obtained.samples);
			fprintf(stderr, "[sound] buffer in bytes: %d\n", obtained.size);
			*/
    }
    sound->SetMixMusic(gSettingsCache.playMusic);
    sound->SetMixFX(gSettingsCache.playEffects);
  }
Example #18
0
File: e8910.c Project: visy/vecx
void
e8910_init_sound()
{
	// SDL audio stuff
	SDL_AudioSpec reqSpec;
	SDL_AudioSpec givenSpec;

	PSG.Regs = snd_regs;
	PSG.RNG  = 1;
	PSG.OutputA = 0;
	PSG.OutputB = 0;
	PSG.OutputC = 0;
	PSG.OutputN = 0xff;
	e8910_build_mixer_table();
	PSG.ready = 1;

	// set up audio buffering
	reqSpec.freq = SOUND_FREQ;            // Audio frequency in samples per second
	reqSpec.format = AUDIO_U8;          // Audio data format
	reqSpec.channels = 1;            // Number of channels: 1 mono, 2 stereo
	reqSpec.samples = SOUND_SAMPLE;            // Audio buffer size in samples
	reqSpec.callback = e8910_callback;      // Callback function for filling the audio buffer
	reqSpec.userdata = NULL;
	/* Open the audio device */
	if ( SDL_OpenAudio(&reqSpec, &givenSpec) < 0 ){
		fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
		exit(-1);
	}

# if 0
	fprintf(stdout, "samples:%d format=%x freq=%d\n", givenSpec.samples, givenSpec.format, givenSpec.freq);
# endif

	// Start playing audio
	SDL_PauseAudio(0);
}
Example #19
0
void srv_sound_on()
{
	SDL_AudioSpec desired, obtained;

	if (quiet==0)
	{
		if (sound_is_on) return;

		desired.freq = 44100;		/* CD-quality */
		desired.callback = fillerup;
		desired.format = AUDIO_S16;	/* 16-bit */
		desired.channels = 1;		/* mono */
		desired.samples = 1024;		/* SQ_Max/3 */

		if ( SDL_OpenAudio(&desired, &obtained) < 0 ) 
		{
			printf("Couldn't open audio: %s\n",SDL_GetError());
			quiet = 1;
		}

		SDL_PauseAudio(0);		/* turn on the callback */
		sound_is_on = 1;
	}
}
/* Open the audio device to what we want */
void
wxGamePanel::StartBuzzer()
{
    if (! m_buzzing) {
        SDL_AudioSpec as;

        /* Fill out what we want */
        as.freq = 44100;
        as.format = AUDIO_S16SYS;
        as.channels = 2;
        as.samples = 1024;
        as.callback = CreateTone;

        /* Get it */
        SDL_OpenAudio(&as, NULL);
 
        /* Go! */
        SDL_PauseAudio(0);

        m_buzzerTimer.Start(1000, true); // 1 sec

        m_buzzing = true;
    }
}
Example #21
0
  SDLAudioDevice*
  SDLAudioDevice::create(const ParameterList& parameters) {
    std::string device = parameters.getValue("device", "DEFAULT");

    if (device != "DEFAULT") {
         device = "SDL_AUDIO_DRIVER=" + device;
         putenv(const_cast<char *>(device.c_str()));
    }
    
    SDL_AudioSpec pars;

    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
        fprintf(stderr, "Unable to init SDL audio: %s.\n", SDL_GetError());
        return 0;
    }
   
//    fprintf(stderr, "SDL audio intialized\n");
    
    pars.freq = 44100;
    pars.callback = sdl_callback;
    pars.format = AUDIO_S16SYS;
    pars.channels = 2;
    pars.samples = 2048;

    SDLAudioDevice *dev =  new SDLAudioDevice(pars.samples * 16, pars.silence);
    pars.userdata = dev;
    
    if (SDL_OpenAudio(&pars, NULL) < 0) {
      delete dev;
      fprintf(stderr, "Unable to open SDL audio unit: %s.\n", SDL_GetError());
      return 0;
    }

//    fprintf(stderr, "SDL unit opened: %lx\n", dev);
    return dev;
  }
Example #22
0
static qboolean SDL_InitCard(soundcardinfo_t *sc, const char *devicename)
{
	SDL_AudioSpec desired, obtained;

	if(!SSDL_InitAudio())
	{
		Con_Printf("Couldn't initialize SDL audio subsystem\n");
		return false;
	}

	memset(&desired, 0, sizeof(desired));

	desired.freq = sc->sn.speed;
	desired.channels = sc->sn.numchannels;	//fixme!
	desired.samples = 0x0200;	//'Good values seem to range between 512 and 8192 inclusive, depending on the application and CPU speed.'
	desired.format = AUDIO_S16SYS;
	desired.callback = (void*)SSDL_Paint;
	desired.userdata = sc;
	memcpy(&obtained, &desired, sizeof(obtained));

#if SDL_MAJOR_VERSION >= 2
	sc->audio_fd = SDL_OpenAudioDevice(devicename, false, &desired, &obtained, (sndcardinfo?0:SDL_AUDIO_ALLOW_FREQUENCY_CHANGE) | SDL_AUDIO_ALLOW_CHANNELS_CHANGE);
	if (!sc->audio_fd)
	{
		Con_Printf("SDL_OpenAudioDevice(%s) failed: couldn't open sound device (%s).\n", devicename?devicename:"default", SDL_GetError());
		return false;
	}
	if (devicename)
		Con_Printf("Initing SDL audio device '%s'.\n", devicename);
	else
		Con_Printf("Initing default SDL audio device.\n");
#else
	if (sndcardinfo)
		return false;	//SDL1 only supports opening one audio device at a time. the existing one might not be sdl, but I don't care.
	if ( SDL_OpenAudio(&desired, &obtained) < 0 )
	{
		Con_Printf("SDL_OpenAudio failed: couldn't open sound device (%s).\n", SDL_GetError());
		return false;
	}
	Con_Printf("Initing default SDL audio device.\n");
#endif
	sc->sn.numchannels = obtained.channels;
	sc->sn.speed = obtained.freq;
	sc->sn.samplebits = obtained.format&0xff;
	sc->sn.samples = 32768;//*sc->sn.numchannels;	//doesn't really matter, so long as it's higher than obtained.samples

#ifdef SELFPAINT
	sc->selfpainting = true;
#endif

	Con_DPrintf("channels: %i\n", sc->sn.numchannels);
	Con_DPrintf("Speed: %i\n", sc->sn.speed);
	Con_DPrintf("Samplebits: %i\n", sc->sn.samplebits);
	Con_DPrintf("SDLSamples: %i (low for latency)\n", obtained.samples);
	Con_DPrintf("FakeSamples: %i\n", sc->sn.samples);

#ifndef SELFPAINT
	sc->sn.buffer = malloc(sc->sn.samples*sc->sn.samplebits/8);
#endif
	Con_DPrintf("Got sound %i-%i\n", obtained.freq, obtained.format);

	sc->Lock		= SSDL_LockBuffer;
	sc->Unlock		= SSDL_UnlockBuffer;
	sc->Submit		= SSDL_Submit;
	sc->Shutdown		= SSDL_Shutdown;
	sc->GetDMAPos		= SSDL_GetDMAPos;

#if SDL_MAJOR_VERSION >= 2
	SDL_PauseAudioDevice(sc->audio_fd, 0);
#else
	SDL_PauseAudio(0);
#endif

	return true;
}
Example #23
0
/* Open the mixer with a certain desired audio format */
int Mix_OpenAudio(int frequency, Uint16 format, int nchannels, int chunksize)
{
	int i;
	SDL_AudioSpec desired;

	/* If the mixer is already opened, increment open count */
	if ( audio_opened ) {
		if ( format == mixer.format && nchannels == mixer.channels ) {
			++audio_opened;
			return(0);
		}
		while ( audio_opened ) {
			Mix_CloseAudio();
		}
	}

	/* Set the desired format and frequency */
	desired.freq = frequency;
	desired.format = format;
	desired.channels = nchannels;
	desired.samples = chunksize;
	desired.callback = mix_channels;
	desired.userdata = NULL;

	/* Accept nearly any audio format */
	if ( SDL_OpenAudio(&desired, &mixer) < 0 ) {
		return(-1);
	}
#if 0
	PrintFormat("Audio device", &mixer);
#endif

	/* Initialize the music players */
	if ( open_music(&mixer) < 0 ) {
		SDL_CloseAudio();
		return(-1);
	}

	num_channels = MIX_CHANNELS;
	mix_channel = (struct _Mix_Channel *) SDL_malloc(num_channels * sizeof(struct _Mix_Channel));

	/* Clear out the audio channels */
	for ( i=0; i<num_channels; ++i ) {
		mix_channel[i].chunk = NULL;
		mix_channel[i].playing = 0;
		mix_channel[i].looping = 0;
		mix_channel[i].volume = SDL_MIX_MAXVOLUME;
		mix_channel[i].fade_volume = SDL_MIX_MAXVOLUME;
		mix_channel[i].fade_volume_reset = SDL_MIX_MAXVOLUME;
		mix_channel[i].fading = MIX_NO_FADING;
		mix_channel[i].tag = -1;
		mix_channel[i].expire = 0;
		mix_channel[i].effects = NULL;
		mix_channel[i].paused = 0;
	}
	Mix_VolumeMusic(SDL_MIX_MAXVOLUME);

	_Mix_InitEffects();

	/* This list is (currently) decided at build time. */
	add_chunk_decoder("WAVE");
	add_chunk_decoder("AIFF");
	add_chunk_decoder("VOC");
#ifdef OGG_MUSIC
	add_chunk_decoder("OGG");
#endif
#ifdef FLAC_MUSIC
	add_chunk_decoder("FLAC");
#endif

	audio_opened = 1;
	SDL_PauseAudio(0);
	return(0);
}
Example #24
0
int main(int argc, char *argv[]) {
    AVFormatContext *pFormatCtx;
    int             i, videoStream, audioStream;
    AVCodecContext  *pCodecCtx;
    AVCodec         *pCodec;
    AVFrame         *pFrame;
    AVPacket        packet;
    int             frameFinished;
    float           aspect_ratio;
    struct SwsContext *img_convert_ctx;

    AVCodecContext  *aCodecCtx;
    AVCodec         *aCodec;

    SDL_Overlay     *bmp;
    SDL_Surface     *screen;
    SDL_Rect        rect;
    SDL_Event       event;
    SDL_AudioSpec   wanted_spec, spec;

    if(argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }
    // Register all formats and codecs
    av_register_all();

    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
        exit(1);
    }

    // Open video file
    if(av_open_input_file(&pFormatCtx, argv[1], NULL, 0, NULL)!=0)
        return -1; // Couldn't open file

    // Retrieve stream information
    if(av_find_stream_info(pFormatCtx)<0)
        return -1; // Couldn't find stream information

    // Dump information about file onto standard error
    dump_format(pFormatCtx, 0, argv[1], 0);

    // Find the first video stream
    videoStream=-1;
    audioStream=-1;
    for(i=0; i<pFormatCtx->nb_streams; i++) {
        if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO &&
                videoStream < 0) {
            videoStream=i;
        }
        if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO &&
                audioStream < 0) {
            audioStream=i;
        }
    }
    if(videoStream==-1)
        return -1; // Didn't find a video stream
    if(audioStream==-1)
        return -1;

    aCodecCtx=pFormatCtx->streams[audioStream]->codec;
    // Set audio settings from codec info
    wanted_spec.freq = aCodecCtx->sample_rate;
    wanted_spec.format = AUDIO_S16SYS;
    wanted_spec.channels = aCodecCtx->channels;
    wanted_spec.silence = 0;
    wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
    wanted_spec.callback = audio_callback;
    wanted_spec.userdata = aCodecCtx;

    if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
        fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
        return -1;
    }
    aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
    if(!aCodec) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1;
    }
    
    if (avcodec_open(aCodecCtx, aCodec) < 0) {
		fprintf(stderr, "Cannot open audio codec!\n");
		return -1;
	}

    // audio_st = pFormatCtx->streams[index]
    packet_queue_init(&audioq);
    SDL_PauseAudio(0);

    // Get a pointer to the codec context for the video stream
    pCodecCtx=pFormatCtx->streams[videoStream]->codec;

    // Find the decoder for the video stream
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==NULL) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1; // Codec not found
    }
    // Open codec
    if(avcodec_open(pCodecCtx, pCodec)<0) {
		fprintf(stderr, "Cannot open video codec!\n");
        return -1; // Could not open codec
	}
	
	// construct the scale context, conversing to PIX_FMT_YUV420P
    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);// other codes
	if (img_convert_ctx == NULL) {
		fprintf(stderr, "Cannot initialize the conversion context!\n");
		return -1;
	}

    // Allocate video frame
    pFrame=avcodec_alloc_frame();

    // Make a screen to put our video

#ifndef __DARWIN__
    screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);
#else
    screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 24, 0);
#endif
    if(!screen) {
        fprintf(stderr, "SDL: could not set video mode - exiting\n");
        exit(1);
    }

    // Allocate a place to put our YUV image on that screen
    bmp = SDL_CreateYUVOverlay(pCodecCtx->width,
                               pCodecCtx->height,
                               SDL_YV12_OVERLAY,
                               screen);


    // Read frames and save first five frames to disk
    i=0;
    while(av_read_frame(pFormatCtx, &packet)>=0) {
        // Is this a packet from the video stream?
        if(packet.stream_index==videoStream) {
            // Decode video frame
            avcodec_decode_video(pCodecCtx, pFrame, &frameFinished,
                                 packet.data, packet.size);

            // Did we get a video frame?
            if(frameFinished) {
                SDL_LockYUVOverlay(bmp);

                AVPicture pict;
                pict.data[0] = bmp->pixels[0];
                pict.data[1] = bmp->pixels[2];
                pict.data[2] = bmp->pixels[1];

                pict.linesize[0] = bmp->pitches[0];
                pict.linesize[1] = bmp->pitches[2];
                pict.linesize[2] = bmp->pitches[1];

                // Convert the image into YUV format that SDL uses
                /*
                img_convert(&pict, PIX_FMT_YUV420P,
                            (AVPicture *)pFrame, pCodecCtx->pix_fmt,
                            pCodecCtx->width, pCodecCtx->height);
				*/
				sws_scale(img_convert_ctx, (const uint8_t * const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pict.data, pict.linesize);
				
                SDL_UnlockYUVOverlay(bmp);

                rect.x = 0;
                rect.y = 0;
                rect.w = pCodecCtx->width;
                rect.h = pCodecCtx->height;
                SDL_DisplayYUVOverlay(bmp, &rect);
                av_free_packet(&packet);
            }
        } else if(packet.stream_index==audioStream) {
            packet_queue_put(&audioq, &packet);
        } else {
            av_free_packet(&packet);
        }
        // Free the packet that was allocated by av_read_frame
        SDL_PollEvent(&event);
        switch(event.type) {
        case SDL_QUIT:
            quit = 1;
            SDL_Quit();
            exit(0);
            break;
        default:
            break;
        }

    }
    
    sws_freeContext(img_convert_ctx);

    // Free the YUV frame
    av_free(pFrame);

    // Close the codec
    avcodec_close(pCodecCtx);

    // Close the video file
    av_close_input_file(pFormatCtx);

    return 0;
}
Example #25
0
static int consumer_play_audio( consumer_sdl self, mlt_frame frame, int init_audio, int *duration )
{
	// Get the properties of self consumer
	mlt_properties properties = self->properties;
	mlt_audio_format afmt = mlt_audio_s16;

	// Set the preferred params of the test card signal
	int channels = mlt_properties_get_int( properties, "channels" );
	int dest_channels = channels;
	int frequency = mlt_properties_get_int( properties, "frequency" );
	static int counter = 0;

	int samples = mlt_sample_calculator( mlt_properties_get_double( self->properties, "fps" ), frequency, counter++ );
	
	int16_t *pcm;
	int bytes;

	mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
	*duration = ( ( samples * 1000 ) / frequency );
	pcm += mlt_properties_get_int( properties, "audio_offset" );

	if ( mlt_properties_get_int( properties, "audio_off" ) )
	{
		self->playing = 1;
		init_audio = 1;
		return init_audio;
	}

	if ( init_audio == 1 )
	{
		SDL_AudioSpec request;
		SDL_AudioSpec got;

		int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );

		// specify audio format
		memset( &request, 0, sizeof( SDL_AudioSpec ) );
		self->playing = 0;
		request.freq = frequency;
		request.format = AUDIO_S16SYS;
		request.channels = dest_channels;
		request.samples = audio_buffer;
		request.callback = sdl_fill_audio;
		request.userdata = (void *)self;
		if ( SDL_OpenAudio( &request, &got ) != 0 )
		{
			mlt_log_error( MLT_CONSUMER_SERVICE( self ), "SDL failed to open audio: %s\n", SDL_GetError() );
			init_audio = 2;
		}
		else if ( got.size != 0 )
		{
			SDL_PauseAudio( 0 );
			init_audio = 0;
		}
	}

	if ( init_audio == 0 )
	{
		mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
		
		bytes = samples * dest_channels * sizeof(*pcm);
		pthread_mutex_lock( &self->audio_mutex );
		while ( self->running && bytes > ( sizeof( self->audio_buffer) - self->audio_avail ) )
			pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
		if ( self->running )
		{
			if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
			{
				if ( channels == dest_channels )
				{
					memcpy( &self->audio_buffer[ self->audio_avail ], pcm, bytes );
				}
				else
				{
					int16_t *dest = (int16_t*) &self->audio_buffer[ self->audio_avail ];
					int i = samples + 1;
					
					while ( --i )
					{
						memcpy( dest, pcm, dest_channels * sizeof(*pcm) );
						pcm += channels;
						dest += dest_channels;
					}
				}
			}
			else
			{
				memset( &self->audio_buffer[ self->audio_avail ], 0, bytes );
			}
			self->audio_avail += bytes;
		}
		pthread_cond_broadcast( &self->audio_cond );
		pthread_mutex_unlock( &self->audio_mutex );
	}
	else
	{
		self->playing = 1;
	}

	return init_audio;
}
Example #26
0
bool visualiserWin::play(std::string &file)
{
	//Initalise ffmpeg.
	av_register_all();

	//Attempt to open the file.
	AVFormatContext* fmtCtx;
	if(av_open_input_file(&fmtCtx, file.c_str(), NULL, 0, NULL) != 0)
	{
		std::cerr << "Could not open file." << std::endl;
		return false;
	}

	if(av_find_stream_info(fmtCtx) < 0)
	{
		std::cerr << "Could not find stream information." << std::cerr;
		return false;
	}

	AVCodecContext* codecCtx;
	int audioStream = -1;
	for(int i = 0; i < fmtCtx->nb_streams; i++)
	{
		if(fmtCtx->streams[i]->codec->codec_type ==
		   CODEC_TYPE_AUDIO)
		{
			audioStream = i;
			break;
		}
	}

	if(audioStream == -1)
	{
		std::cerr << "Couldn't find audio stream." << std::endl;
		return false;
	}

	codecCtx = fmtCtx->streams[audioStream]->codec;

	AVCodec *codec;
	codec = avcodec_find_decoder(codecCtx->codec_id);
	if(!codec)
	{
		std::cerr << "Could not find codec!" << std::endl;
		return false;
	}
	avcodec_open(codecCtx, codec);

	SDL_AudioSpec wantedSpec;
	SDL_AudioSpec gotSpec;

	packetQueue* queue = new packetQueue;

	sdlargst* SDLArgs = new sdlargst;

	SDLArgs->avcodeccontext = codecCtx;
	SDLArgs->queue = queue;
	SDLArgs->dspman = dspman;

	wantedSpec.freq = codecCtx->sample_rate;
	wantedSpec.format = AUDIO_S16SYS;
	wantedSpec.channels = codecCtx->channels;
	wantedSpec.silence = 0;
	wantedSpec.samples = 1024;
	wantedSpec.callback = audioThreadEntryPoint;
	wantedSpec.userdata = (void*)SDLArgs;

	if(SDL_OpenAudio(&wantedSpec, &gotSpec) < 0)
	{
		throw(SDLException());
		return false;
	}

	SDL_PauseAudio(0);

	//Construct worker thread arguments.
	ffmpegargst* args = new ffmpegargst;
	args->audiostream = audioStream;
	args->avformatcontext = fmtCtx;
	args->queue = queue;

	//Begin ffmpeg worker thread.
	ffmpegworkerthread = new pthread_t;

	//Run the thread.
	pthread_create(ffmpegworkerthread, NULL, ffmpegWorkerEntry, args);

	// Also run the sound.
	return false;
}
Example #27
0
qboolean
SNDDMA_Init (void)
{
	SDL_AudioSpec desired, obtained;
	int desired_bits, freq;
	
	if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
		if (SDL_Init(SDL_INIT_AUDIO) < 0) {
			Com_Printf ("Couldn't init SDL audio: %s\n", SDL_GetError ());
			return 0;
		}
	} else if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
		if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
			Com_Printf ("Couldn't init SDL audio: %s\n", SDL_GetError ());
			return 0;
		}
	}
	
	snd_inited = 0;
	desired_bits = (Cvar_Get("sndbits", "16", CVAR_ARCHIVE))->value;

	/* Set up the desired format */
	freq = (Cvar_Get("s_khz", "0", CVAR_ARCHIVE))->value;
	if (freq == 44)
		desired.freq = 44100;
	else if (freq == 22)
		desired.freq = 22050;
	else
		desired.freq = 11025;
	
	switch (desired_bits) {
		case 8:
			desired.format = AUDIO_U8;
			break;
		case 16:
			if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
				desired.format = AUDIO_S16MSB;
			else
				desired.format = AUDIO_S16LSB;
			break;
		default:
			Com_Printf ("Unknown number of audio bits: %d\n", desired_bits);
			return 0;
	}
	desired.channels = (Cvar_Get("sndchannels", "2", CVAR_ARCHIVE))->value;
	
	if (desired.freq == 44100)
		desired.samples = 2048;
	else if (desired.freq == 22050)
		desired.samples = 1024;
	else
		desired.samples = 512;
	
	desired.callback = paint_audio;
	
	/* Open the audio device */
	if (SDL_OpenAudio (&desired, &obtained) < 0) {
		Com_Printf ("Couldn't open SDL audio: %s\n", SDL_GetError ());
		return 0;
	}

	/* Make sure we can support the audio format */
	switch (obtained.format) {
		case AUDIO_U8:
			/* Supported */
			break;
		case AUDIO_S16LSB:
		case AUDIO_S16MSB:
			if (((obtained.format == AUDIO_S16LSB) &&
				 (SDL_BYTEORDER == SDL_LIL_ENDIAN)) ||
				((obtained.format == AUDIO_S16MSB) &&
				 (SDL_BYTEORDER == SDL_BIG_ENDIAN))) {
				/* Supported */
				break;
			}
			/* Unsupported, fall through */ ;
		default:
			/* Not supported -- force SDL to do our bidding */
			SDL_CloseAudio ();
			if (SDL_OpenAudio (&desired, NULL) < 0) {
				Com_Printf ("Couldn't open SDL audio: %s\n", SDL_GetError ());
				return 0;
			}
			memcpy (&obtained, &desired, sizeof (desired));
			break;
	}
	SDL_PauseAudio (0);

	/* Fill the audio DMA information block */
	shm = &dma;
	shm->samplebits = (obtained.format & 0xFF);
	shm->speed = obtained.freq;
	shm->channels = obtained.channels;
	shm->samples = obtained.samples * shm->channels;
	shm->samplepos = 0;
	shm->submission_chunk = 1;
	shm->buffer = NULL;

	snd_inited = 1;
	return 1;
}
Example #28
0
void InitializeAudio(int freq)
{    
    if(SDL_WasInit(SDL_INIT_AUDIO|SDL_INIT_TIMER) == (SDL_INIT_AUDIO|SDL_INIT_TIMER) ) 
    {
#ifdef DEBUG
        printf("[JttL's SDL Audio plugin] Debug: Audio and timer allready initialized.\n");
#endif
    }
    else 
    {
#ifdef DEBUG
        printf("[JttL's SDL Audio plugin] Debug: Audio and timer not yet initialized. Initializing...\n");
#endif
        InitializeSDL();
    }
    if (critical_failure == 1)
        return;
    GameFreq = freq; // This is important for the sync
    if(hardware_spec != NULL) free(hardware_spec);
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Prototype of our callback function
    void my_audio_callback(void *userdata, Uint8 *stream, int len);

    // Open the audio device
    SDL_AudioSpec *desired, *obtained;
    
    // Allocate a desired SDL_AudioSpec
    desired = malloc(sizeof(SDL_AudioSpec));
    
    // Allocate space for the obtained SDL_AudioSpec
    obtained = malloc(sizeof(SDL_AudioSpec));
    
    // 22050Hz - FM Radio quality
    //desired->freq=freq;
    
    if(freq < 11025) OutputFreq = 11025;
    else if(freq < 22050) OutputFreq = 22050;
    else OutputFreq = 44100;
    
    desired->freq = OutputFreq;
    
#ifdef DEBUG
    printf("[JttL's SDL Audio plugin] Debug: Requesting frequency: %iHz.\n", desired->freq);
#endif
    /* 16-bit signed audio */
    desired->format=AUDIO_S16SYS;
#ifdef DEBUG
    printf("[JttL's SDL Audio plugin] Debug: Requesting format: %i.\n", desired->format);
#endif
    /* Stereo */
    desired->channels=2;
    /* Large audio buffer reduces risk of dropouts but increases response time */
    desired->samples=SecondaryBufferSize;

    /* Our callback function */
    desired->callback=my_audio_callback;
    desired->userdata=NULL;

    if(buffer == NULL)
    {
        printf("[JttL's SDL Audio plugin] Allocating memory for audio buffer: %i bytes.\n", (int) (PrimaryBufferSize*sizeof(Uint8)));
        buffer = (Uint8*) malloc(PrimaryBufferSize);
    }

    if (mixBuffer == NULL)
    {
        //this should be the size of the SDL audio buffer
        mixBuffer = (Uint8*) malloc(SecondaryBufferSize * 4);
    }

    memset(buffer, 0, PrimaryBufferSize * sizeof(Uint8));

    /* Open the audio device */
    if ( SDL_OpenAudio(desired, obtained) < 0 )
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Couldn't open audio: %s\n", SDL_GetError());
        critical_failure = 1;
        return;
    }
    /* desired spec is no longer needed */

    if(desired->format != obtained->format)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained audio format differs from requested.\n");
    }
    if(desired->freq != obtained->freq)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained frequency differs from requested.\n");
    }
    free(desired);
    hardware_spec=obtained;

#ifdef DEBUG
    printf("[JttL's SDL Audio plugin] Debug: Frequency: %i\n", hardware_spec->freq);
    printf("[JttL's SDL Audio plugin] Debug: Format: %i\n", hardware_spec->format);
    printf("[JttL's SDL Audio plugin] Debug: Channels: %i\n", hardware_spec->channels);
    printf("[JttL's SDL Audio plugin] Debug: Silence: %i\n", hardware_spec->silence);
    printf("[JttL's SDL Audio plugin] Debug: Samples: %i\n", hardware_spec->samples);
    printf("[JttL's SDL Audio plugin] Debug: Size: %i\n", hardware_spec->size);
#endif
    SDL_PauseAudio(0);
    
    /* set playback volume */
    if (VolumeControlType == VOLUME_TYPE_SDL)
    {
        VolSDL = SDL_MIX_MAXVOLUME * VolPercent / 100;
    }
    else
    {
        VolPercent = volGet();
    }

}
Example #29
0
EXPORT void CALL DllTest ( HWND hParent )
{
    // Defining flags for tests
    BOOL init_audio = FALSE;
    BOOL init_timer = FALSE;
    BOOL open_audio_device = FALSE;
    BOOL format_match = FALSE;
    BOOL freq_match = FALSE;

    // Storage for SDL_Errors.
    char *sdl_error[3];

    // Clear the pointers (Should not be truly necessary unless something horrible goes wrong)
    memset(sdl_error, 0, sizeof(char*[3]));

    // Print out inital message
    printf("[JttL's SDL Audio plugin] Starting Audio Test.\n");

    // Make Sure SDL Audio is disabled so we can restart fresh
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Quit the subsystems before attempting to reinitalize them, if either are initalized already
    if(SDL_WasInit(SDL_INIT_AUDIO) != 0) SDL_QuitSubSystem(SDL_INIT_AUDIO);
    if(SDL_WasInit(SDL_INIT_TIMER) != 0) SDL_QuitSubSystem(SDL_INIT_TIMER);

    // Attempt to initialize SDL Audio
    if(SDL_Init(SDL_INIT_AUDIO) < 0 )
    {
        sdl_error[0] = SDL_GetError();
        printf("[JttL's SDL Audio plugin] Error: Couldn't initialize audio subsystem: %s\n", sdl_error[0]);
        init_audio = FALSE;
    }
    else
    {
        printf("[JttL's SDL Audio plugin] Audio subsystem initialized.\n");
        init_audio = TRUE;
    }

    // Attempt to initialize SDL Timer
    if(SDL_InitSubSystem(SDL_INIT_TIMER) < 0 )
    {
        sdl_error[1] = SDL_GetError();
        printf("[JttL's SDL Audio plugin] Error: Couldn't initialize timer subsystem: %s\n", sdl_error[1]);
        init_timer = FALSE;
    }
    else
    {
        printf("[JttL's SDL Audio plugin] Timer subsystem initialized.\n");
        init_timer = TRUE;
    }

    // Close the audio device
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Prototype of our callback function
    void my_audio_callback(void *userdata, Uint8 *stream, int len);

    // Open the audio device
    SDL_AudioSpec *desired, *obtained;

    // Allocate a desired SDL_AudioSpec
    desired = malloc(sizeof(SDL_AudioSpec));

    // Allocate space for the obtained SDL_AudioSpec
    obtained = malloc(sizeof(SDL_AudioSpec));

    // 22050Hz - FM Radio quality
    desired->freq=GameFreq;

    // Print out message for frequency
    printf("[JttL's SDL Audio plugin] Requesting frequency: %iHz.\n", desired->freq);

    // 16-bit signed audio
    desired->format=AUDIO_S16SYS;

    // Print out message for format
    printf("[JttL's SDL Audio plugin] Requesting format: %i.\n", desired->format);

    // Enable two hardware channels (for Stereo output)
    desired->channels=2;

    // Large audio buffer reduces risk of dropouts but increases response time
    desired->samples=SecondaryBufferSize;

    // Our callback function
    desired->callback=my_audio_callback;
    desired->userdata=NULL;

    // Open the audio device
    if ( SDL_OpenAudio(desired, obtained) < 0 )
    {
        sdl_error[2] = SDL_GetError();
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Couldn't open audio device: %s\n", sdl_error[2]);
        open_audio_device = FALSE;
    }
    else 
    {
        open_audio_device = TRUE;
    }

    // Check to see if we have the audio format we requested.
    if(desired->format != obtained->format)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained audio format differs from requested.\n");
        format_match = FALSE;
    }
    else
    {
        format_match = TRUE;
    }

    // Check to see if we have the frequency we requested.
    if(desired->freq != obtained->freq)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained frequency differs from requested.\n");
        freq_match = FALSE;
    }
    else 
    {
        freq_match = TRUE;
    }

    // Free no longer needed objects used for testing the specifications.
    free(desired);
    free(obtained);

    // Uninitialize SDL audio, as it is no longer needed.
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Quit the Audio and Timer subsystems if they are enabled. (They should be, unless something went horribly wrong.)
    if(SDL_WasInit(SDL_INIT_AUDIO) != 0) SDL_QuitSubSystem(SDL_INIT_AUDIO);
    if(SDL_WasInit(SDL_INIT_TIMER) != 0) SDL_QuitSubSystem(SDL_INIT_TIMER);

    char tMsg[1024];

    if((init_audio == TRUE) && ( init_timer == TRUE ) && ( open_audio_device == TRUE ) && (format_match == TRUE) && (freq_match == TRUE)) 
    {
        sprintf(tMsg,"[JttL's SDL Audio plugin] Audio test successful.");
        critical_failure = 0;
    }
    else 
    {
        sprintf(tMsg,"[JttL's SDL Audio plugin] Test Results\n--\n");
        if(init_audio != TRUE)
        {
            sprintf(tMsg, "%sError initalizing SDL Audio:\n - %s\n", tMsg,sdl_error[0]);
        }
        if(init_timer != TRUE)
        {
            sprintf(tMsg, "%sError initalizing SDL Timer:\n - %s\n", tMsg,sdl_error[1]);
        }
        if(open_audio_device != TRUE)
        {
            sprintf(tMsg, "%sError opening audio device:\n - %s\n", tMsg,sdl_error[2]);
        }
        if(format_match != TRUE)
        {
            sprintf(tMsg, "%sUnable to get the requested output audio format.\n", tMsg);
        }
        if(freq_match != TRUE)
        {
            sprintf(tMsg, "%sUnable to get the requested output frequency.\n", tMsg);
        }
        critical_failure = 1;
    }

    display_test(tMsg);
}
Example #30
0
SDL_bool
SDLTest_CommonInit(SDLTest_CommonState * state)
{
    int i, j, m, n, w, h;
    SDL_DisplayMode fullscreen_mode;

    if (state->flags & SDL_INIT_VIDEO) {
        if (state->verbose & VERBOSE_VIDEO) {
            n = SDL_GetNumVideoDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in video drivers\n");
            } else {
                fprintf(stderr, "Built-in video drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetVideoDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_VideoInit(state->videodriver) < 0) {
            fprintf(stderr, "Couldn't initialize video driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Video driver: %s\n",
                    SDL_GetCurrentVideoDriver());
        }

        /* Upload GL settings */
        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, state->gl_red_size);
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, state->gl_green_size);
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, state->gl_blue_size);
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, state->gl_alpha_size);
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, state->gl_double_buffer);
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, state->gl_buffer_size);
        SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, state->gl_depth_size);
        SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, state->gl_stencil_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, state->gl_accum_red_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, state->gl_accum_green_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, state->gl_accum_blue_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, state->gl_accum_alpha_size);
        SDL_GL_SetAttribute(SDL_GL_STEREO, state->gl_stereo);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, state->gl_multisamplebuffers);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, state->gl_multisamplesamples);
        if (state->gl_accelerated >= 0) {
            SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL,
                                state->gl_accelerated);
        }
        SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, state->gl_retained_backing);
        if (state->gl_major_version) {
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, state->gl_major_version);
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, state->gl_minor_version);
        }
        if (state->gl_debug) {
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
        }

        if (state->verbose & VERBOSE_MODES) {
            SDL_Rect bounds;
            SDL_DisplayMode mode;
            int bpp;
            Uint32 Rmask, Gmask, Bmask, Amask;

            n = SDL_GetNumVideoDisplays();
            fprintf(stderr, "Number of displays: %d\n", n);
            for (i = 0; i < n; ++i) {
                fprintf(stderr, "Display %d: %s\n", i, SDL_GetDisplayName(i));

                SDL_zero(bounds);
                SDL_GetDisplayBounds(i, &bounds);
                fprintf(stderr, "Bounds: %dx%d at %d,%d\n", bounds.w, bounds.h, bounds.x, bounds.y);

                SDL_GetDesktopDisplayMode(i, &mode);
                SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask,
                                           &Bmask, &Amask);
                fprintf(stderr,
                        "  Current mode: %dx%[email protected]%dHz, %d bits-per-pixel (%s)\n",
                        mode.w, mode.h, mode.refresh_rate, bpp,
                        SDL_GetPixelFormatName(mode.format));
                if (Rmask || Gmask || Bmask) {
                    fprintf(stderr, "      Red Mask   = 0x%.8x\n", Rmask);
                    fprintf(stderr, "      Green Mask = 0x%.8x\n", Gmask);
                    fprintf(stderr, "      Blue Mask  = 0x%.8x\n", Bmask);
                    if (Amask)
                        fprintf(stderr, "      Alpha Mask = 0x%.8x\n", Amask);
                }

                /* Print available fullscreen video modes */
                m = SDL_GetNumDisplayModes(i);
                if (m == 0) {
                    fprintf(stderr, "No available fullscreen video modes\n");
                } else {
                    fprintf(stderr, "  Fullscreen video modes:\n");
                    for (j = 0; j < m; ++j) {
                        SDL_GetDisplayMode(i, j, &mode);
                        SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                                   &Gmask, &Bmask, &Amask);
                        fprintf(stderr,
                                "    Mode %d: %dx%[email protected]%dHz, %d bits-per-pixel (%s)\n",
                                j, mode.w, mode.h, mode.refresh_rate, bpp,
                                SDL_GetPixelFormatName(mode.format));
                        if (Rmask || Gmask || Bmask) {
                            fprintf(stderr, "        Red Mask   = 0x%.8x\n",
                                    Rmask);
                            fprintf(stderr, "        Green Mask = 0x%.8x\n",
                                    Gmask);
                            fprintf(stderr, "        Blue Mask  = 0x%.8x\n",
                                    Bmask);
                            if (Amask)
                                fprintf(stderr,
                                        "        Alpha Mask = 0x%.8x\n",
                                        Amask);
                        }
                    }
                }
            }
        }

        if (state->verbose & VERBOSE_RENDER) {
            SDL_RendererInfo info;

            n = SDL_GetNumRenderDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in render drivers\n");
            } else {
                fprintf(stderr, "Built-in render drivers:\n");
                for (i = 0; i < n; ++i) {
                    SDL_GetRenderDriverInfo(i, &info);
                    SDLTest_PrintRenderer(&info);
                }
            }
        }

        SDL_zero(fullscreen_mode);
        switch (state->depth) {
        case 8:
            fullscreen_mode.format = SDL_PIXELFORMAT_INDEX8;
            break;
        case 15:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB555;
            break;
        case 16:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB565;
            break;
        case 24:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB24;
            break;
        default:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB888;
            break;
        }
        fullscreen_mode.refresh_rate = state->refresh_rate;

        state->windows =
            (SDL_Window **) SDL_malloc(state->num_windows *
                                        sizeof(*state->windows));
        state->renderers =
            (SDL_Renderer **) SDL_malloc(state->num_windows *
                                        sizeof(*state->renderers));
        if (!state->windows || !state->renderers) {
            fprintf(stderr, "Out of memory!\n");
            return SDL_FALSE;
        }
        for (i = 0; i < state->num_windows; ++i) {
            char title[1024];

            if (state->num_windows > 1) {
                SDL_snprintf(title, SDL_arraysize(title), "%s %d",
                             state->window_title, i + 1);
            } else {
                SDL_strlcpy(title, state->window_title, SDL_arraysize(title));
            }
            state->windows[i] =
                SDL_CreateWindow(title, state->window_x, state->window_y,
                                 state->window_w, state->window_h,
                                 state->window_flags);
            if (!state->windows[i]) {
                fprintf(stderr, "Couldn't create window: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }
            if (state->window_minW || state->window_minH) {
                SDL_SetWindowMinimumSize(state->windows[i], state->window_minW, state->window_minH);
            }
            if (state->window_maxW || state->window_maxH) {
                SDL_SetWindowMaximumSize(state->windows[i], state->window_maxW, state->window_maxH);
            }
            SDL_GetWindowSize(state->windows[i], &w, &h);
            if (!(state->window_flags & SDL_WINDOW_RESIZABLE) &&
                (w != state->window_w || h != state->window_h)) {
                printf("Window requested size %dx%d, got %dx%d\n", state->window_w, state->window_h, w, h);
                state->window_w = w;
                state->window_h = h;
            }
            if (SDL_SetWindowDisplayMode(state->windows[i], &fullscreen_mode) < 0) {
                fprintf(stderr, "Can't set up fullscreen display mode: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }

            if (state->window_icon) {
                SDL_Surface *icon = SDLTest_LoadIcon(state->window_icon);
                if (icon) {
                    SDL_SetWindowIcon(state->windows[i], icon);
                    SDL_FreeSurface(icon);
                }
            }

            SDL_ShowWindow(state->windows[i]);

            state->renderers[i] = NULL;

            if (!state->skip_renderer
                && (state->renderdriver
                    || !(state->window_flags & SDL_WINDOW_OPENGL))) {
                m = -1;
                if (state->renderdriver) {
                    SDL_RendererInfo info;
                    n = SDL_GetNumRenderDrivers();
                    for (j = 0; j < n; ++j) {
                        SDL_GetRenderDriverInfo(j, &info);
                        if (SDL_strcasecmp(info.name, state->renderdriver) ==
                            0) {
                            m = j;
                            break;
                        }
                    }
                    if (m == n) {
                        fprintf(stderr,
                                "Couldn't find render driver named %s",
                                state->renderdriver);
                        return SDL_FALSE;
                    }
                }
                state->renderers[i] = SDL_CreateRenderer(state->windows[i],
                                            m, state->render_flags);
                if (!state->renderers[i]) {
                    fprintf(stderr, "Couldn't create renderer: %s\n",
                            SDL_GetError());
                    return SDL_FALSE;
                }
                if (state->logical_w && state->logical_h) {
                    SDL_RenderSetLogicalSize(state->renderers[i], state->logical_w, state->logical_h);
                } else if (state->scale) {
                    SDL_RenderSetScale(state->renderers[i], state->scale, state->scale);
                }
                if (state->verbose & VERBOSE_RENDER) {
                    SDL_RendererInfo info;

                    fprintf(stderr, "Current renderer:\n");
                    SDL_GetRendererInfo(state->renderers[i], &info);
                    SDLTest_PrintRenderer(&info);
                }
            }
        }
    }

    if (state->flags & SDL_INIT_AUDIO) {
        if (state->verbose & VERBOSE_AUDIO) {
            n = SDL_GetNumAudioDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in audio drivers\n");
            } else {
                fprintf(stderr, "Built-in audio drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetAudioDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_AudioInit(state->audiodriver) < 0) {
            fprintf(stderr, "Couldn't initialize audio driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Audio driver: %s\n",
                    SDL_GetCurrentAudioDriver());
        }

        if (SDL_OpenAudio(&state->audiospec, NULL) < 0) {
            fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
            return SDL_FALSE;
        }
    }

    return SDL_TRUE;
}