Beispiel #1
0
// resume playing, after audio_pause()
static void audio_resume(void)
{
	//printf("SDL: audio_resume called!\n");	
	SDL_PauseAudio(0);
}
Beispiel #2
0
void sandbox_sdl_audio_stop(void)
{
	if(SDL_GetAudioStatus() != SDL_AUDIO_PAUSED)
		SDL_PauseAudio(1);
}
Beispiel #3
0
// resumes playing a previously paused sound
void CSound::resumeSounds()
{
	SDL_PauseAudio(0);
}
Beispiel #4
0
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, NULL, NULL );
		s_sdlSpeed		= Cvar_Get( "s_sdlSpeed",		"0",	CVAR_ARCHIVE, NULL, NULL );
		s_sdlChannels	= Cvar_Get( "s_sdlChannels",	"2",	CVAR_ARCHIVE, NULL, NULL );
		s_sdlDevSamps	= Cvar_Get( "s_sdlDevSamps",	"0",	CVAR_ARCHIVE, NULL, NULL );
		s_sdlMixSamps	= Cvar_Get( "s_sdlMixSamps",	"0",	CVAR_ARCHIVE, NULL, NULL );
	}

	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 = 22050;
	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 = (Uint16)s_sdlDevSamps->integer;
	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->integer;
	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;
}
Beispiel #5
0
int stream_component_open(VideoState *is, int stream_index) {

    AVFormatContext *pFormatCtx = is->pFormatCtx;
    AVCodecContext *codecCtx    = NULL;
    AVCodec *codec              = NULL;
    AVDictionary *optionsDict   = NULL;
    SDL_AudioSpec wanted_spec, spec;

    if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) {
        return -1;
    }

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

    if(codecCtx->codec_type == AVMEDIA_TYPE_AUDIO) {
        // Set audio settings from codec info
        wanted_spec.freq     = codecCtx->sample_rate;
        wanted_spec.format   = AUDIO_S16SYS;
        wanted_spec.channels = codecCtx->channels;
        wanted_spec.silence  = 0;
        wanted_spec.samples  = SDL_AUDIO_BUFFER_SIZE;
        wanted_spec.callback = audio_callback;
        wanted_spec.userdata = is;

        if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
            fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
            return -1;
        }
        is->audio_hw_buf_size = spec.size;
    }

    codec = avcodec_find_decoder(codecCtx->codec_id);
    if(!codec || (avcodec_open2(codecCtx, codec, &optionsDict) < 0)) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1;
    }

    switch(codecCtx->codec_type) {
    case AVMEDIA_TYPE_AUDIO:
        is->audioStream     = stream_index;
        is->audio_st        = pFormatCtx->streams[stream_index];
        is->audio_buf_size  = 0;
        is->audio_buf_index = 0;

        /* averaging filter for audio sync */
        is->audio_diff_avg_coef = exp(log(0.01 / AUDIO_DIFF_AVG_NB));
        is->audio_diff_avg_count = 0;
        /* Correct audio only if larger error than this */
        is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / codecCtx->sample_rate;

        memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
        packet_queue_init(&is->audioq);
        SDL_PauseAudio(0);
        break;

    case AVMEDIA_TYPE_VIDEO:
        is->videoStream            = stream_index;
        is->video_st               = pFormatCtx->streams[stream_index];
        is->frame_timer            = (double)av_gettime() / 1000000.0;
        is->frame_last_delay       = 40e-3;
        is->video_current_pts_time = av_gettime();

        packet_queue_init(&is->videoq);
        is->video_tid = SDL_CreateThread(video_thread, is);
        is->sws_ctx =
            sws_getContext
            (
             is->video_st->codec->width,
             is->video_st->codec->height,
             is->video_st->codec->pix_fmt,
             is->video_st->codec->width,
             is->video_st->codec->height,
             PIX_FMT_YUV420P, 
             SWS_BILINEAR, 
             NULL, 
             NULL, 
             NULL
             );
        codecCtx->get_buffer = our_get_buffer;
        codecCtx->release_buffer = our_release_buffer;
        break;

    default:
        break;
    }

    return 0;
}
Beispiel #6
0
void hw_enable_audio(int enable)
{
    SDL_PauseAudio(!enable);
    g_audioenable = enable;
}
Beispiel #7
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);
}
Beispiel #8
0
void audio_close(void)
{
    SDL_DestroyMutex(g_audio_mutex);
    SDL_PauseAudio(true);
    SDL_CloseAudio();
}
Beispiel #9
0
int stream_component_open(VideoState *is, int stream_index) {

  AVFormatContext *pFormatCtx = is->pFormatCtx;
  AVCodecContext *codecCtx;
  AVCodec *codec;
  SDL_AudioSpec wanted_spec, spec;

  if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) {
    return -1;
  }

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

  if(codecCtx->codec_type == AVMEDIA_TYPE_AUDIO) {
    // Set audio settings from codec info
    wanted_spec.freq = codecCtx->sample_rate;
    wanted_spec.format = AUDIO_S16SYS;
    wanted_spec.channels = codecCtx->channels;
    wanted_spec.silence = 0;
    wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
    wanted_spec.callback = audio_callback;
    wanted_spec.userdata = is;
    
    if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
      fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
      return -1;
    }
  }
  codec = avcodec_find_decoder(codecCtx->codec_id);
  if(!codec || (avcodec_open(codecCtx, codec) < 0)) {
    fprintf(stderr, "Unsupported codec!\n");
    return -1;
  }

  switch(codecCtx->codec_type) {
  case AVMEDIA_TYPE_AUDIO:
    is->audioStream = stream_index;
    is->audio_st = pFormatCtx->streams[stream_index];
    is->audio_buf_size = 0;
    is->audio_buf_index = 0;
    memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
    packet_queue_init(&is->audioq);
    SDL_PauseAudio(0);
    break;
  case AVMEDIA_TYPE_VIDEO:
    is->videoStream = stream_index;
    is->video_st = pFormatCtx->streams[stream_index];
    
    packet_queue_init(&is->videoq);
    is->video_tid = SDL_CreateThread(video_thread, is);

// Create software scaler context for converting to uncompressed imagery.
		is->decodeCtx_ = sws_getContext(is->video_st->codec->width, is->video_st->codec->height, is->video_st->codec->pix_fmt, 
										is->video_st->codec->width, is->video_st->codec->height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
		if (is->decodeCtx_ == NULL)
			printf("Cannot initialize image decompression context for image.");

    break;
  default:
    break;
  }
}
Beispiel #10
0
int main(int argc, char *argv[] )
{
	char msg[1024];
	FILE *cartfile;


    /* Information about the current video settings. */
    const SDL_VideoInfo* info = NULL;

	// get defaults and parse command-line params
	if (osint_defaults ()) {
		return 1;
	}

	osint_parse_cmdline (argc, argv);

	cartfile = fopen (cartname, "rb");

	if (cartfile != NULL) {
		fread (cart, 1, sizeof (cart), cartfile);
		fclose (cartfile);
	} else {
		sprintf (msg, "cannot open '%s'", cartname);
		fprintf(stderr, msg);
	}

    // Initialize SDL's video subsystem
	info = init_sdl();
    //setup_opengl( width, height );

	/* determine a set of colors to use based */
	osint_gencolors ();

#ifdef ENABLE_OVERLAY
	// Load overlay if neccessary (TGA 24-bit uncompressed)
	g_overlay.width = 0;
	if (overlayname)
		load_overlay(overlayname);
#endif

	// set up audio buffering
	reqSpec.freq = 22050;						// 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 = 441;						// Audio buffer size in samples
	reqSpec.callback = fillsoundbuffer;			// Callback function for filling the audio buffer
	reqSpec.userdata = NULL;
	usedSpec = &givenSpec;
	/* Open the audio device */
	if ( SDL_OpenAudio(&reqSpec, usedSpec) < 0 ){
	  fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
	  exit(-1);
	}

	if(usedSpec == NULL)
		usedSpec = &reqSpec;

	// Start playing audio
	SDL_PauseAudio(0);

	/* message loop handler and emulator code */

	osint_emuloop ();

    /*
     * Quit SDL so we can release the fullscreen
     * mode and restore the previous video settings,
     * etc.
     */
    SDL_Quit( );

    /* Exit program. */
    exit( 0 );

	return 0;
// END OF MAIN!!!

}
/* 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 = (_Mix_Channel *) SDL_malloc(num_channels * sizeof(_Mix_Channel));

	/* Clear out the audio channels */
	for ( i=0; i<num_channels; ++i ) {
		_Mix_InitChannel(i);
	}

	mix_music_compat_channel = mix_channel[0];
	mix_music_compat_channel.sound = NULL;
	mix_music_compat_channel.is_music = SDL_TRUE;
	mix_music_compat_channel.playing = 0;

    _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
#if defined(MP3_MUSIC) || defined(MP3_MAD_MUSIC)
    add_chunk_decoder("MP3");
#endif

    audio_opened = 1;
    SDL_PauseAudio(0);
    return(0);
}
Beispiel #12
0
void osint_emuloop (void)
{
	int frames, running;
    double t, t0, t1, fps;
    char    titlestr[ 200 ];
    SDL_Event event;
	
	// reset the vectrex hardware
	vecx_reset ();

    frames = 0;
	running = 1;
	t0 = SDL_GetTicks();
	t1 = t0;
	while (running) {

	    // Grab all the events off the queue. 
	    while( SDL_PollEvent( &event ) ) {
		   switch( event.type ) {
			case SDL_KEYDOWN:
				// Handle key presses
				switch(event.key.keysym.sym) {
					case SDLK_LEFT :
						alg_jch0 = 0x00;
						break;
					case SDLK_RIGHT :
						alg_jch0 = 0xFF;
						break;
					case SDLK_UP :
						alg_jch1 = 0xFF;
						break;
					case SDLK_DOWN :
						alg_jch1 = 0x00;
						break;
					case SDLK_a :
						snd_regs[14] &= ~0x01;
						break;
					case SDLK_s :
						snd_regs[14] &= ~0x02;
						break;
					case SDLK_d:
						snd_regs[14] &= ~0x04;
						break;
					case SDLK_f :
						snd_regs[14] &= ~0x08;
						break;
					case SDLK_p :					// pause
					case SDLK_SPACE :
						if(1 == running) {
							running = 2;		// 2 = "pause state"
							SDL_PauseAudio(1);
						}
						else {
							running = 1;
							SDL_PauseAudio(0);
						}
						break;
					case SDLK_w :					// toggle sound debug on/off
						if(AY_debug) AY_debug = 0;
						else AY_debug = 1;
						break;
					case SDLK_q :					// quit
					case SDLK_ESCAPE :
						running = 0;
						break;
				} // end switch keydown
				break;
			case SDL_KEYUP:
				// Handle key releases
				switch(event.key.keysym.sym) {
					case SDLK_LEFT :
						alg_jch0 = 0x80;
						break;
					case SDLK_RIGHT :
						alg_jch0 = 0x80;
						break;
					case SDLK_UP :
						alg_jch1 = 0x80;
						break;
					case SDLK_DOWN :
						alg_jch1 = 0x80;
						break;
					case SDLK_a :
						snd_regs[14] |= 0x01;
						break;
					case SDLK_s :
						snd_regs[14] |= 0x02;
						break;
					case SDLK_d:
						snd_regs[14] |= 0x04;
						break;
					case SDLK_f :
						snd_regs[14] |= 0x08;
						break;
				} //end switch keyup
				break;
			case SDL_QUIT:
				/* Handle quit requests (like Ctrl-c). */
				running = 0;
				break;
			} // end outer switch

		} // wend events

        // Calculate and display Window caption info
		if(2 == running) {
			SDL_WM_SetCaption("VecX/SDL/GL (PAUSED)", NULL);
		}
		else {
			// Get time
			t = SDL_GetTicks();
			if(AY_debug) {
				// update AY debug info 10x a second
				if( (t-t1) >= 100)
				{
					fps = (double)frames;
					sprintf(titlestr, "F: %04d %04d %04d  V: %02d %02d %02d  TE: %d %d %d",
							AY_spufreq[0], AY_spufreq[1], AY_spufreq[2],
							AY_vol[0], AY_vol[1], AY_vol[2], 
							AY_tone_enable[0], AY_tone_enable[1], AY_tone_enable[2]);
					SDL_WM_SetCaption(titlestr, NULL);
					t1 = t;
					frames = 0;
				}
			}
			else {
				// update fps display once per second
				if( (t-t1) >= 1000)
				{
					fps = (double)frames;
					sprintf( titlestr, "VecX/SDL/GL (%.1f FPS) Drawn: %d ", 
							fps, vector_draw_cnt );
					SDL_WM_SetCaption(titlestr, NULL);
					t1 = t;
					frames = 0;
				}
			}
	        frames ++;
		}

		// emulate this "frame" (if not paused)
		if(1 == running)
			vecx_emu ((VECTREX_MHZ / 1000) * EMU_TIMER, 0);

		// speed control
		while(SDL_GetTicks() < (t0 + EMU_TIMER)) ;
		t0 = SDL_GetTicks();

	} // wend running

printf("Exit emuloop.\n");
}
Beispiel #13
0
int
main(int argc, char *argv[])
{
    int i;
    char filename[4096];

	/* Enable standard application logging */
	SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Load the SDL library */
    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    if (argc >= 1) {
        SDL_strlcpy(filename, argv[1], sizeof(filename));
    } else {
        SDL_strlcpy(filename, "sample.wav", sizeof(filename));
    }
    /* Load the wave file into memory */
    if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "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 */

    /* Show the list of available drivers */
    SDL_Log("Available audio drivers:");
    for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) {
		SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
    }

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

    SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());

    /* Let the audio run */
    SDL_PauseAudio(0);
    while (!done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING))
        SDL_Delay(1000);

    /* Clean up on signal */
    SDL_CloseAudio();
    SDL_FreeWAV(wave.sound);
    SDL_Quit();
    return (0);
}
Beispiel #14
0
Datei: tx.c Projekt: zevv/rgbufo
int main(int argc, char **argv)
{
	SDL_AudioSpec fmt; 

	rb_data = rb_new(256);
	rb_audio = rb_new(48000);

	//int fd = sound_open("/dev/dsp");

	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER);

	fmt.freq = SRATE;
	fmt.format = AUDIO_S16;
	fmt.channels = 1;
	fmt.samples = 256;
	fmt.callback = gen_audio;

	if ( SDL_OpenAudio(&fmt, NULL) < 0 ) {
		fprintf(stderr, "Can't open audio: %s\n", SDL_GetError());
		exit(1);
	}


	SDL_Event ev;
	screen = SDL_SetVideoMode(16, 16, 32, SDL_HWSURFACE | SDL_RESIZABLE) ;
	screen = SDL_SetVideoMode(16, 16, 32, SDL_HWSURFACE | SDL_RESIZABLE) ;
	draw();

	SDL_PauseAudio(0);

	for(;;) {

		while(SDL_WaitEvent(&ev)) {

			if(ev.type == SDL_KEYDOWN) {

				switch(ev.key.keysym.sym) {
					case 27:
						exit(0);
						break;
					default:
						{
							char buf[16];
							snprintf(buf, sizeof buf, "d%c\n", ev.key.keysym.sym);
							send(buf, strlen(buf));
						}
						break;
				}
			}

			if(ev.type == SDL_MOUSEBUTTONDOWN) {
				update_color();
				run = 1;
			}

			if(ev.type == SDL_VIDEORESIZE) {
				screen = SDL_SetVideoMode(ev.resize.w, ev.resize.h, 32, SDL_HWSURFACE | SDL_RESIZABLE) ;
				draw();
				update_color();
			}

			if(ev.type == SDL_MOUSEMOTION) {
				run = 0;
				mx = ev.motion.x;
				my = ev.motion.y;
				update_color();
			}
		}
	}

	return 0;
}
/**
 * Setup SDL audio, video and window subsystems.
 */
void
av_setup(void)
{
	unsigned video_flags = SDL_SWSURFACE;

#ifndef CONFIG_MACOSX
	char *icon_path = NULL;
#endif

	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
	{
		CRITICAL2("SDL_Init error: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	atexit(SDL_Quit);

	if (options.want_audio)
	{
#ifdef CONFIG_WIN32
		/*
		 * default direct-audio-something has got unreasonably long audio buffers,
		 * but if user knows what he's doing then no problemo...
		 */
		if (!SDL_getenv("SDL_AUDIODRIVER"))
		{
			INFO1("fixing WIN32 audio driver setup");
			SDL_putenv("SDL_AUDIODRIVER=waveout");
		}
		/*
		 * also some sources mention that on win audio needs to be initialised
		 * together with video. Maybe, it works for me as it is now.
		 */
#endif
		if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
		{
			ERROR2("audio initialization failed: %s", SDL_GetError());
		}
		else
		{
			INFO1("audio subsystem initialized");
			have_audio = 1;
		}
	}
	else
		NOTICE1("no audio");

	if (options.want_fullscreen)
	{
		video_flags |= SDL_FULLSCREEN;
		NOTICE1("fullscreen mode enabled");
	}

#ifndef CONFIG_MACOSX
	if ((icon_path = locate_file("moon_32x32.bmp", FT_IMAGE)))
	{
		SDL_Surface *icon = SDL_LoadBMP(icon_path);

		if (icon != NULL)
			SDL_WM_SetIcon(icon, NULL);
		else
			INFO2("setting icon failed: %s\n", SDL_GetError());
		free(icon_path);
	}
#endif

#ifdef PACKAGE_BUILD
	SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION
			" build " PACKAGE_BUILD, NULL);
#else
	SDL_WM_SetCaption(PACKAGE_STRING, NULL);
#endif

	if ((display = SDL_SetVideoMode(MAX_X * 2, MAX_Y * 2, 24, video_flags))
			== NULL)
	{
		CRITICAL2("SDL_SetVideoMode failed: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	screen = xcalloc(MAX_X * MAX_Y, 1);
	screen_surf = SDL_CreateRGBSurfaceFrom(screen, MAX_X, MAX_Y, 8, MAX_X,
			0, 0, 0, 0);
	if (!screen_surf)
	{
		CRITICAL2("can't create screen surface: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	screen_surf2x = SDL_CreateRGBSurface(SDL_SWSURFACE, MAX_X * 2, MAX_Y * 2,
			8, ~0, ~0, ~0, 0);
	if (!screen_surf2x)
	{
		CRITICAL2("can't create screen_2x surface: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* XXX: Hardcoded video width & height */
	video_overlay = SDL_CreateYUVOverlay(160, 100, SDL_YV12_OVERLAY, display);
	if (!video_overlay)
	{
		CRITICAL2("can't create video_overlay: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	news_overlay = SDL_CreateYUVOverlay(312, 106, SDL_YV12_OVERLAY, display);
	/* XXX: Hardcoded video width & height */
	if (!news_overlay)
	{
		CRITICAL2("can't create news_overlay: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	fade_info.step = 1;
	fade_info.steps = 1;
	do_fading = 1;

	alloc_dirty_tree();

	SDL_EnableUNICODE(1);
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,
		SDL_DEFAULT_REPEAT_INTERVAL);

	if (have_audio)
	{
		int i = 0;

		audio_desired.freq = 11025;
		audio_desired.format = AUDIO_S16SYS;
		audio_desired.channels = 1;
		/* audio was unresponsive on win32 so let's use shorter buffer */
		audio_desired.samples = 2048;	/* was 8192 */
		audio_desired.callback = audio_callback;

		/* initialize audio channels */
		for (i = 0; i < AV_NUM_CHANNELS; ++i)
		{
			Channels[i].volume = AV_MAX_VOLUME;
			Channels[i].mute = 0;
			Channels[i].chunk = NULL;
			Channels[i].chunk_tailp = &Channels[i].chunk;
			Channels[i].offset = 0;
		}

		/* we don't care what we got, library will convert for us */
		if (SDL_OpenAudio(&audio_desired, NULL) < 0)
		{
			ERROR2("SDL_OpenAudio error: %s", SDL_GetError());
			NOTICE1("disabling audio");
			have_audio = 0;
		}
		else
			SDL_PauseAudio(0);
	}

	SDL_AddTimer(30, sdl_timer_callback, NULL);
}
Beispiel #16
0
void sound_sdl::update_audio_stream(bool is_throttled, const INT16 *buffer, int samples_this_frame)
{
	// if nothing to do, don't do it
	if (sample_rate() != 0 && stream_buffer)
	{
		int bytes_this_frame = samples_this_frame * sizeof(INT16) * 2;
		int play_position, write_position, stream_in;
		int orig_write; // used in LOG

		play_position = stream_playpos;

		write_position = stream_playpos + ((sample_rate() / 50) * sizeof(INT16) * 2);
		orig_write = write_position;

		if (!stream_in_initialized)
		{
			stream_in = stream_buffer_in = (write_position + stream_buffer_size) / 2;

			if (LOG_SOUND)
			{
				fprintf(sound_log, "stream_in = %d\n", (int)stream_in);
				fprintf(sound_log, "stream_playpos = %d\n", (int)stream_playpos);
				fprintf(sound_log, "write_position = %d\n", (int)write_position);
			}
			// start playing
			SDL_PauseAudio(0);

			stream_in_initialized = 1;
		}
		else
		{
			// normalize the stream in position
			stream_in = stream_buffer_in;
			if (stream_in < write_position && stream_loop == 1)
				stream_in += stream_buffer_size;

			// now we should have, in order:
			//    <------pp---wp---si--------------->

			// if we're between play and write positions, then bump forward, but only in full chunks
			while (stream_in < write_position)
			{
				if (LOG_SOUND)
					fprintf(sound_log, "Underflow: PP=%d  WP=%d(%d)  SI=%d(%d)  BTF=%d\n", (int)play_position, (int)write_position, (int)orig_write, (int)stream_in, (int)stream_buffer_in, (int)bytes_this_frame);

				buffer_underflows++;
				stream_in += bytes_this_frame;
			}

			// if we're going to overlap the play position, just skip this chunk
			if (stream_in + bytes_this_frame > play_position + stream_buffer_size)
			{
				if (LOG_SOUND)
					fprintf(sound_log, "Overflow: PP=%d  WP=%d(%d)  SI=%d(%d)  BTF=%d\n", (int)play_position, (int)write_position, (int)orig_write, (int)stream_in, (int)stream_buffer_in, (int)bytes_this_frame);

				buffer_overflows++;
				return;
			}
		}

		if (stream_in >= stream_buffer_size)
		{
			stream_in -= stream_buffer_size;
			stream_loop = 1;

			if (LOG_SOUND)
				fprintf(sound_log, "stream_loop set to 1 (stream_in looped)\n");

		}

		// now we know where to copy; let's do it
		stream_buffer_in = stream_in;
		copy_sample_data(is_throttled, buffer, bytes_this_frame);
	}
}
static void sound_start()
{
	SDL_PauseAudio( false );
}
Beispiel #18
0
int
main(int argc, char *argv[])
{
    int i;
    char filename[4096];

	/* Enable standard application logging */
	SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Load the SDL library */
    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    if (argc > 1) {
        SDL_strlcpy(filename, argv[1], sizeof(filename));
    } else {
        SDL_strlcpy(filename, "sample.wav", sizeof(filename));
    }
    /* Load the wave file into memory */
    if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
        quit(1);
    }

    wave.spec.callback = NULL;  /* we'll push audio. */

#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) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
        SDL_FreeWAV(wave.sound);
        quit(2);
    }

    /*static x[99999]; SDL_QueueAudio(1, x, sizeof (x));*/

    /* Let the audio run */
    SDL_PauseAudio(0);

    /* Note that we stuff the entire audio buffer into the queue in one
       shot. Most apps would want to feed it a little at a time, as it
       plays, but we're going for simplicity here. */
    
    while (!done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING))
    {
        /* The device from SDL_OpenAudio() is always device #1. */
        const Uint32 queued = SDL_GetQueuedAudioSize(1);
        SDL_Log("Device has %u bytes queued.\n", (unsigned int) queued);
        if (queued <= 8192) {  /* time to requeue the whole thing? */
            if (SDL_QueueAudio(1, wave.sound, wave.soundlen) == 0) {
                SDL_Log("Device queued %u more bytes.\n", (unsigned int) wave.soundlen);
            } else {
                SDL_Log("Device FAILED to queue %u more bytes: %s\n", (unsigned int) wave.soundlen, SDL_GetError());
            }
        }

        SDL_Delay(100);  /* let it play for awhile. */
    }

    /* Clean up on signal */
    SDL_CloseAudio();
    SDL_FreeWAV(wave.sound);
    SDL_Quit();
    return 0;
}
Beispiel #19
0
static boolean I_SDL_InitSound(boolean _use_sfx_prefix)
{
    int i;

    use_sfx_prefix = _use_sfx_prefix;

    // No sounds yet

    for (i=0; i<NUM_CHANNELS; ++i)
    {
        channels_playing[i] = NULL;
    }

    if (SDL_Init(SDL_INIT_AUDIO) < 0)
    {
        fprintf(stderr, "Unable to set up sound.\n");
        return false;
    }

    if (Mix_OpenAudio(snd_samplerate, AUDIO_S16SYS, 2, GetSliceSize()) < 0)
    {
        fprintf(stderr, "Error initialising SDL_mixer: %s\n", Mix_GetError());
        return false;
    }

    ExpandSoundData = ExpandSoundData_SDL;

    Mix_QuerySpec(&mixer_freq, &mixer_format, &mixer_channels);

#ifdef HAVE_LIBSAMPLERATE
    if (use_libsamplerate != 0)
    {
        if (SRC_ConversionMode() < 0)
        {
            I_Error("I_SDL_InitSound: Invalid value for use_libsamplerate: %i",
                    use_libsamplerate);
        }

        ExpandSoundData = ExpandSoundData_SRC;
    }
#else
    if (use_libsamplerate != 0)
    {
        fprintf(stderr, "I_SDL_InitSound: use_libsamplerate=%i, but "
                        "libsamplerate support not compiled in.\n",
                        use_libsamplerate);
    }
#endif

    // SDL_mixer version 1.2.8 and earlier has a bug in the Mix_SetPanning
    // function that can cause the game to lock up.  If we're using an old
    // version, we need to apply a workaround.  But the workaround has its
    // own drawbacks ...

    {
        const SDL_version *mixer_version;
        int v;

        mixer_version = Mix_Linked_Version();
        v = SDL_VERSIONNUM(mixer_version->major,
                           mixer_version->minor,
                           mixer_version->patch);

        if (v <= SDL_VERSIONNUM(1, 2, 8))
        {
            setpanning_workaround = true;
            fprintf(stderr, "\n"
              "ATTENTION: You are using an old version of SDL_mixer!\n"
              "           This version has a bug that may cause "
                          "your sound to stutter.\n"
              "           Please upgrade to a newer version!\n"
              "\n");
        }
    }

    Mix_AllocateChannels(NUM_CHANNELS);

    SDL_PauseAudio(0);

    sound_initialized = true;

    return true;
}
Beispiel #20
0
static void audio_loop(t_mdxmini *data, int freq, int len)
{
    
	int total;
	int sec;
	int sec_sample;

    if (len < 0)
        len = mdx_get_length(data);

	mdx_set_max_loop(data, 0);
    
	fade_init();
	
	total = sec = sec_sample = 0;

    // put title info
    audio_disp_title(data);
    
    // put time
    audio_info(data, sec, len);

	do
	{
		// waiting for next block
        while(pcm.count >=  (PCM_BUFFER_LEN - PCM_BLOCK_SIZE))
        {
            if (audio_poll_event() < 0)
            {
                SDL_PauseAudio(1);
                return;
            }
            SDL_Delay(1);
        }
		
        // calculate samples
	mdx_calc_sample(data, pcm.buffer + pcm.write_pos, PCM_BLOCK);
		if (is_fade_run())
			fade_stereo (pcm.buffer + pcm.write_pos, PCM_BLOCK);
		
		pcm.write_pos += PCM_BLOCK_SIZE;
		if (pcm.write_pos >= PCM_BUFFER_LEN)
				pcm.write_pos = 0;
        
        pcm.count += PCM_BLOCK_SIZE;
		
		total += PCM_BLOCK;
		sec_sample += PCM_BLOCK;
        
        // if sec_samples > 1sec
		while (sec_sample >= freq)
		{
			sec_sample -= freq;
			sec++;
            
            if (sec >= (len - 3))
			{
				if (!is_fade_run())
					fade_start(freq, 1);
			}
            if (!g_viewnote)
                audio_info(data, sec, len);
            
		}
        
		if (g_viewnote)
            audio_info(data, sec, len);

	}while(sec < len && !pcm.stop);
    
    printf("\n");
	
	SDL_PauseAudio(1);
}
Beispiel #21
0
int main(int argc, char** argv) {
	SDL_ffmpegFile* film;
	int s;
	SDL_ffmpegStream *str;
	SDL_AudioSpec *specs;
	int w,h;
	int done = 0;
	SDL_Surface *screen;

	/* check if we got an argument */
	if(argc < 2) {
		printf("usage: \"%s\" \"filename\"\n", argv[0]);
		return -1;
	}
	/* standard SDL initialization stuff */
	if(SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO|SDL_DOUBLEBUF) < 0) {
		fprintf(stderr, "problem initializing SDL: %s\n", SDL_GetError());
		return -1;
	}

	/* open file from arg[1] */
	film = SDL_ffmpegOpen(argv[1]);
	if(!film) {
		printf("error opening file\n");
		return -1;
	}

	/* print some info on detected stream to output */

	for(s = 0; s<film->AStreams; s++) {
		str = SDL_ffmpegGetAudioStream(film, s);

		printf("Info on audiostream #%i:\n", s);
		printf("\tChannels: %i\n",      str->channels);
		if(strlen(str->language)) printf("\tLanguage: %s\n",      str->language);
		printf("\tSampleRate: %i\n",    str->sampleRate);
	}

	for(s = 0; s<film->VStreams; s++) {
		str = SDL_ffmpegGetVideoStream(film, s);

		printf("Info on videostream #%i:\n", s);
		if(strlen(str->language)) printf("\tLanguage: %s\n",      str->language);
		printf("\tFrame: %ix%i\n",  str->width, str->height);
		printf("\tFrameRate: %.2ffps\n",  1.0 / (str->frameRate[0] / str->frameRate[1]));
	}

	/* select the streams you want to decode (example just uses 0 as a default) */
	SDL_ffmpegSelectVideoStream(film, 0);
	SDL_ffmpegSelectAudioStream(film, 0);

	/* get the audiospec which fits the selected videostream, if no videostream */
	/* is selected, default values are used (2 channel, 48Khz) */
	specs = SDL_ffmpegGetAudioSpec(film, 512, audioCallback);

	/* we get the size from our active video stream, if no active video stream */
	/* exists, width and height are set to default values (320x240) */
	SDL_ffmpegGetVideoSize(film, &w, &h);

	/* Open the Video device */
	screen = SDL_SetVideoMode(w, h, 32, SDL_DOUBLEBUF|SDL_HWSURFACE);
	if(!screen) {
		printf("Couldn't open video: %s\n", SDL_GetError());
		return -1;
	}

	/* Open the Audio device */
	if( SDL_OpenAudio(specs, 0) < 0 ) {
		printf("Couldn't open audio: %s\n", SDL_GetError());
		return -1;
	}

	/* we start our decode thread, this always tries to buffer in some frames */
	/* so we can enjoy smooth playback */
	SDL_ffmpegStartDecoding(film);

	/* we unpause the audio so our audiobuffer gets read */
	SDL_PauseAudio(0);


	while( !done ) {
		SDL_ffmpegVideoFrame* frame;

		/* just some standard SDL event stuff */
		SDL_Event event;
		while(SDL_PollEvent(&event)) {

			if(event.type == SDL_QUIT) {
				done = 1;
				break;
			}

			if(event.type == SDL_MOUSEBUTTONDOWN) {
				int x,y;
				int64_t time;
				SDL_PumpEvents();

				SDL_GetMouseState(&x, &y);
				/* by clicking you turn on the stream, seeking to the percentage */
				/* in time, based on the x-position you clicked on */
				time = ((double)x / w) * SDL_ffmpegGetDuration(film);

				/* we seek to time (milliseconds) */
				SDL_ffmpegSeek(film, time);

				/* by passing 0(false) as our second argument, we play the file */
				/* passing a non-zero value would mean we pause our file */
				SDL_ffmpegPause(film, 0);
			}
		}

		/* we retrieve the current image from the file */
		/* we get 0 if no file could be retrieved */
		/* important! please note this call should be paired with SDL_ffmpegReleaseVideo */
		frame = SDL_ffmpegGetVideoFrame(film);

		if(frame) {

			/* we got a frame, so we better show this one */
			SDL_BlitSurface(frame->buffer, 0, screen, 0);

			/* After releasing this frame, you can no longer use it. */
			/* you should call this function every time you get a frame! */
			SDL_ffmpegReleaseVideo(film, frame);

			/* we flip the double buffered screen so we might actually see something */
			SDL_Flip(screen);
		}

		/* we wish not to kill our poor cpu, so we give it some timeoff */
		SDL_Delay(5);
	}

	/* after all is said and done, we should call this */
	SDL_ffmpegFree(film);

	/* the SDL_Quit function offcourse... */
	SDL_Quit();

	return 0;
}
Beispiel #22
0
/**
 * Pause (1) or unpause (0) the audio output.
 */
void SilenceSound(int n)
{
    // Not needed, the callback will write silence to buffer anyway
    // otherwise it causes noticable lag
    SDL_PauseAudio(n);  
}
int
main(int argc, char **argv)
{
	char *file = NULL;
	int have_video = 0, have_audio = 0;
	unsigned h = 0, w = 0;
	float fps = 0.0;
	unsigned ch = 0, hz = 0;
	struct audiobuf abuf;
	int end = 0;
	SDL_Surface *display = NULL;
	SDL_Overlay *ovl = NULL;
	SDL_Event event;
	mm_file media;

	if (argc > 1)
		file = argv[1];
	else
		usage(argv[0]);

	if (mm_open(&media, file) <= 0)
		eprintf("No audio or video in `%s'\n", file);

	if (mm_video_info(&media, &w, &h, &fps) >= 0)
	{
		printf("Video data: %dx%d, %gfps\n", w, h, fps);
		have_video = 1;
	}

	if (mm_audio_info(&media, &ch, &hz) >= 0)
	{
		printf("Audio data: %s, %dHz\n", (ch == 1) ? "mono" : "stereo", hz);
		have_audio = 1;
	}

	if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) < 0)
		eprintf("Sdl init failed: %s\n", SDL_GetError());

	if (have_video)
	{
		if ((display = SDL_SetVideoMode(w, h, 24,
					SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL)
			eprintf("SDL_SetVideoMode: %s\n", SDL_GetError());

		if ((ovl = SDL_CreateYUVOverlay(w, h,
					SDL_YV12_OVERLAY, display)) == NULL)
			eprintf("SDL_CreateYUVOverlay: %s\n", SDL_GetError());
	}

	if (have_audio)
	{
		int bytes;
		int bps;
		double tdiff;
		SDL_AudioSpec desired;

		desired.channels = ch;
		desired.freq = hz;
		desired.format = AUDIO_U8;
		bps = ch * 1;
		desired.samples = 4096;
		desired.callback = audio_cb;
		desired.userdata = &abuf;
		if (SDL_OpenAudio(&desired, NULL) < 0)
			eprintf("SDL_OpenAudio: %s\n", SDL_GetError());

		abuf.size = 4 * 4096;
		abuf.off = 0;
		abuf.bytes = 0;
		abuf.buf = xmalloc(abuf.size);

		tdiff = get_time();
		while ((bytes = mm_decode_audio(&media,
					abuf.buf + abuf.bytes, abuf.size - abuf.bytes)) > 0)
		{
			abuf.bytes += bytes;
			if (abuf.size - abuf.bytes <= 4096)
				abuf.buf = xrealloc(abuf.buf, abuf.size *= 2);
		};
		if (bytes < 0)
			eperror("convert_audio");

		printf("Decoding: %.3f seconds\n", get_time() - tdiff);
		printf("Audio: %d samples, %.2f seconds\n", abuf.bytes / bps,
			(double) (abuf.bytes) / bps / desired.freq);

		SDL_PauseAudio(0);
	}

	while (!end)
	{
		while (SDL_PollEvent(&event))
			switch (event.type)
			{
				case SDL_QUIT:
					end = 1;
					break;
				case SDL_KEYDOWN:
					if (event.key.keysym.sym == SDLK_q
						|| event.key.keysym.sym == SDLK_ESCAPE)
						end = 1;
					break;
				default:
					break;
			}

		if (have_video && !end)
		{
			static double oldt, newt;

			if (mm_decode_video(&media, ovl) > 0)
			{
				SDL_Rect r = { 0, 0, w, h };
				newt = 1 / fps + oldt - get_time();
				if (newt > 0)
					SDL_Delay(newt * 1000);
				SDL_DisplayYUVOverlay(ovl, &r);
				oldt = get_time();
			}
			else
				end = 1;
		}

		if (have_audio && abuf.bytes <= 0)
			end = 1;

		if (!have_video)
			SDL_Delay(100);
	}

	if (have_audio)
	{
		SDL_PauseAudio(1);
		free(abuf.buf);
	}

	if (have_video)
	{
		SDL_FreeYUVOverlay(ovl);
	}

	SDL_Quit();
	mm_close(&media);

	return EXIT_SUCCESS;
}
Beispiel #24
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);
}
Beispiel #25
0
void sandbox_sdl_audio_start(void)
{
	if(SDL_GetAudioStatus() != SDL_AUDIO_PLAYING)
		SDL_PauseAudio(0);
}
Beispiel #26
0
void xsound_play(void) {

	if (sound_opened) {
		SDL_PauseAudio(0);
	}
}
Beispiel #27
0
// pauses any currently playing sounds
void CSound::pauseSound()
{
	SDL_PauseAudio(1);
}
Beispiel #28
0
void xsound_stop(void) {

	if (sound_opened) {
		SDL_PauseAudio(1);
	}
}
Beispiel #29
0
bool CSound::init()
{
	g_pLogFile->ftextOut("Starting the sound driver...<br>");
	SDL_AudioSpec obtained;

	// now start up the SDL sound system
	mAudioSpec.silence = 0;

	switch (mAudioSpec.freq)
	{
		case 11025: mAudioSpec.samples = 256; break;
		case 22050: mAudioSpec.samples = 512; break;
		default: mAudioSpec.samples = 1024; break;
	}
	mAudioSpec.callback = CCallback;
	mAudioSpec.userdata = NULL;

	// Initialize variables
	if( SDL_OpenAudio(&mAudioSpec, &obtained) < 0 )
	{
		g_pLogFile->ftextOut("SoundDrv_Start(): Couldn't open audio: %s<br>", SDL_GetError());
		g_pLogFile->ftextOut("Sound will be disabled.<br>");
		mAudioSpec.channels = 0;
		mAudioSpec.format = 0;
		mAudioSpec.freq = 0;
		return false;
	}

	mAudioSpec = obtained;

	m_MixedForm.reserve(mAudioSpec.size);

	g_pLogFile->ftextOut("SDL_AudioSpec:<br>");
	g_pLogFile->ftextOut("  freq: %d<br>", mAudioSpec.freq);
	g_pLogFile->ftextOut("  channels: %d<br>", mAudioSpec.channels);
	g_pLogFile->ftextOut("  audio buffer size: %d<br>", mAudioSpec.size);
	switch( mAudioSpec.format )
	{
		case AUDIO_U8:
			g_pLogFile->ftextOut("  format: AUDIO_U8<br>" );
			break;
		case AUDIO_S16:
			g_pLogFile->ftextOut("  format: AUDIO_S16<br>" );
			break;
		default:
			g_pLogFile->ftextOut("  format: UNKNOWN %d<br>", mAudioSpec.format );
			break;
	}
#if SDL_VERSION_ATLEAST(2, 0, 0)
    g_pLogFile->ftextOut("Using audio driver: %s<br>", SDL_GetCurrentAudioDriver());
#else
   // g_pLogFile->ftextOut("Using audio driver: %s<br>", SDL_AudioDriverName(name, 32));
#endif

	//m_mixing_channels = 15;
	m_mixing_channels = 32;

	if(!m_soundchannel.empty())
		m_soundchannel.clear();
	m_soundchannel.assign(m_mixing_channels, CSoundChannel(mAudioSpec));

	SDL_PauseAudio(0);

	g_pLogFile->ftextOut("Sound System: SDL sound system initialized.<br>");

	// Let's initialize the OPL Emulator here!
	m_OPL_Player.init();

	return true;
}
Beispiel #30
0
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate,int channels,int format,int flags){

	/* SDL Audio Specifications */
	SDL_AudioSpec aspec, obtained;
	
	/* Allocate ring-buffer memory */
	buffer = (unsigned char *) malloc(BUFFSIZE);

	mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_SDL_INFO, rate, (channels > 1) ? "Stereo" : "Mono", af_fmt2str_short(format));

	if(ao_subdevice) {
		setenv("SDL_AUDIODRIVER", ao_subdevice, 1);
		mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_SDL_DriverInfo, ao_subdevice);
	}

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

	ao_data.bps=channels*rate;
	if(format != AF_FORMAT_U8 && format != AF_FORMAT_S8)
	  ao_data.bps*=2;
	
	/* The desired audio format (see SDL_AudioSpec) */
	switch(format) {
	    case AF_FORMAT_U8:
		aspec.format = AUDIO_U8;
	    break;
	    case AF_FORMAT_S16_LE:
		aspec.format = AUDIO_S16LSB;
	    break;
	    case AF_FORMAT_S16_BE:
		aspec.format = AUDIO_S16MSB;
	    break;
	    case AF_FORMAT_S8:
		aspec.format = AUDIO_S8;
	    break;
	    case AF_FORMAT_U16_LE:
		aspec.format = AUDIO_U16LSB;
	    break;
	    case AF_FORMAT_U16_BE:
		aspec.format = AUDIO_U16MSB;
	    break;
	    default:
                aspec.format = AUDIO_S16LSB;
                ao_data.format = AF_FORMAT_S16_LE;
                mp_msg(MSGT_AO,MSGL_WARN,MSGTR_AO_SDL_UnsupportedAudioFmt, 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*/)) {
                mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_SDL_CantInit, SDL_GetError());
                return 0;
        }

	/* Open the audio device and start playing sound! */
	if(SDL_OpenAudio(&aspec, &obtained) < 0) {
        	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_SDL_CantOpenAudio, SDL_GetError());
        	return(0);
	} 

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

	switch(obtained.format) {
	    case AUDIO_U8 :
		ao_data.format = AF_FORMAT_U8;
	    break;
	    case AUDIO_S16LSB :
		ao_data.format = AF_FORMAT_S16_LE;
	    break;
	    case AUDIO_S16MSB :
		ao_data.format = AF_FORMAT_S16_BE;
	    break;
	    case AUDIO_S8 :
		ao_data.format = AF_FORMAT_S8;
	    break;
	    case AUDIO_U16LSB :
		ao_data.format = AF_FORMAT_U16_LE;
	    break;
	    case AUDIO_U16MSB :
		ao_data.format = AF_FORMAT_U16_BE;
	    break;
	    default:
                mp_msg(MSGT_AO,MSGL_WARN,MSGTR_AO_SDL_UnsupportedAudioFmt, obtained.format);
                return 0;
	}

	mp_msg(MSGT_AO,MSGL_V,"SDL: buf size = %d\n",obtained.size);
	ao_data.buffersize=obtained.size;
	ao_data.outburst = CHUNK_SIZE;
	
	reset();
	/* unsilence audio, if callback is ready */
	SDL_PauseAudio(0);

	return 1;
}