wavestream.c
author Stephane Peter
Sat, 30 Oct 1999 22:57:49 +0000
changeset 11 3939a99bf422
parent 0 4ce2db4db959
child 24 a25bb2d59ce8
permissions -rw-r--r--
Various bugfixes for music looping
     1 /*
     2     MIXERLIB:  An audio mixer library based on the SDL library
     3     Copyright (C) 1997-1999  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     5635-34 Springhouse Dr.
    21     Pleasanton, CA 94588 (USA)
    22     slouken@devolution.com
    23 */
    24 
    25 /* This file supports streaming WAV files, without volume adjustment */
    26 
    27 #include <stdlib.h>
    28 #include <string.h>
    29 
    30 #include <SDL/SDL_audio.h>
    31 #include <SDL/SDL_mutex.h>
    32 #include <SDL/SDL_rwops.h>
    33 #include <SDL/SDL_endian.h>
    34 
    35 #include "wave.h"
    36 #include "wavestream.h"
    37 
    38 /* Currently we only support a single stream at a time */
    39 static WAVStream *theWave = NULL;
    40 
    41 /* This is initialized by the music mixer */
    42 SDL_mutex *music_lock = NULL;
    43 
    44 /* This is the format of the audio mixer data */
    45 static SDL_AudioSpec mixer;
    46 
    47 /* Function to load the WAV/AIFF stream */
    48 static FILE *LoadWAVStream (const char *file, SDL_AudioSpec *spec,
    49 					long *start, long *stop);
    50 static FILE *LoadAIFFStream (const char *file, SDL_AudioSpec *spec,
    51 					long *start, long *stop);
    52 
    53 /* Initialize the WAVStream player, with the given mixer settings
    54    This function returns 0, or -1 if there was an error.
    55  */
    56 int WAVStream_Init(SDL_AudioSpec *mixerfmt)
    57 {
    58 	/* FIXME: clean up the mutex, or move it into music.c */
    59 	music_lock = SDL_CreateMutex();
    60 	if ( music_lock == NULL ) {
    61 		return(-1);
    62 	}
    63 	mixer = *mixerfmt;
    64 	return(0);
    65 }
    66 
    67 /* Unimplemented */
    68 extern void WAVStream_SetVolume(int volume)
    69 {
    70 }
    71 
    72 /* Load a WAV stream from the given file */
    73 extern WAVStream *WAVStream_LoadSong(const char *file, const char *magic)
    74 {
    75 	WAVStream *wave;
    76 	SDL_AudioSpec wavespec;
    77 
    78 	if ( ! mixer.format ) {
    79 		SDL_SetError("WAV music output not started");
    80 		return(NULL);
    81 	}
    82 	wave = (WAVStream *)malloc(sizeof *wave);
    83 	if ( wave ) {
    84 		memset(wave, 0, (sizeof *wave));
    85 		if ( strcmp(magic, "RIFF") == 0 ) {
    86 			wave->wavefp = LoadWAVStream(file, &wavespec,
    87 					&wave->start, &wave->stop);
    88 		} else
    89 		if ( strcmp(magic, "FORM") == 0 ) {
    90 			wave->wavefp = LoadAIFFStream(file, &wavespec,
    91 					&wave->start, &wave->stop);
    92 		}
    93 		if ( wave->wavefp == NULL ) {
    94 			free(wave);
    95 			return(NULL);
    96 		}
    97 		SDL_BuildAudioCVT(&wave->cvt,
    98 			wavespec.format, wavespec.channels, wavespec.freq,
    99 			mixer.format, mixer.channels, mixer.freq);
   100 	}
   101 	return(wave);
   102 }
   103 
   104 /* Start playback of a given WAV stream */
   105 extern void WAVStream_Start(WAVStream *wave)
   106 {
   107 	SDL_mutexP(music_lock);
   108 	clearerr(wave->wavefp);
   109 	fseek(wave->wavefp, wave->start, SEEK_SET);
   110 	theWave = wave;
   111 	SDL_mutexV(music_lock);
   112 }
   113 
   114 /* Play some of a stream previously started with WAVStream_Start()
   115    The music_lock is held while this function is called.
   116  */
   117 extern void WAVStream_PlaySome(Uint8 *stream, int len)
   118 {
   119 	long pos;
   120 
   121 	SDL_mutexP(music_lock);
   122 	if ( theWave && ((pos=ftell(theWave->wavefp)) < theWave->stop) ) {
   123 		if ( theWave->cvt.needed ) {
   124 			int original_len;
   125 
   126 			original_len=(int)((double)len/theWave->cvt.len_ratio);
   127 			if ( theWave->cvt.len != original_len ) {
   128 				int worksize;
   129 				if ( theWave->cvt.buf != NULL ) {
   130 					free(theWave->cvt.buf);
   131 				}
   132 				worksize = original_len*theWave->cvt.len_mult;
   133 				theWave->cvt.buf=(Uint8 *)malloc(worksize);
   134 				if ( theWave->cvt.buf == NULL ) {
   135 					SDL_mutexV(music_lock);
   136 					return;
   137 				}
   138 				theWave->cvt.len = original_len;
   139 			}
   140 			if ( (theWave->stop - pos) < original_len ) {
   141 				original_len = (theWave->stop - pos);
   142 			}
   143 			theWave->cvt.len = original_len;
   144 			fread(theWave->cvt.buf,original_len,1,theWave->wavefp);
   145 			SDL_ConvertAudio(&theWave->cvt);
   146 			memcpy(stream, theWave->cvt.buf, theWave->cvt.len_cvt);
   147 		} else {
   148 			if ( (theWave->stop - pos) < len ) {
   149 				len = (theWave->stop - pos);
   150 			}
   151 			fread(stream, len, 1, theWave->wavefp);
   152 		}
   153 	}
   154 	SDL_mutexV(music_lock);
   155 }
   156 
   157 /* Stop playback of a stream previously started with WAVStream_Start() */
   158 extern void WAVStream_Stop(void)
   159 {
   160 	SDL_mutexP(music_lock);
   161 	theWave = NULL;
   162 	SDL_mutexV(music_lock);
   163 }
   164 
   165 /* Close the given WAV stream */
   166 extern void WAVStream_FreeSong(WAVStream *wave)
   167 {
   168 	if ( wave ) {
   169 		/* Remove song from the currently playing list */
   170 		SDL_mutexP(music_lock);
   171 		if ( wave == theWave ) {
   172 			theWave = NULL;
   173 		}
   174 		SDL_mutexV(music_lock);
   175 
   176 		/* Clean up associated data */
   177 		if ( wave->wavefp ) {
   178 			fclose(wave->wavefp);
   179 		}
   180 		if ( wave->cvt.buf ) {
   181 			free(wave->cvt.buf);
   182 		}
   183 		free(wave);
   184 	}
   185 }
   186 
   187 /* Return non-zero if a stream is currently playing */
   188 extern int WAVStream_Active(void)
   189 {
   190 	int active;
   191 
   192 	SDL_mutexP(music_lock);
   193 	active = 0;
   194 	if ( theWave && (ftell(theWave->wavefp) < theWave->stop) ) {
   195 		active = 1;
   196 	}
   197 	SDL_mutexV(music_lock);
   198 
   199 	return(active);
   200 }
   201 
   202 static int ReadChunk(SDL_RWops *src, Chunk *chunk, int read_data)
   203 {
   204 	chunk->magic	= SDL_ReadLE32(src);
   205 	chunk->length	= SDL_ReadLE32(src);
   206 	if ( read_data ) {
   207 		chunk->data = (Uint8 *)malloc(chunk->length);
   208 		if ( chunk->data == NULL ) {
   209 			SDL_SetError("Out of memory");
   210 			return(-1);
   211 		}
   212 		if ( SDL_RWread(src, chunk->data, chunk->length, 1) != 1 ) {
   213 			SDL_SetError("Couldn't read chunk");
   214 			free(chunk->data);
   215 			return(-1);
   216 		}
   217 	} else {
   218 		SDL_RWseek(src, chunk->length, SEEK_CUR);
   219 	}
   220 	return(chunk->length);
   221 }
   222 
   223 static FILE *LoadWAVStream (const char *file, SDL_AudioSpec *spec,
   224 					long *start, long *stop)
   225 {
   226 	int was_error;
   227 	FILE *wavefp;
   228 	SDL_RWops *src;
   229 	Chunk chunk;
   230 	int lenread;
   231 
   232 	/* WAV magic header */
   233 	Uint32 RIFFchunk;
   234 	Uint32 wavelen;
   235 	Uint32 WAVEmagic;
   236 
   237 	/* FMT chunk */
   238 	WaveFMT *format = NULL;
   239 
   240 	/* Make sure we are passed a valid data source */
   241 	was_error = 0;
   242 	wavefp = fopen(file, "rb");
   243 	src = NULL;
   244 	if ( wavefp ) {
   245 		src = SDL_RWFromFP(wavefp, 0);
   246 	}
   247 	if ( src == NULL ) {
   248 		was_error = 1;
   249 		goto done;
   250 	}
   251 		
   252 	/* Check the magic header */
   253 	RIFFchunk	= SDL_ReadLE32(src);
   254 	wavelen		= SDL_ReadLE32(src);
   255 	WAVEmagic	= SDL_ReadLE32(src);
   256 	if ( (RIFFchunk != RIFF) || (WAVEmagic != WAVE) ) {
   257 		SDL_SetError("Unrecognized file type (not WAVE)");
   258 		was_error = 1;
   259 		goto done;
   260 	}
   261 
   262 	/* Read the audio data format chunk */
   263 	chunk.data = NULL;
   264 	do {
   265 		/* FIXME! Add this logic to SDL_LoadWAV_RW() */
   266 		if ( chunk.data ) {
   267 			free(chunk.data);
   268 		}
   269 		lenread = ReadChunk(src, &chunk, 1);
   270 		if ( lenread < 0 ) {
   271 			was_error = 1;
   272 			goto done;
   273 		}
   274 	} while ( (chunk.magic == FACT) || (chunk.magic == LIST) );
   275 
   276 	/* Decode the audio data format */
   277 	format = (WaveFMT *)chunk.data;
   278 	if ( chunk.magic != FMT ) {
   279 		free(chunk.data);
   280 		SDL_SetError("Complex WAVE files not supported");
   281 		was_error = 1;
   282 		goto done;
   283 	}
   284 	switch (SDL_SwapLE16(format->encoding)) {
   285 		case PCM_CODE:
   286 			/* We can understand this */
   287 			break;
   288 		default:
   289 			SDL_SetError("Unknown WAVE data format");
   290 			was_error = 1;
   291 			goto done;
   292 	}
   293 	memset(spec, 0, (sizeof *spec));
   294 	spec->freq = SDL_SwapLE32(format->frequency);
   295 	switch (SDL_SwapLE16(format->bitspersample)) {
   296 		case 8:
   297 			spec->format = AUDIO_U8;
   298 			break;
   299 		case 16:
   300 			spec->format = AUDIO_S16;
   301 			break;
   302 		default:
   303 			SDL_SetError("Unknown PCM data format");
   304 			was_error = 1;
   305 			goto done;
   306 	}
   307 	spec->channels = SDL_SwapLE16(format->channels);
   308 	spec->samples = 4096;		/* Good default buffer size */
   309 
   310 	/* Set the file offset to the DATA chunk data */
   311 	chunk.data = NULL;
   312 	do {
   313 		*start = SDL_RWtell(src) + 2*sizeof(Uint32);
   314 		lenread = ReadChunk(src, &chunk, 0);
   315 		if ( lenread < 0 ) {
   316 			was_error = 1;
   317 			goto done;
   318 		}
   319 	} while ( chunk.magic != DATA );
   320 	*stop = SDL_RWtell(src);
   321 
   322 done:
   323 	if ( format != NULL ) {
   324 		free(format);
   325 	}
   326 	if ( src ) {
   327 		SDL_RWclose(src);
   328 	}
   329 	if ( was_error ) {
   330 		if ( wavefp ) {
   331 			fclose(wavefp);
   332 			wavefp = NULL;
   333 		}
   334 	}
   335 	return(wavefp);
   336 }
   337 
   338 static double SANE_to_double(Uint32 l1, Uint32 l2, Uint16 s1)
   339 {
   340 	double d;
   341 	struct almost_double {
   342 		Uint32 hi, lo;
   343 	} *dp = (struct almost_double *)&d;
   344 
   345 	dp->hi = ((l1 << 4) & 0x3ff00000) | (l1 & 0xc0000000);
   346 	dp->hi |= (l1 << 5) & 0xffff0;
   347 	dp->hi |= (l2 >> 27) & 0x1f;
   348 	dp->lo = (l2 << 5) & 0xffffffe0;
   349 	dp->lo |= ((s1 >> 11) & 0x1f);
   350 	return(d);
   351 }
   352 
   353 static FILE *LoadAIFFStream (const char *file, SDL_AudioSpec *spec,
   354 					long *start, long *stop)
   355 {
   356 	int was_error;
   357 	FILE *wavefp;
   358 	SDL_RWops *src;
   359 	Chunk chunk;
   360 	int lenread;
   361 
   362 	/* AIFF magic header */
   363 	Uint32 FORMchunk;
   364 	Uint32 chunklen;
   365 	Uint32 AIFFmagic;
   366 	/* SSND chunk        */
   367 	Uint32 SSNDchunk;
   368 	Uint32 ssndlen;
   369 	Uint32 offset;
   370 	Uint32 blocksize;
   371 	/* COMM format chunk */
   372 	Uint32 COMMchunk;
   373 	Uint32 commlen;
   374 	Uint16 channels;
   375 	Uint32 numsamples;
   376 	Uint16 samplesize;
   377 	struct { /* plus a SANE format double precision number */
   378 		Uint32 l1;
   379 		Uint32 l2;
   380 		Uint16 s1;
   381 	} sane_freq;
   382 	
   383 	Uint32 frequency;
   384 
   385 
   386 	/* Make sure we are passed a valid data source */
   387 	was_error = 0;
   388 	wavefp = fopen(file, "rb");
   389 	src = NULL;
   390 	if ( wavefp ) {
   391 		src = SDL_RWFromFP(wavefp, 0);
   392 	}
   393 	if ( src == NULL ) {
   394 		was_error = 1;
   395 		goto done;
   396 	}
   397 		
   398 	/* Check the magic header */
   399 	FORMchunk	= SDL_ReadLE32(src);
   400 	chunklen	= SDL_ReadLE32(src);
   401 	AIFFmagic	= SDL_ReadLE32(src);
   402 	if ( (FORMchunk != FORM) || (AIFFmagic != AIFF) ) {
   403 		SDL_SetError("Unrecognized file type (not AIFF)");
   404 		was_error = 1;
   405 		goto done;
   406 	}
   407 
   408 	/* Read the SSND data chunk */
   409 	SSNDchunk	= SDL_ReadLE32(src);
   410 	if ( SSNDchunk != SSND ) {
   411 		SDL_SetError("Unrecognized AIFF chunk (not SSND)");
   412 		was_error = 1;
   413 		goto done;
   414 	}
   415 	ssndlen		= SDL_ReadLE32(src);
   416 	offset		= SDL_ReadLE32(src);
   417 	blocksize	= SDL_ReadLE32(src);
   418 
   419 	/* Fill in start and stop pointers, then seek to format chunk */
   420 	ssndlen -= (2*sizeof(Uint32));
   421 	*start = SDL_RWtell(src) + offset;
   422 	*stop = SDL_RWtell(src) + ssndlen;
   423 	SDL_RWseek(src, *stop, SEEK_SET);
   424 
   425 	/* Read the audio data format chunk */
   426 	COMMchunk	= SDL_ReadLE32(src);
   427 	if ( COMMchunk != COMM ) {
   428 		SDL_SetError("Unrecognized AIFF chunk (not COMM)");
   429 		was_error = 1;
   430 		goto done;
   431 	}
   432 	commlen		= SDL_ReadLE32(src);
   433 	channels	= SDL_ReadLE16(src);
   434 	numsamples	= SDL_ReadLE32(src);
   435 	samplesize	= SDL_ReadLE16(src);
   436 	sane_freq.l1	= SDL_ReadLE32(src);
   437 	sane_freq.l2	= SDL_ReadLE32(src);
   438 	sane_freq.s1	= SDL_ReadLE16(src);
   439 	frequency	= (Uint32)SANE_to_double(sane_freq.l1, sane_freq.l2,
   440 								sane_freq.s1);
   441 
   442 	/* Decode the audio data format */
   443 	memset(spec, 0, (sizeof *spec));
   444 	spec->freq = frequency;
   445 	switch (samplesize) {
   446 		case 8:
   447 			spec->format = AUDIO_U8;
   448 			break;
   449 		case 16:
   450 			spec->format = AUDIO_S16;
   451 			break;
   452 		default:
   453 			SDL_SetError("Unknown samplesize in data format");
   454 			was_error = 1;
   455 			goto done;
   456 	}
   457 	spec->channels = channels;
   458 	spec->samples = 4096;		/* Good default buffer size */
   459 
   460 done:
   461 	if ( src ) {
   462 		SDL_RWclose(src);
   463 	}
   464 	if ( was_error ) {
   465 		if ( wavefp ) {
   466 			fclose(wavefp);
   467 			wavefp = NULL;
   468 		}
   469 	}
   470 	return(wavefp);
   471 }