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