// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005 Simon Howard // Copyright(C) 2008 David Flater // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // // DESCRIPTION: // System interface for sound. // //----------------------------------------------------------------------------- #include "config.h" #include #include #include #include #include "SDL.h" #include "SDL_mixer.h" #ifdef HAVE_LIBSAMPLERATE #include #endif #include "deh_main.h" #include "i_system.h" #include "s_sound.h" #include "m_argv.h" #include "w_wad.h" #include "z_zone.h" #include "doomdef.h" #define LOW_PASS_FILTER #define MAX_SOUND_SLICE_TIME 70 /* ms */ #define NUM_CHANNELS 16 static boolean sound_initialized = false; static Mix_Chunk sound_chunks[NUMSFX]; static int channels_playing[NUM_CHANNELS]; static int mixer_freq; static Uint16 mixer_format; static int mixer_channels; int use_libsamplerate = 0; // When a sound stops, check if it is still playing. If it is not, // we can mark the sound data as CACHE to be freed back for other // means. static void ReleaseSoundOnChannel(int channel) { int i; int id = channels_playing[channel]; if (!id) { return; } channels_playing[channel] = sfx_None; #ifdef HAVE_LIBSAMPLERATE // Don't allow precached sounds to be swapped out. if (use_libsamplerate) return; #endif for (i=0; i freq2) { return ConvertibleRatio(freq2, freq1); } else if ((freq2 % freq1) != 0) { // Not in a direct ratio return false; } else { // Check the ratio is a power of 2 ratio = freq2 / freq1; while ((ratio & 1) == 0) { ratio = ratio >> 1; } return ratio == 1; } } // Generic sound expansion function for any sample rate. static void ExpandSoundData_SDL(byte *data, int samplerate, uint32_t length, Mix_Chunk *destination) { SDL_AudioCVT convertor; uint32_t expanded_length; // Calculate the length of the expanded version of the sample. expanded_length = (uint32_t) ((((uint64_t) length) * mixer_freq) / samplerate); // 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); // If we can, use the standard / optimized SDL conversion routines. if (samplerate <= mixer_freq && ConvertibleRatio(samplerate, mixer_freq) && SDL_BuildAudioCVT(&convertor, AUDIO_U8, 1, samplerate, mixer_format, mixer_channels, mixer_freq)) { convertor.buf = destination->abuf; convertor.len = length; memcpy(convertor.buf, data, length); SDL_ConvertAudio(&convertor); } else { Sint16 *expanded = (Sint16 *) destination->abuf; int expanded_length; int expand_ratio; int i; // Generic expansion if conversion does not work: // // SDL's audio conversion only works for rate conversions that are // powers of 2; if the two formats are not in a direct power of 2 // ratio, do this naive conversion instead. // number of samples in the converted sound expanded_length = ((uint64_t) length * mixer_freq) / samplerate; expand_ratio = (length << 8) / expanded_length; for (i=0; i> 8; sample = data[src] | (data[src] << 8); sample -= 32768; // expand 8->16 bits, mono->stereo expanded[i * 2] = expanded[i * 2 + 1] = sample; } #ifdef LOW_PASS_FILTER // Perform a low-pass filter on the upscaled sound to filter // out high-frequency noise from the conversion process. { float rc, dt, alpha; // Low-pass filter for cutoff frequency f: // // For sampling rate r, dt = 1 / r // rc = 1 / 2*pi*f // alpha = dt / (rc + dt) // Filter to the half sample rate of the original sound effect // (maximum frequency, by nyquist) dt = 1.0f / mixer_freq; rc = 1.0f / (3.14f * samplerate); alpha = dt / (rc + dt); for (i=1; i 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]); // don't need the original lump any more W_ReleaseLumpNum(lumpnum); return true; } #ifdef HAVE_LIBSAMPLERATE // Preload and resample all sound effects with libsamplerate. static void I_PrecacheSounds_SRC(void) { 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); zone_size = Z_ZoneSize(); if (zone_size < 32 * 1024 * 1024) { 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)); } printf("I_PrecacheSounds_SRC: Precaching all sound effects.."); // Pass 1: resample all sounds and determine maximum amplitude. for (sound_i=sfx_pistol; sound_i 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 max_amp) max_amp = fabs_amp; } } } // Pass 2: normalize and convert to signed 16-bit stereo. if (max_amp <= 0) max_amp = 1; norm_factor = INT16_MAX / max_amp; for (sound_i=sfx_pistol; sound_iname)); return W_GetNumForName(namebuf); } static void I_SDL_UpdateSoundParams(int handle, int vol, int sep) { int left, right; if (!sound_initialized) { return; } left = ((254 - sep) * vol) / 127; right = ((sep) * vol) / 127; Mix_SetPanning(handle, left, right); } // // Starting a sound means adding it // to the current list of active sounds // in the internal channels. // As the SFX info struct contains // e.g. a pointer to the raw data, // it is ignored. // As our sound handling does not handle // priority, it is ignored. // Pitching (that is, increased speed of playback) // is set, but currently not used by mixing. // static int I_SDL_StartSound(int id, int channel, int vol, int sep) { Mix_Chunk *chunk; if (!sound_initialized) { return -1; } // Release a sound effect if there is already one playing // on this channel ReleaseSoundOnChannel(channel); // Get the sound data chunk = GetSFXChunk(id); if (chunk == NULL) { return -1; } // play sound Mix_PlayChannelTimed(channel, chunk, 0, -1); channels_playing[channel] = id; // set separation, etc. I_SDL_UpdateSoundParams(channel, vol, sep); return channel; } static void I_SDL_StopSound (int handle) { if (!sound_initialized) { return; } Mix_HaltChannel(handle); // Sound data is no longer needed; release the // sound data being used for this channel ReleaseSoundOnChannel(handle); } static boolean I_SDL_SoundIsPlaying(int handle) { if (handle < 0) { return false; } return Mix_Playing(handle); } // // Periodically called to update the sound system // static void I_SDL_UpdateSound(void) { int i; // Check all channels to see if a sound has finished for (i=0; i limit) { return (1 << n); } } // Should never happen? return 1024; } static boolean I_SDL_InitSound(void) { int i; // No sounds yet for (i=0; i