diff options
Diffstat (limited to 'src/i_sdlsound.c')
-rw-r--r-- | src/i_sdlsound.c | 518 |
1 files changed, 265 insertions, 253 deletions
diff --git a/src/i_sdlsound.c b/src/i_sdlsound.c index a26a81dd..1cfafa6f 100644 --- a/src/i_sdlsound.c +++ b/src/i_sdlsound.c @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // // Copyright(C) 1993-1996 Id Software, Inc. -// Copyright(C) 2005 Simon Howard +// Copyright(C) 2005-8 Simon Howard // Copyright(C) 2008 David Flater // // This program is free software; you can redistribute it and/or @@ -29,8 +29,8 @@ #include <stdio.h> #include <stdlib.h> +#include <string.h> #include <assert.h> -#include <math.h> #include "SDL.h" #include "SDL_mixer.h" @@ -38,15 +38,15 @@ #include <samplerate.h> #endif -#include "deh_main.h" +#include "deh_str.h" +#include "i_sound.h" #include "i_system.h" #include "i_swap.h" -#include "s_sound.h" #include "m_argv.h" #include "w_wad.h" #include "z_zone.h" -#include "doomdef.h" +#include "doomtype.h" #define LOW_PASS_FILTER //#define DEBUG_DUMP_WAVS @@ -57,12 +57,16 @@ static boolean setpanning_workaround = false; static boolean sound_initialized = false; -static Mix_Chunk sound_chunks[NUMSFX]; -static int channels_playing[NUM_CHANNELS]; +static sfxinfo_t *channels_playing[NUM_CHANNELS]; static int mixer_freq; static Uint16 mixer_format; static int mixer_channels; +static boolean use_sfx_prefix; +static void (*ExpandSoundData)(sfxinfo_t *sfxinfo, + byte *data, + int samplerate, + int length) = NULL; int use_libsamplerate = 0; @@ -73,34 +77,51 @@ int use_libsamplerate = 0; static void ReleaseSoundOnChannel(int channel) { int i; - int id = channels_playing[channel]; + sfxinfo_t *sfxinfo = channels_playing[channel]; - if (!id) + if (sfxinfo == NULL) { return; } - channels_playing[channel] = sfx_None; + channels_playing[channel] = NULL; -#ifdef HAVE_LIBSAMPLERATE - // Don't allow precached sounds to be swapped out. - if (use_libsamplerate) - return; -#endif - for (i=0; i<NUM_CHANNELS; ++i) { // Playing on this channel? if so, don't release. - if (channels_playing[i] == id) + if (channels_playing[i] == sfxinfo) return; } // Not used on any channel, and can be safely released - - Z_ChangeTag(sound_chunks[id].abuf, PU_CACHE); + + Z_ChangeTag(sfxinfo->driver_data, PU_CACHE); } +// Allocate a new Mix_Chunk along with its data, storing +// the result in the variable pointed to by variable + +static Mix_Chunk *AllocateChunk(sfxinfo_t *sfxinfo, uint32_t len) +{ + Mix_Chunk *chunk; + + // Allocate the chunk and the audio buffer together + + chunk = Z_Malloc(len + sizeof(Mix_Chunk), + PU_STATIC, + &sfxinfo->driver_data); + sfxinfo->driver_data = chunk; + + // Skip past the chunk structure for the audio buffer + + chunk->abuf = (byte *) (chunk + 1); + chunk->alen = len; + chunk->allocated = 1; + chunk->volume = MIX_MAX_VOLUME; + + return chunk; +} #ifdef HAVE_LIBSAMPLERATE @@ -131,6 +152,114 @@ static int SRC_ConversionMode(void) } } +// libsamplerate-based generic sound expansion function for any sample rate +// unsigned 8 bits --> signed 16 bits +// mono --> stereo +// samplerate --> mixer_freq +// Returns number of clipped samples. +// DWF 2008-02-10 with cleanups by Simon Howard. + +static void ExpandSoundData_SRC(sfxinfo_t *sfxinfo, + byte *data, + int samplerate, + int length) +{ + SRC_DATA src_data; + uint32_t i, abuf_index=0, clipped=0; + uint32_t alen; + int retn; + int16_t *expanded; + Mix_Chunk *chunk; + + src_data.input_frames = length; + src_data.data_in = malloc(length * sizeof(float)); + src_data.src_ratio = (double)mixer_freq / samplerate; + + // We include some extra space here in case of rounding-up. + src_data.output_frames = src_data.src_ratio * length + (mixer_freq / 4); + src_data.data_out = malloc(src_data.output_frames * sizeof(float)); + + assert(src_data.data_in != NULL && src_data.data_out != NULL); + + // Convert input data to floats + + for (i=0; i<length; ++i) + { + // Unclear whether 128 should be interpreted as "zero" or whether a + // symmetrical range should be assumed. The following assumes a + // symmetrical range. + src_data.data_in[i] = data[i] / 127.5 - 1; + } + + // Do the sound conversion + + retn = src_simple(&src_data, SRC_ConversionMode(), 1); + assert(retn == 0); + + // Allocate the new chunk. + + alen = src_data.output_frames_gen * 4; + + chunk = AllocateChunk(sfxinfo, src_data.output_frames_gen * 4); + expanded = (int16_t *) chunk->abuf; + + // Convert the result back into 16-bit integers. + + for (i=0; i<src_data.output_frames_gen; ++i) + { + // libsamplerate does not limit itself to the -1.0 .. 1.0 range on + // output, so a multiplier less than INT16_MAX (32767) is required + // to avoid overflows or clipping. However, the smaller the + // multiplier, the quieter the sound effects get, and the more you + // have to turn down the music to keep it in balance. + + // 22265 is the largest multiplier that can be used to resample all + // of the Vanilla DOOM sound effects to 48 kHz without clipping + // using SRC_SINC_BEST_QUALITY. It is close enough (only slightly + // too conservative) for SRC_SINC_MEDIUM_QUALITY and + // SRC_SINC_FASTEST. PWADs with interestingly different sound + // effects or target rates other than 48 kHz might still result in + // clipping--I don't know if there's a limit to it. + + // As the number of clipped samples increases, the signal is + // gradually overtaken by noise, with the loudest parts going first. + // However, a moderate amount of clipping is often tolerated in the + // quest for the loudest possible sound overall. The results of + // using INT16_MAX as the multiplier are not all that bad, but + // artifacts are noticeable during the loudest parts. + + float cvtval_f = src_data.data_out[i] * 22265; + int32_t cvtval_i = cvtval_f + (cvtval_f < 0 ? -0.5 : 0.5); + + // Asymmetrical sound worries me, so we won't use -32768. + if (cvtval_i < -INT16_MAX) + { + cvtval_i = -INT16_MAX; + ++clipped; + } + else if (cvtval_i > INT16_MAX) + { + cvtval_i = INT16_MAX; + ++clipped; + } + + // Left and right channels + + expanded[abuf_index++] = cvtval_i; + expanded[abuf_index++] = cvtval_i; + } + + free(src_data.data_in); + free(src_data.data_out); + + if (clipped > 0) + { + fprintf(stderr, "Sound '%s': clipped %u samples (%0.2f %%)\n", + sfxinfo->name, clipped, + 400.0 * clipped / chunk->alen); + } +} + #endif static boolean ConvertibleRatio(int freq1, int freq2) @@ -213,13 +342,15 @@ static void WriteWAV(char *filename, byte *data, #endif // Generic sound expansion function for any sample rate. +// Returns number of clipped samples (always 0). -static void ExpandSoundData_SDL(byte *data, +static void ExpandSoundData_SDL(sfxinfo_t *sfxinfo, + byte *data, int samplerate, - uint32_t length, - Mix_Chunk *destination) + int length) { SDL_AudioCVT convertor; + Mix_Chunk *chunk; uint32_t expanded_length; // Calculate the length of the expanded version of the sample. @@ -229,9 +360,10 @@ static void ExpandSoundData_SDL(byte *data, // Double up twice: 8 -> 16 bit and mono -> stereo expanded_length *= 4; - destination->alen = expanded_length; - destination->abuf - = Z_Malloc(expanded_length, PU_STATIC, &destination->abuf); + + // Allocate a chunk in which to expand the sound + + chunk = AllocateChunk(sfxinfo, expanded_length); // If we can, use the standard / optimized SDL conversion routines. @@ -241,7 +373,7 @@ static void ExpandSoundData_SDL(byte *data, AUDIO_U8, 1, samplerate, mixer_format, mixer_channels, mixer_freq)) { - convertor.buf = destination->abuf; + convertor.buf = chunk->abuf; convertor.len = length; memcpy(convertor.buf, data, length); @@ -249,7 +381,7 @@ static void ExpandSoundData_SDL(byte *data, } else { - Sint16 *expanded = (Sint16 *) destination->abuf; + Sint16 *expanded = (Sint16 *) chunk->abuf; int expanded_length; int expand_ratio; int i; @@ -312,93 +444,49 @@ static void ExpandSoundData_SDL(byte *data, } } +// Load and convert a sound effect +// Returns true if successful -// Load and validate a sound effect lump. -// Preconditions: -// S_sfx[sound].lumpnum has been set -// Postconditions if sound is valid: -// returns true -// starred parameters are set, with data_ref pointing to start of sound -// caller is responsible for releasing the identified lump -// Postconditions if sound is invalid: -// returns false -// starred parameters are garbage -// lump already released - -static boolean LoadSoundLump(int sound, - int *lumpnum, - int *samplerate, - uint32_t *length, - byte **data_ref) +static boolean CacheSFX(sfxinfo_t *sfxinfo) { - int lumplen; + int lumpnum; + unsigned int lumplen; + int samplerate; + unsigned int length; byte *data; - // Load the sound + // need to load the sound - *lumpnum = S_sfx[sound].lumpnum; - *data_ref = W_CacheLumpNum(*lumpnum, PU_STATIC); - lumplen = W_LumpLength(*lumpnum); - data = *data_ref; + lumpnum = sfxinfo->lumpnum; + data = W_CacheLumpNum(lumpnum, PU_STATIC); + lumplen = W_LumpLength(lumpnum); - // Ensure this is a valid sound + // Check the header, and ensure this is a valid sound - if (lumplen < 8 || data[0] != 0x03 || data[1] != 0x00) + if (lumplen < 8 + || data[0] != 0x03 || data[1] != 0x00) { - // Invalid sound - W_ReleaseLumpNum(*lumpnum); - return false; + // Invalid sound + + return false; } // 16 bit sample rate field, 32 bit length field - *samplerate = (data[3] << 8) | data[2]; - *length = (data[7] << 24) | (data[6] << 16) | (data[5] << 8) | data[4]; + samplerate = (data[3] << 8) | data[2]; + length = (data[7] << 24) | (data[6] << 16) | (data[5] << 8) | data[4]; - // If the header specifies that the length of the sound is - // greater than the length of the lump itself, this is an invalid - // sound lump. + // If the header specifies that the length of the sound is greater than + // the length of the lump itself, this is an invalid sound lump - if (*length > lumplen - 8) + if (length > lumplen - 8) { - W_ReleaseLumpNum(*lumpnum); - return false; - } - - // Prune header - *data_ref += 8; - - return true; -} - - -// Load and convert a sound effect -// Returns true if successful - -static boolean CacheSFX_SDL(int sound) -{ - int lumpnum; - int samplerate; - uint32_t length; - byte *data; - -#ifdef HAVE_LIBSAMPLERATE - assert(!use_libsamplerate); // Should be using I_PrecacheSounds_SRC instead -#endif - - if (!LoadSoundLump(sound, &lumpnum, &samplerate, &length, &data)) return false; + } // Sample rate conversion - // sound_chunks[sound].alen and abuf are determined by ExpandSoundData. - sound_chunks[sound].allocated = 1; - sound_chunks[sound].volume = MIX_MAX_VOLUME; - - ExpandSoundData_SDL(data, - samplerate, - length, - &sound_chunks[sound]); + ExpandSoundData(sfxinfo, data + 8, samplerate, length); #ifdef DEBUG_DUMP_WAVS { @@ -417,196 +505,115 @@ static boolean CacheSFX_SDL(int sound) return true; } +static void GetSfxLumpName(sfxinfo_t *sfx, char *buf) +{ + // Linked sfx lumps? Get the lump number for the sound linked to. + + if (sfx->link != NULL) + { + sfx = sfx->link; + } + + // Doom adds a DS* prefix to sound lumps; Heretic and Hexen don't + // do this. + + if (use_sfx_prefix) + { + sprintf(buf, "ds%s", DEH_String(sfx->name)); + } + else + { + strcpy(buf, DEH_String(sfx->name)); + } +} #ifdef HAVE_LIBSAMPLERATE -// Preload and resample all sound effects with libsamplerate. +// Preload all the sound effects - stops nasty ingame freezes -static void I_PrecacheSounds_SRC(void) +static void I_SDL_PrecacheSounds(sfxinfo_t *sounds, int num_sounds) { char namebuf[9]; - uint32_t sound_i, sample_i; - boolean good_sound[NUMSFX]; - float *resampled_sound[NUMSFX]; - uint32_t resampled_sound_length[NUMSFX]; - float norm_factor; - float max_amp = 0; - unsigned int zone_size; - - assert(use_libsamplerate); + int i; - zone_size = Z_ZoneSize(); + // Don't need to precache the sounds unless we are using libsamplerate. - if (zone_size < 32 * 1024 * 1024) + if (use_libsamplerate == 0) { - fprintf(stderr, - "WARNING: low memory. Heap size is only %d MiB.\n" - "WARNING: use_libsamplerate needs more heap!\n" - "WARNING: put -mb 64 on the command line to avoid " - "\"Error: Z_Malloc: failed on allocation of X bytes\" !\n", - zone_size / (1024 * 1024)); + return; } - printf("I_PrecacheSounds_SRC: Precaching all sound effects.."); - - // Pass 1: resample all sounds and determine maximum amplitude. + printf("I_SDL_PrecacheSounds: Precaching all sound effects.."); - for (sound_i=sfx_pistol; sound_i<NUMSFX; ++sound_i) + for (i=0; i<num_sounds; ++i) { - good_sound[sound_i] = false; - - if ((sound_i % 6) == 0) + if ((i % 6) == 0) { printf("."); fflush(stdout); } - sprintf(namebuf, "ds%s", DEH_String(S_sfx[sound_i].name)); - S_sfx[sound_i].lumpnum = W_CheckNumForName(namebuf); - if (S_sfx[sound_i].lumpnum != -1) - { - int lumpnum; - int samplerate; - uint32_t length; - byte *data; - double of_temp; - int retn; - float *rsound; - uint32_t rlen; - SRC_DATA src_data; - - if (!LoadSoundLump(sound_i, &lumpnum, &samplerate, &length, &data)) - continue; - - assert(length <= LONG_MAX); - src_data.input_frames = length; - src_data.data_in = malloc(length * sizeof(float)); - src_data.src_ratio = (double)mixer_freq / samplerate; - - // mixer_freq / 4 adds a quarter-second safety margin. - - of_temp = src_data.src_ratio * length + (mixer_freq / 4); - assert(of_temp <= LONG_MAX); - src_data.output_frames = of_temp; - src_data.data_out = malloc(src_data.output_frames * sizeof(float)); - assert(src_data.data_in != NULL && src_data.data_out != NULL); - - // Convert input data to floats - - for (sample_i=0; sample_i<length; ++sample_i) - { - // Unclear whether 128 should be interpreted as "zero" or - // whether a symmetrical range should be assumed. The - // following assumes a symmetrical range. - - src_data.data_in[sample_i] = data[sample_i] / 127.5 - 1; - } - - // don't need the original lump any more - - W_ReleaseLumpNum(lumpnum); - - // Resample - - retn = src_simple(&src_data, SRC_ConversionMode(), 1); - assert(retn == 0); - assert(src_data.output_frames_gen > 0); - resampled_sound[sound_i] = src_data.data_out; - resampled_sound_length[sound_i] = src_data.output_frames_gen; - free(src_data.data_in); - good_sound[sound_i] = true; - - // Track maximum amplitude for later normalization - - rsound = resampled_sound[sound_i]; - rlen = resampled_sound_length[sound_i]; - for (sample_i=0; sample_i<rlen; ++sample_i) - { - float fabs_amp = fabsf(rsound[sample_i]); - if (fabs_amp > max_amp) - max_amp = fabs_amp; - } - } - } - - // Pass 2: normalize and convert to signed 16-bit stereo. + GetSfxLumpName(&sounds[i], namebuf); - if (max_amp <= 0) - max_amp = 1; - norm_factor = INT16_MAX / max_amp; + sounds[i].lumpnum = W_CheckNumForName(namebuf); - for (sound_i=sfx_pistol; sound_i<NUMSFX; ++sound_i) - { - if (good_sound[sound_i]) + if (sounds[i].lumpnum != -1) { - uint32_t rlen = resampled_sound_length[sound_i]; - int16_t *expanded; - uint32_t abuf_index; - float *rsound; - - sound_chunks[sound_i].allocated = 1; - sound_chunks[sound_i].volume = MIX_MAX_VOLUME; - sound_chunks[sound_i].alen = rlen * 4; - sound_chunks[sound_i].abuf = Z_Malloc(sound_chunks[sound_i].alen, - PU_STATIC, - &sound_chunks[sound_i].abuf); - expanded = (int16_t *) sound_chunks[sound_i].abuf; - abuf_index=0; - - rsound = resampled_sound[sound_i]; - for (sample_i=0; sample_i<rlen; ++sample_i) - { - float cvtval_f = norm_factor * rsound[sample_i]; - int16_t cvtval_i = cvtval_f + (cvtval_f < 0 ? -0.5 : 0.5); + // Try to cache the sound and then release it as cache - // Left and right channels - - expanded[abuf_index++] = cvtval_i; - expanded[abuf_index++] = cvtval_i; + if (CacheSFX(&sounds[i])) + { + Z_ChangeTag(sounds[i].driver_data, PU_CACHE); } - free(rsound); } } - printf(" norm factor = %f\n", norm_factor); + printf("\n"); +} + +#else + +static void I_SDL_PrecacheSounds(sfxinfo_t *sounds, int num_sounds) +{ + // no-op } #endif +// Load a SFX chunk into memory and ensure that it is locked. -static Mix_Chunk *GetSFXChunk(int sound_id) +static boolean LockSound(sfxinfo_t *sfxinfo) { - if (sound_chunks[sound_id].abuf == NULL) + // If the sound isn't loaded, load it now + + if (sfxinfo->driver_data == NULL) { -#ifdef HAVE_LIBSAMPLERATE - if (use_libsamplerate != 0) - return NULL; /* If valid, it should have been precached */ -#endif - if (!CacheSFX_SDL(sound_id)) - return NULL; + if (!CacheSFX(sfxinfo)) + { + return false; + } } else { - // don't free the sound while it is playing! + // Lock the sound effect into memory - Z_ChangeTag(sound_chunks[sound_id].abuf, PU_STATIC); + Z_ChangeTag(sfxinfo->driver_data, PU_STATIC); } - return &sound_chunks[sound_id]; + return true; } - // // Retrieve the raw data lump index // for a given SFX name. // -static int I_SDL_GetSfxLumpNum(sfxinfo_t* sfx) +static int I_SDL_GetSfxLumpNum(sfxinfo_t *sfx) { char namebuf[9]; - sprintf(namebuf, "ds%s", DEH_String(sfx->name)); - + GetSfxLumpName(sfx, namebuf); + return W_GetNumForName(namebuf); } @@ -622,6 +629,11 @@ static void I_SDL_UpdateSoundParams(int handle, int vol, int sep) left = ((254 - sep) * vol) / 127; right = ((sep) * vol) / 127; + if (left < 0) left = 0; + else if ( left > 255) left = 255; + if (right < 0) right = 0; + else if (right > 255) right = 255; + // SDL_mixer version 1.2.8 and earlier has a bug in the Mix_SetPanning // function. A workaround is to call Mix_UnregisterAllEffects for // the channel before calling it. This is undesirable as it may lead @@ -648,7 +660,7 @@ static void I_SDL_UpdateSoundParams(int handle, int vol, int sep) // is set, but currently not used by mixing. // -static int I_SDL_StartSound(int id, int channel, int vol, int sep) +static int I_SDL_StartSound(sfxinfo_t *sfxinfo, int channel, int vol, int sep) { Mix_Chunk *chunk; @@ -664,18 +676,18 @@ static int I_SDL_StartSound(int id, int channel, int vol, int sep) // Get the sound data - chunk = GetSFXChunk(id); - - if (chunk == NULL) + if (!LockSound(sfxinfo)) { - return -1; + return -1; } + chunk = (Mix_Chunk *) sfxinfo->driver_data; + // play sound Mix_PlayChannelTimed(channel, chunk, 0, -1); - channels_playing[channel] = id; + channels_playing[channel] = sfxinfo; // set separation, etc. @@ -772,20 +784,17 @@ static int GetSliceSize(void) return 1024; } -static boolean I_SDL_InitSound(void) -{ +static boolean I_SDL_InitSound(boolean _use_sfx_prefix) +{ int i; - - // No sounds yet - for (i=0; i<NUMSFX; ++i) - { - sound_chunks[i].abuf = NULL; - } + use_sfx_prefix = _use_sfx_prefix; + + // No sounds yet for (i=0; i<NUM_CHANNELS; ++i) { - channels_playing[i] = sfx_None; + channels_playing[i] = NULL; } if (SDL_Init(SDL_INIT_AUDIO) < 0) @@ -796,10 +805,12 @@ static boolean I_SDL_InitSound(void) if (Mix_OpenAudio(snd_samplerate, AUDIO_S16SYS, 2, GetSliceSize()) < 0) { - fprintf(stderr, "Error initializing SDL_mixer: %s\n", Mix_GetError()); + fprintf(stderr, "Error initialising SDL_mixer: %s\n", Mix_GetError()); return false; } + ExpandSoundData = ExpandSoundData_SDL; + Mix_QuerySpec(&mixer_freq, &mixer_format, &mixer_channels); #ifdef HAVE_LIBSAMPLERATE @@ -811,7 +822,7 @@ static boolean I_SDL_InitSound(void) use_libsamplerate); } - I_PrecacheSounds_SRC(); + ExpandSoundData = ExpandSoundData_SRC; } #else if (use_libsamplerate != 0) @@ -879,5 +890,6 @@ sound_module_t sound_sdl_module = I_SDL_StartSound, I_SDL_StopSound, I_SDL_SoundIsPlaying, + I_SDL_PrecacheSounds, }; |