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