wavestream.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 19 Aug 2001 19:13:09 +0000
changeset 95 871a7c1b93fb
parent 64 00b28153c609
child 97 2bf733171d56
permissions -rw-r--r--
Torbj´┐Żrn Andersson fixed AIFF music playing support
I removed malloc.h from timidity so it would build on MacOS X
     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_audio.h"
    31 #include "SDL_mutex.h"
    32 #include "SDL_rwops.h"
    33 #include "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 static 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 #ifndef macintosh /* Hmm.. */
    61 	if ( music_lock == NULL ) {
    62 		return(-1);
    63 	}
    64 #endif
    65 	mixer = *mixerfmt;
    66 	return(0);
    67 }
    68 
    69 /* Unimplemented */
    70 extern void WAVStream_SetVolume(int volume)
    71 {
    72 }
    73 
    74 /* Load a WAV stream from the given file */
    75 extern WAVStream *WAVStream_LoadSong(const char *file, const char *magic)
    76 {
    77 	WAVStream *wave;
    78 	SDL_AudioSpec wavespec;
    79 
    80 	if ( ! mixer.format ) {
    81 		SDL_SetError("WAV music output not started");
    82 		return(NULL);
    83 	}
    84 	wave = (WAVStream *)malloc(sizeof *wave);
    85 	if ( wave ) {
    86 		memset(wave, 0, (sizeof *wave));
    87 		if ( strcmp(magic, "RIFF") == 0 ) {
    88 			wave->wavefp = LoadWAVStream(file, &wavespec,
    89 					&wave->start, &wave->stop);
    90 		} else
    91 		if ( strcmp(magic, "FORM") == 0 ) {
    92 			wave->wavefp = LoadAIFFStream(file, &wavespec,
    93 					&wave->start, &wave->stop);
    94 		}
    95 		if ( wave->wavefp == NULL ) {
    96 			free(wave);
    97 			return(NULL);
    98 		}
    99 		SDL_BuildAudioCVT(&wave->cvt,
   100 			wavespec.format, wavespec.channels, wavespec.freq,
   101 			mixer.format, mixer.channels, mixer.freq);
   102 	}
   103 	return(wave);
   104 }
   105 
   106 /* Start playback of a given WAV stream */
   107 extern void WAVStream_Start(WAVStream *wave)
   108 {
   109 	SDL_mutexP(music_lock);
   110 	clearerr(wave->wavefp);
   111 	fseek(wave->wavefp, wave->start, SEEK_SET);
   112 	theWave = wave;
   113 	SDL_mutexV(music_lock);
   114 }
   115 
   116 /* Play some of a stream previously started with WAVStream_Start()
   117    The music_lock is held while this function is called.
   118  */
   119 extern void WAVStream_PlaySome(Uint8 *stream, int len)
   120 {
   121 	long pos;
   122 
   123 	SDL_mutexP(music_lock);
   124 	if ( theWave && ((pos=ftell(theWave->wavefp)) < theWave->stop) ) {
   125 		if ( theWave->cvt.needed ) {
   126 			int original_len;
   127 
   128 			original_len=(int)((double)len/theWave->cvt.len_ratio);
   129 			if ( theWave->cvt.len != original_len ) {
   130 				int worksize;
   131 				if ( theWave->cvt.buf != NULL ) {
   132 					free(theWave->cvt.buf);
   133 				}
   134 				worksize = original_len*theWave->cvt.len_mult;
   135 				theWave->cvt.buf=(Uint8 *)malloc(worksize);
   136 				if ( theWave->cvt.buf == NULL ) {
   137 					SDL_mutexV(music_lock);
   138 					return;
   139 				}
   140 				theWave->cvt.len = original_len;
   141 			}
   142 			if ( (theWave->stop - pos) < original_len ) {
   143 				original_len = (theWave->stop - pos);
   144 			}
   145 			theWave->cvt.len = original_len;
   146 			fread(theWave->cvt.buf,original_len,1,theWave->wavefp);
   147 			SDL_ConvertAudio(&theWave->cvt);
   148 			memcpy(stream, theWave->cvt.buf, theWave->cvt.len_cvt);
   149 		} else {
   150 			if ( (theWave->stop - pos) < len ) {
   151 				len = (theWave->stop - pos);
   152 			}
   153 			fread(stream, len, 1, theWave->wavefp);
   154 		}
   155 	}
   156 	SDL_mutexV(music_lock);
   157 }
   158 
   159 /* Stop playback of a stream previously started with WAVStream_Start() */
   160 extern void WAVStream_Stop(void)
   161 {
   162 	SDL_mutexP(music_lock);
   163 	theWave = NULL;
   164 	SDL_mutexV(music_lock);
   165 }
   166 
   167 /* Close the given WAV stream */
   168 extern void WAVStream_FreeSong(WAVStream *wave)
   169 {
   170 	if ( wave ) {
   171 		/* Remove song from the currently playing list */
   172 		SDL_mutexP(music_lock);
   173 		if ( wave == theWave ) {
   174 			theWave = NULL;
   175 		}
   176 		SDL_mutexV(music_lock);
   177 
   178 		/* Clean up associated data */
   179 		if ( wave->wavefp ) {
   180 			fclose(wave->wavefp);
   181 		}
   182 		if ( wave->cvt.buf ) {
   183 			free(wave->cvt.buf);
   184 		}
   185 		free(wave);
   186 	}
   187 }
   188 
   189 /* Return non-zero if a stream is currently playing */
   190 extern int WAVStream_Active(void)
   191 {
   192 	int active;
   193 
   194 	SDL_mutexP(music_lock);
   195 	active = 0;
   196 	if ( theWave && (ftell(theWave->wavefp) < theWave->stop) ) {
   197 		active = 1;
   198 	}
   199 	SDL_mutexV(music_lock);
   200 
   201 	return(active);
   202 }
   203 
   204 static int ReadChunk(SDL_RWops *src, Chunk *chunk, int read_data)
   205 {
   206 	chunk->magic	= SDL_ReadLE32(src);
   207 	chunk->length	= SDL_ReadLE32(src);
   208 	if ( read_data ) {
   209 		chunk->data = (Uint8 *)malloc(chunk->length);
   210 		if ( chunk->data == NULL ) {
   211 			SDL_SetError("Out of memory");
   212 			return(-1);
   213 		}
   214 		if ( SDL_RWread(src, chunk->data, chunk->length, 1) != 1 ) {
   215 			SDL_SetError("Couldn't read chunk");
   216 			free(chunk->data);
   217 			return(-1);
   218 		}
   219 	} else {
   220 		SDL_RWseek(src, chunk->length, SEEK_CUR);
   221 	}
   222 	return(chunk->length);
   223 }
   224 
   225 static FILE *LoadWAVStream (const char *file, SDL_AudioSpec *spec,
   226 					long *start, long *stop)
   227 {
   228 	int was_error;
   229 	FILE *wavefp;
   230 	SDL_RWops *src;
   231 	Chunk chunk;
   232 	int lenread;
   233 
   234 	/* WAV magic header */
   235 	Uint32 RIFFchunk;
   236 	Uint32 wavelen;
   237 	Uint32 WAVEmagic;
   238 
   239 	/* FMT chunk */
   240 	WaveFMT *format = NULL;
   241 
   242 	/* Make sure we are passed a valid data source */
   243 	was_error = 0;
   244 	wavefp = fopen(file, "rb");
   245 	src = NULL;
   246 	if ( wavefp ) {
   247 		src = SDL_RWFromFP(wavefp, 0);
   248 	}
   249 	if ( src == NULL ) {
   250 		was_error = 1;
   251 		goto done;
   252 	}
   253 
   254 	/* Check the magic header */
   255 	RIFFchunk	= SDL_ReadLE32(src);
   256 	wavelen		= SDL_ReadLE32(src);
   257 	WAVEmagic	= SDL_ReadLE32(src);
   258 	if ( (RIFFchunk != RIFF) || (WAVEmagic != WAVE) ) {
   259 		SDL_SetError("Unrecognized file type (not WAVE)");
   260 		was_error = 1;
   261 		goto done;
   262 	}
   263 
   264 	/* Read the audio data format chunk */
   265 	chunk.data = NULL;
   266 	do {
   267 		/* FIXME! Add this logic to SDL_LoadWAV_RW() */
   268 		if ( chunk.data ) {
   269 			free(chunk.data);
   270 		}
   271 		lenread = ReadChunk(src, &chunk, 1);
   272 		if ( lenread < 0 ) {
   273 			was_error = 1;
   274 			goto done;
   275 		}
   276 	} while ( (chunk.magic == FACT) || (chunk.magic == LIST) );
   277 
   278 	/* Decode the audio data format */
   279 	format = (WaveFMT *)chunk.data;
   280 	if ( chunk.magic != FMT ) {
   281 		free(chunk.data);
   282 		SDL_SetError("Complex WAVE files not supported");
   283 		was_error = 1;
   284 		goto done;
   285 	}
   286 	switch (SDL_SwapLE16(format->encoding)) {
   287 		case PCM_CODE:
   288 			/* We can understand this */
   289 			break;
   290 		default:
   291 			SDL_SetError("Unknown WAVE data format");
   292 			was_error = 1;
   293 			goto done;
   294 	}
   295 	memset(spec, 0, (sizeof *spec));
   296 	spec->freq = SDL_SwapLE32(format->frequency);
   297 	switch (SDL_SwapLE16(format->bitspersample)) {
   298 		case 8:
   299 			spec->format = AUDIO_U8;
   300 			break;
   301 		case 16:
   302 			spec->format = AUDIO_S16;
   303 			break;
   304 		default:
   305 			SDL_SetError("Unknown PCM data format");
   306 			was_error = 1;
   307 			goto done;
   308 	}
   309 	spec->channels = (Uint8) SDL_SwapLE16(format->channels);
   310 	spec->samples = 4096;		/* Good default buffer size */
   311 
   312 	/* Set the file offset to the DATA chunk data */
   313 	chunk.data = NULL;
   314 	do {
   315 		*start = SDL_RWtell(src) + 2*sizeof(Uint32);
   316 		lenread = ReadChunk(src, &chunk, 0);
   317 		if ( lenread < 0 ) {
   318 			was_error = 1;
   319 			goto done;
   320 		}
   321 	} while ( chunk.magic != DATA );
   322 	*stop = SDL_RWtell(src);
   323 
   324 done:
   325 	if ( format != NULL ) {
   326 		free(format);
   327 	}
   328 	if ( src ) {
   329 		SDL_RWclose(src);
   330 	}
   331 	if ( was_error ) {
   332 		if ( wavefp ) {
   333 			fclose(wavefp);
   334 			wavefp = NULL;
   335 		}
   336 	}
   337 	return(wavefp);
   338 }
   339 
   340 /* I couldn't get SANE_to_double() to work, so I stole this from libsndfile.
   341  * I don't pretend to fully understand it.
   342  */
   343 
   344 static Uint32 SANE_to_Uint32 (Uint8 *sanebuf)
   345 {
   346 	/* Negative number? */
   347 	if (sanebuf[0] & 0x80)
   348 		return 0;
   349 
   350 	/* Less than 1? */
   351 	if (sanebuf[0] <= 0x3F)
   352 		return 1;
   353 
   354 	/* Way too big? */
   355 	if (sanebuf[0] > 0x40)
   356 		return 0x4000000;
   357 
   358 	/* Still too big? */
   359 	if (sanebuf[0] == 0x40 && sanebuf[1] > 0x1C)
   360 		return 800000000;
   361 
   362 	return ((sanebuf[2] << 23) | (sanebuf[3] << 15) | (sanebuf[4] << 7)
   363 		| (sanebuf[5] >> 1)) >> (29 - sanebuf[1]);
   364 }
   365 
   366 static FILE *LoadAIFFStream (const char *file, SDL_AudioSpec *spec,
   367 					long *start, long *stop)
   368 {
   369 	int was_error;
   370 	int found_SSND;
   371 	int found_COMM;
   372 	FILE *wavefp;
   373 	SDL_RWops *src;
   374 
   375 	Uint32 chunk_type;
   376 	Uint32 chunk_length;
   377 	long next_chunk;
   378 
   379 	/* AIFF magic header */
   380 	Uint32 FORMchunk;
   381 	Uint32 AIFFmagic;
   382 	/* SSND chunk        */
   383 	Uint32 SSNDchunk;
   384 	Uint32 offset;
   385 	Uint32 blocksize;
   386 	/* COMM format chunk */
   387 	Uint32 COMMchunk;
   388 	Uint16 channels;
   389 	Uint32 numsamples;
   390 	Uint16 samplesize;
   391 	Uint8 sane_freq[10];
   392 	Uint32 frequency;
   393 
   394 
   395 	/* Make sure we are passed a valid data source */
   396 	was_error = 0;
   397 	wavefp = fopen(file, "rb");
   398 	src = NULL;
   399 	if ( wavefp ) {
   400 		src = SDL_RWFromFP(wavefp, 0);
   401 	}
   402 	if ( src == NULL ) {
   403 		was_error = 1;
   404 		goto done;
   405 	}
   406 
   407 	/* Check the magic header */
   408 	FORMchunk	= SDL_ReadLE32(src);
   409 	chunk_length	= SDL_ReadBE32(src);
   410 	AIFFmagic	= SDL_ReadLE32(src);
   411 	if ( (FORMchunk != FORM) || (AIFFmagic != AIFF) ) {
   412 		SDL_SetError("Unrecognized file type (not AIFF)");
   413 		was_error = 1;
   414 		goto done;
   415 	}
   416 
   417 	/* From what I understand of the specification, chunks may appear in
   418          * any order, and we should just ignore unknown ones.
   419          */
   420 
   421 	found_SSND = 0;
   422 	found_COMM = 0;
   423 
   424 	do {
   425 	    chunk_type		= SDL_ReadLE32(src);
   426 	    chunk_length	= SDL_ReadBE32(src);
   427 	    next_chunk		= SDL_RWtell(src) + chunk_length;
   428 
   429 	    /* Paranoia to avoid infinite loops */
   430 	    if (chunk_length == 0)
   431 		break;
   432 
   433             switch (chunk_type) {
   434 		case SSND:
   435 		    found_SSND		= 1;
   436 		    offset		= SDL_ReadBE32(src);
   437 		    blocksize		= SDL_ReadBE32(src);
   438 		    *start		= SDL_RWtell(src) + offset;
   439 		    break;
   440 
   441 		case COMM:
   442 		    found_COMM		= 1;
   443 
   444 		    /* Read the audio data format chunk */
   445 		    channels		= SDL_ReadBE16(src);
   446 		    numsamples		= SDL_ReadBE32(src);
   447 		    samplesize		= SDL_ReadBE16(src);
   448 		    SDL_RWread(src, sane_freq, sizeof(sane_freq), 1);
   449 		    frequency		= SANE_to_Uint32(sane_freq);
   450 		    break;
   451 
   452 		default:
   453 		    break;
   454 	    }
   455 	} while ((!found_SSND || !found_COMM)
   456 		 && SDL_RWseek(src, next_chunk, SEEK_SET) != -1);
   457 
   458 	if (!found_SSND) {
   459 	    SDL_SetError("Bad AIFF file (no SSND chunk)");
   460 	    was_error = 1;
   461 	    goto done;
   462 	}
   463 		    
   464 	if (!found_COMM) {
   465 	    SDL_SetError("Bad AIFF file (no COMM chunk)");
   466 	    was_error = 1;
   467 	    goto done;
   468 	}
   469 
   470 	*stop = *start + channels * numsamples * (samplesize / 8) - 1;
   471 
   472 	/* Decode the audio data format */
   473 	memset(spec, 0, (sizeof *spec));
   474 	spec->freq = frequency;
   475 	switch (samplesize) {
   476 		case 8:
   477 			spec->format = AUDIO_U8;
   478 			break;
   479 		case 16:
   480 			spec->format = AUDIO_S16MSB;
   481 			break;
   482 		default:
   483 			SDL_SetError("Unknown samplesize in data format");
   484 			was_error = 1;
   485 			goto done;
   486 	}
   487 	spec->channels = (Uint8) channels;
   488 	spec->samples = 4096;		/* Good default buffer size */
   489 
   490 done:
   491 	if ( src ) {
   492 		SDL_RWclose(src);
   493 	}
   494 	if ( was_error ) {
   495 		if ( wavefp ) {
   496 			fclose(wavefp);
   497 			wavefp = NULL;
   498 		}
   499 	}
   500 	return(wavefp);
   501 }