src/audio/dsp/SDL_dspaudio.c
author Sam Lantinga <slouken@lokigames.com>
Sat, 07 Jul 2001 23:27:29 +0000
changeset 93 fc774f445e10
parent 35 d3bc792e136d
child 94 ae6e6b73333f
permissions -rw-r--r--
Applied Hannu's fix and switched to blocking writes .. seems to work?
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997, 1998, 1999, 2000, 2001  Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Library General Public
     7     License as published by the Free Software Foundation; either
     8     version 2 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Library General Public License for more details.
    14 
    15     You should have received a copy of the GNU Library General Public
    16     License along with this library; if not, write to the Free
    17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18 
    19     Sam Lantinga
    20     slouken@devolution.com
    21 */
    22 
    23 #ifdef SAVE_RCSID
    24 static char rcsid =
    25  "@(#) $Id$";
    26 #endif
    27 
    28 /* Allow access to a raw mixing buffer */
    29 
    30 #include <stdlib.h>
    31 #include <stdio.h>
    32 #include <string.h>
    33 #include <errno.h>
    34 #include <unistd.h>
    35 #include <fcntl.h>
    36 #include <signal.h>
    37 #include <sys/time.h>
    38 #include <sys/ioctl.h>
    39 #include <sys/stat.h>
    40 #include <sys/soundcard.h>
    41 
    42 #include "SDL_audio.h"
    43 #include "SDL_error.h"
    44 #include "SDL_audiomem.h"
    45 #include "SDL_audio_c.h"
    46 #include "SDL_timer.h"
    47 #include "SDL_audiodev_c.h"
    48 #include "SDL_dspaudio.h"
    49 
    50 /* The tag name used by DSP audio */
    51 #define DSP_DRIVER_NAME         "dsp"
    52 
    53 /* Open the audio device for playback, and don't block if busy */
    54 #define USE_BLOCKING_WRITES
    55 #ifdef USE_BLOCKING_WRITES
    56 #define OPEN_FLAGS	O_WRONLY
    57 #else
    58 #define OPEN_FLAGS	(O_WRONLY|O_NONBLOCK)
    59 #endif
    60 
    61 /* Audio driver functions */
    62 static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec);
    63 static void DSP_WaitAudio(_THIS);
    64 static void DSP_PlayAudio(_THIS);
    65 static Uint8 *DSP_GetAudioBuf(_THIS);
    66 static void DSP_CloseAudio(_THIS);
    67 
    68 /* Audio driver bootstrap functions */
    69 
    70 static int Audio_Available(void)
    71 {
    72 	int fd;
    73 	int available;
    74 
    75 	available = 0;
    76 	fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0);
    77 	if ( fd >= 0 ) {
    78 		available = 1;
    79 		close(fd);
    80 	}
    81 	return(available);
    82 }
    83 
    84 static void Audio_DeleteDevice(SDL_AudioDevice *device)
    85 {
    86 	free(device->hidden);
    87 	free(device);
    88 }
    89 
    90 static SDL_AudioDevice *Audio_CreateDevice(int devindex)
    91 {
    92 	SDL_AudioDevice *this;
    93 
    94 	/* Initialize all variables that we clean on shutdown */
    95 	this = (SDL_AudioDevice *)malloc(sizeof(SDL_AudioDevice));
    96 	if ( this ) {
    97 		memset(this, 0, (sizeof *this));
    98 		this->hidden = (struct SDL_PrivateAudioData *)
    99 				malloc((sizeof *this->hidden));
   100 	}
   101 	if ( (this == NULL) || (this->hidden == NULL) ) {
   102 		SDL_OutOfMemory();
   103 		if ( this ) {
   104 			free(this);
   105 		}
   106 		return(0);
   107 	}
   108 	memset(this->hidden, 0, (sizeof *this->hidden));
   109 	audio_fd = -1;
   110 
   111 	/* Set the function pointers */
   112 	this->OpenAudio = DSP_OpenAudio;
   113 	this->WaitAudio = DSP_WaitAudio;
   114 	this->PlayAudio = DSP_PlayAudio;
   115 	this->GetAudioBuf = DSP_GetAudioBuf;
   116 	this->CloseAudio = DSP_CloseAudio;
   117 
   118 	this->free = Audio_DeleteDevice;
   119 
   120 	return this;
   121 }
   122 
   123 AudioBootStrap DSP_bootstrap = {
   124 	DSP_DRIVER_NAME, "OSS /dev/dsp standard audio",
   125 	Audio_Available, Audio_CreateDevice
   126 };
   127 
   128 /* This function waits until it is possible to write a full sound buffer */
   129 static void DSP_WaitAudio(_THIS)
   130 {
   131 	/* Check to see if the thread-parent process is still alive */
   132 	{ static int cnt = 0;
   133 		/* Note that this only works with thread implementations 
   134 		   that use a different process id for each thread.
   135 		*/
   136 		if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */
   137 			if ( kill(parent, 0) < 0 ) {
   138 				this->enabled = 0;
   139 			}
   140 		}
   141 	}
   142 
   143 #ifndef USE_BLOCKING_WRITES /* Not necessary when using blocking writes */
   144 	/* See if we need to use timed audio synchronization */
   145 	if ( frame_ticks ) {
   146 		/* Use timer for general audio synchronization */
   147 		Sint32 ticks;
   148 
   149 		ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS;
   150 		if ( ticks > 0 ) {
   151 			SDL_Delay(ticks);
   152 		}
   153 	} else {
   154 		/* Use select() for audio synchronization */
   155 		fd_set fdset;
   156 		struct timeval timeout;
   157 
   158 		FD_ZERO(&fdset);
   159 		FD_SET(audio_fd, &fdset);
   160 		timeout.tv_sec = 10;
   161 		timeout.tv_usec = 0;
   162 #ifdef DEBUG_AUDIO
   163 		fprintf(stderr, "Waiting for audio to get ready\n");
   164 #endif
   165 		if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) {
   166 			const char *message =
   167 			"Audio timeout - buggy audio driver? (disabled)";
   168 			/* In general we should never print to the screen,
   169 			   but in this case we have no other way of letting
   170 			   the user know what happened.
   171 			*/
   172 			fprintf(stderr, "SDL: %s\n", message);
   173 			this->enabled = 0;
   174 			/* Don't try to close - may hang */
   175 			audio_fd = -1;
   176 #ifdef DEBUG_AUDIO
   177 			fprintf(stderr, "Done disabling audio\n");
   178 #endif
   179 		}
   180 #ifdef DEBUG_AUDIO
   181 		fprintf(stderr, "Ready!\n");
   182 #endif
   183 	}
   184 #endif /* !USE_BLOCKING_WRITES */
   185 }
   186 
   187 static void DSP_PlayAudio(_THIS)
   188 {
   189 	int written, p=0;
   190 
   191 	/* Write the audio data, checking for EAGAIN on broken audio drivers */
   192 	do {
   193 		written = write(audio_fd, &mixbuf[p], mixlen-p);
   194 		if (written>0)
   195 		   p += written;
   196 		if (written == -1 && errno != 0 && errno != EAGAIN && errno != EINTR)
   197 		{
   198 		   /* Non recoverable error has occurred. It should be reported!!! */
   199 		   perror("audio");
   200 		   break;
   201 		}
   202 
   203 		if ( p < written || ((written < 0) && ((errno == 0) || (errno == EAGAIN))) ) {
   204 			SDL_Delay(1);	/* Let a little CPU time go by */
   205 		}
   206 	} while ( p < written );
   207 
   208 	/* If timer synchronization is enabled, set the next write frame */
   209 	if ( frame_ticks ) {
   210 		next_frame += frame_ticks;
   211 	}
   212 
   213 	/* If we couldn't write, assume fatal error for now */
   214 	if ( written < 0 ) {
   215 		this->enabled = 0;
   216 	}
   217 #ifdef DEBUG_AUDIO
   218 	fprintf(stderr, "Wrote %d bytes of audio data\n", written);
   219 #endif
   220 }
   221 
   222 static Uint8 *DSP_GetAudioBuf(_THIS)
   223 {
   224 	return(mixbuf);
   225 }
   226 
   227 static void DSP_CloseAudio(_THIS)
   228 {
   229 	if ( mixbuf != NULL ) {
   230 		SDL_FreeAudioMem(mixbuf);
   231 		mixbuf = NULL;
   232 	}
   233 	if ( audio_fd >= 0 ) {
   234 		close(audio_fd);
   235 		audio_fd = -1;
   236 	}
   237 }
   238 
   239 static int DSP_ReopenAudio(_THIS, const char *audiodev, int format,
   240 						SDL_AudioSpec *spec)
   241 {
   242 	int frag_spec;
   243 	int value;
   244 
   245 	/* Close and then reopen the audio device */
   246 	close(audio_fd);
   247 	audio_fd = open(audiodev, O_WRONLY, 0);
   248 	if ( audio_fd < 0 ) {
   249 		SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
   250 		return(-1);
   251 	}
   252 
   253 	/* Calculate the final parameters for this audio specification */
   254 	SDL_CalculateAudioSpec(spec);
   255 
   256 	/* Determine the power of two of the fragment size */
   257 	for ( frag_spec = 0; (0x01<<frag_spec) < spec->size; ++frag_spec );
   258 	if ( (0x01<<frag_spec) != spec->size ) {
   259 		SDL_SetError("Fragment size must be a power of two");
   260 		return(-1);
   261 	}
   262 	frag_spec |= 0x00020000;	/* two fragments, for low latency */
   263 
   264 	/* Set the audio buffering parameters */
   265 #ifdef DEBUG_AUDIO
   266 	fprintf(stderr, "Requesting %d fragments of size %d\n",
   267 		(frag_spec >> 16), 1<<(frag_spec&0xFFFF));
   268 #endif
   269 	if ( ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0 ) {
   270 		fprintf(stderr, "Warning: Couldn't set audio fragment size\n");
   271 	}
   272 #ifdef DEBUG_AUDIO
   273 	{ audio_buf_info info;
   274 	  ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info);
   275 	  fprintf(stderr, "fragments = %d\n", info.fragments);
   276 	  fprintf(stderr, "fragstotal = %d\n", info.fragstotal);
   277 	  fprintf(stderr, "fragsize = %d\n", info.fragsize);
   278 	  fprintf(stderr, "bytes = %d\n", info.bytes);
   279 	}
   280 #endif
   281 
   282 	/* Set the audio format */
   283 	value = format;
   284 	if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) ||
   285 						(value != format) ) {
   286 		SDL_SetError("Couldn't set audio format");
   287 		return(-1);
   288 	}
   289 
   290 	/* Set the number of channels of output */
   291 	value = spec->channels;
   292 #ifdef SNDCTL_DSP_CHANNELS
   293 	if ( ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0 ) {
   294 #endif
   295 		value = (spec->channels > 1);
   296 		ioctl(audio_fd, SNDCTL_DSP_STEREO, &value);
   297 		value = (value ? 2 : 1);
   298 #ifdef SNDCTL_DSP_CHANNELS
   299 	}
   300 #endif
   301 	if ( value != spec->channels ) {
   302 		SDL_SetError("Couldn't set audio channels");
   303 		return(-1);
   304 	}
   305 
   306 	/* Set the DSP frequency */
   307 	value = spec->freq;
   308 	if ( ioctl(audio_fd, SOUND_PCM_WRITE_RATE, &value) < 0 ) {
   309 		SDL_SetError("Couldn't set audio frequency");
   310 		return(-1);
   311 	}
   312 	spec->freq = value;
   313 
   314 	/* We successfully re-opened the audio */
   315 	return(0);
   316 }
   317 
   318 static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec)
   319 {
   320 	char audiodev[1024];
   321 	int format;
   322 	int value;
   323 	Uint16 test_format;
   324 
   325 	/* Reset the timer synchronization flag */
   326 	frame_ticks = 0.0;
   327 
   328 	/* Open the audio device */
   329 	audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
   330 	if ( audio_fd < 0 ) {
   331 		SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
   332 		return(-1);
   333 	}
   334 	mixbuf = NULL;
   335 
   336 	/* Get a list of supported hardware formats */
   337 	if ( ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0 ) {
   338 		SDL_SetError("Couldn't get audio format list");
   339 		return(-1);
   340 	}
   341 
   342 	/* Try for a closest match on audio format */
   343 	format = 0;
   344 	for ( test_format = SDL_FirstAudioFormat(spec->format);
   345 						! format && test_format; ) {
   346 #ifdef DEBUG_AUDIO
   347 		fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
   348 #endif
   349 		switch ( test_format ) {
   350 			case AUDIO_U8:
   351 				if ( value & AFMT_U8 ) {
   352 					format = AFMT_U8;
   353 				}
   354 				break;
   355 			case AUDIO_S8:
   356 				if ( value & AFMT_S8 ) {
   357 					format = AFMT_S8;
   358 				}
   359 				break;
   360 			case AUDIO_S16LSB:
   361 				if ( value & AFMT_S16_LE ) {
   362 					format = AFMT_S16_LE;
   363 				}
   364 				break;
   365 			case AUDIO_S16MSB:
   366 				if ( value & AFMT_S16_BE ) {
   367 					format = AFMT_S16_BE;
   368 				}
   369 				break;
   370 			case AUDIO_U16LSB:
   371 				if ( value & AFMT_U16_LE ) {
   372 					format = AFMT_U16_LE;
   373 				}
   374 				break;
   375 			case AUDIO_U16MSB:
   376 				if ( value & AFMT_U16_BE ) {
   377 					format = AFMT_U16_BE;
   378 				}
   379 				break;
   380 			default:
   381 				break;
   382 		}
   383 		if ( ! format ) {
   384 			test_format = SDL_NextAudioFormat();
   385 		}
   386 	}
   387 	if ( format == 0 ) {
   388 		SDL_SetError("Couldn't find any hardware audio formats");
   389 		return(-1);
   390 	}
   391 	spec->format = test_format;
   392 
   393 	/* Set the audio format */
   394 	value = format;
   395 	if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) ||
   396 						(value != format) ) {
   397 		SDL_SetError("Couldn't set audio format");
   398 		return(-1);
   399 	}
   400 
   401 	/* Set the number of channels of output */
   402 	value = spec->channels;
   403 #ifdef SNDCTL_DSP_CHANNELS
   404 	if ( ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0 ) {
   405 #endif
   406 		value = (spec->channels > 1);
   407 		ioctl(audio_fd, SNDCTL_DSP_STEREO, &value);
   408 		value = (value ? 2 : 1);
   409 #ifdef SNDCTL_DSP_CHANNELS
   410 	}
   411 #endif
   412 	spec->channels = value;
   413 
   414 	/* Because some drivers don't allow setting the buffer size
   415 	   after setting the format, we must re-open the audio device
   416 	   once we know what format and channels are supported
   417 	 */
   418 	if ( DSP_ReopenAudio(this, audiodev, format, spec) < 0 ) {
   419 		/* Error is set by DSP_ReopenAudio() */
   420 		return(-1);
   421 	}
   422 
   423 	/* Allocate mixing buffer */
   424 	mixlen = spec->size;
   425 	mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen);
   426 	if ( mixbuf == NULL ) {
   427 		return(-1);
   428 	}
   429 	memset(mixbuf, spec->silence, spec->size);
   430 
   431 #ifndef USE_BLOCKING_WRITES
   432 	/* Check to see if we need to use select() workaround */
   433 	{ char *workaround;
   434 		workaround = getenv("SDL_DSP_NOSELECT");
   435 		if ( workaround ) {
   436 			frame_ticks = (float)(spec->samples*1000)/spec->freq;
   437 			next_frame = SDL_GetTicks()+frame_ticks;
   438 		}
   439 	}
   440 #endif /* !USE_BLOCKING_WRITES */
   441 
   442 	/* Get the parent process id (we're the parent of the audio thread) */
   443 	parent = getpid();
   444 
   445 	/* We're ready to rock and roll. :-) */
   446 	return(0);
   447 }