2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 // snd_main.c -- main control for any streaming sound output device
26 #include "snd_modplug.h"
29 #define SND_MIN_SPEED 8000
30 #define SND_MAX_SPEED 96000
31 #define SND_MIN_WIDTH 1
32 #define SND_MAX_WIDTH 2
33 #define SND_MIN_CHANNELS 1
34 #define SND_MAX_CHANNELS 8
36 #if SND_LISTENERS != 8
37 # error this data only supports up to 8 channel, update it!
39 typedef struct listener_s
47 typedef struct speakerlayout_s
50 unsigned int channels;
51 listener_t listeners[SND_LISTENERS];
55 static speakerlayout_t snd_speakerlayout;
57 // Our speaker layouts are based on ALSA. They differ from those
58 // Win32 and Mac OS X APIs use when there's more than 4 channels.
59 // (rear left + rear right, and front center + LFE are swapped).
60 #define SND_SPEAKERLAYOUTS (sizeof(snd_speakerlayouts) / sizeof(snd_speakerlayouts[0]))
61 static const speakerlayout_t snd_speakerlayouts[] =
66 {45, 0.2, 0.2, 0.5}, // front left
67 {315, 0.2, 0.2, 0.5}, // front right
68 {135, 0.2, 0.2, 0.5}, // rear left
69 {225, 0.2, 0.2, 0.5}, // rear right
70 {0, 0.2, 0.2, 0.5}, // front center
71 {0, 0, 0, 0}, // lfe (we don't have any good lfe sound sources and it would take some filtering work to generate them (and they'd probably still be wrong), so... no lfe)
72 {90, 0.2, 0.2, 0.5}, // side left
73 {180, 0.2, 0.2, 0.5}, // side right
79 {45, 0.2, 0.2, 0.5}, // front left
80 {315, 0.2, 0.2, 0.5}, // front right
81 {135, 0.2, 0.2, 0.5}, // rear left
82 {225, 0.2, 0.2, 0.5}, // rear right
83 {0, 0.2, 0.2, 0.5}, // front center
84 {0, 0, 0, 0}, // lfe (we don't have any good lfe sound sources and it would take some filtering work to generate them (and they'd probably still be wrong), so... no lfe)
90 // these systems sometimes have a subwoofer as well, but it has no
94 {45, 0.3, 0.3, 0.8}, // front left
95 {315, 0.3, 0.3, 0.8}, // front right
96 {135, 0.3, 0.3, 0.8}, // rear left
97 {225, 0.3, 0.3, 0.8}, // rear right
105 // these systems sometimes have a subwoofer as well, but it has no
106 // channel of its own
109 {90, 0.5, 0.5, 1}, // side left
110 {270, 0.5, 0.5, 1}, // side right
122 {0, 0, 1, 1}, // center
135 // =======================================================================
136 // Internal sound data & structures
137 // =======================================================================
139 channel_t channels[MAX_CHANNELS];
140 unsigned int total_channels;
142 snd_ringbuffer_t *snd_renderbuffer = NULL;
143 static unsigned int soundtime = 0;
144 static unsigned int oldpaintedtime = 0;
145 static unsigned int extrasoundtime = 0;
146 static double snd_starttime = 0.0;
147 qboolean snd_threaded = false;
148 qboolean snd_usethreadedmixing = false;
150 vec3_t listener_origin;
151 matrix4x4_t listener_matrix[SND_LISTENERS];
152 mempool_t *snd_mempool;
154 // Linked list of known sfx
155 static sfx_t *known_sfx = NULL;
157 static qboolean sound_spatialized = false;
159 qboolean simsound = false;
161 static qboolean recording_sound = false;
164 static int current_swapstereo = false;
165 static int current_channellayout = SND_CHANNELLAYOUT_AUTO;
166 static int current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
168 static double spatialpower, spatialmin, spatialdiff, spatialoffset, spatialfactor;
169 typedef enum { SPATIAL_NONE, SPATIAL_LOG, SPATIAL_POW, SPATIAL_THRESH } spatialmethod_t;
170 spatialmethod_t spatialmethod;
172 // Cvars declared in sound.h (part of the sound API)
173 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1", "volume of background music (such as CD music or replacement files such as sound/cdtracks/track002.ogg)"};
174 cvar_t volume = {CVAR_SAVE, "volume", "0.7", "volume of sound effects"};
175 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0", "indicates the sound subsystem is active"};
176 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1", "volume of ambient sound effects (such as swampy sounds at the start of e1m2)"};
177 cvar_t snd_soundradius = {CVAR_SAVE, "snd_soundradius", "2000", "radius of weapon sounds and other standard sound effects (monster idle noises are half this radius and flickering light noises are one third of this radius)"};
178 cvar_t snd_spatialization_min_radius = {CVAR_SAVE, "snd_spatialization_min_radius", "10000", "use minimum spatialization above to this radius"};
179 cvar_t snd_spatialization_max_radius = {CVAR_SAVE, "snd_spatialization_max_radius", "100", "use maximum spatialization below this radius"};
180 cvar_t snd_spatialization_min = {CVAR_SAVE, "snd_spatialization_min", "0.70", "minimum spatializazion of sounds"};
181 cvar_t snd_spatialization_max = {CVAR_SAVE, "snd_spatialization_max", "0.95", "maximum spatialization of sounds"};
182 cvar_t snd_spatialization_power = {CVAR_SAVE, "snd_spatialization_power", "0", "exponent of the spatialization falloff curve (0: logarithmic)"};
183 cvar_t snd_spatialization_control = {CVAR_SAVE, "snd_spatialization_control", "0", "enable spatialization control (headphone friendly mode)"};
185 // Cvars declared in snd_main.h (shared with other snd_*.c files)
186 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1", "how much sound to mix ahead of time"};
187 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1", "enables keeping compressed ogg sound files compressed, decompressing them only as needed, otherwise they will be decompressed completely at load (may use a lot of memory)"};
188 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0", "swaps left/right speakers for old ISA soundblaster cards"};
189 extern cvar_t v_flipped;
190 cvar_t snd_channellayout = {0, "snd_channellayout", "0", "channel layout. Can be 0 (auto - snd_restart needed), 1 (standard layout), or 2 (ALSA layout)"};
191 cvar_t snd_mutewhenidle = {CVAR_SAVE, "snd_mutewhenidle", "1", "whether to disable sound output when game window is inactive"};
192 cvar_t snd_entchannel0volume = {CVAR_SAVE, "snd_entchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of regular entities"};
193 cvar_t snd_entchannel1volume = {CVAR_SAVE, "snd_entchannel1volume", "1", "volume multiplier of the 1st entity channel of regular entities"};
194 cvar_t snd_entchannel2volume = {CVAR_SAVE, "snd_entchannel2volume", "1", "volume multiplier of the 2nd entity channel of regular entities"};
195 cvar_t snd_entchannel3volume = {CVAR_SAVE, "snd_entchannel3volume", "1", "volume multiplier of the 3rd entity channel of regular entities"};
196 cvar_t snd_entchannel4volume = {CVAR_SAVE, "snd_entchannel4volume", "1", "volume multiplier of the 4th entity channel of regular entities"};
197 cvar_t snd_entchannel5volume = {CVAR_SAVE, "snd_entchannel5volume", "1", "volume multiplier of the 5th entity channel of regular entities"};
198 cvar_t snd_entchannel6volume = {CVAR_SAVE, "snd_entchannel6volume", "1", "volume multiplier of the 6th entity channel of regular entities"};
199 cvar_t snd_entchannel7volume = {CVAR_SAVE, "snd_entchannel7volume", "1", "volume multiplier of the 7th entity channel of regular entities"};
200 cvar_t snd_playerchannel0volume = {CVAR_SAVE, "snd_playerchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of player entities"};
201 cvar_t snd_playerchannel1volume = {CVAR_SAVE, "snd_playerchannel1volume", "1", "volume multiplier of the 1st entity channel of player entities"};
202 cvar_t snd_playerchannel2volume = {CVAR_SAVE, "snd_playerchannel2volume", "1", "volume multiplier of the 2nd entity channel of player entities"};
203 cvar_t snd_playerchannel3volume = {CVAR_SAVE, "snd_playerchannel3volume", "1", "volume multiplier of the 3rd entity channel of player entities"};
204 cvar_t snd_playerchannel4volume = {CVAR_SAVE, "snd_playerchannel4volume", "1", "volume multiplier of the 4th entity channel of player entities"};
205 cvar_t snd_playerchannel5volume = {CVAR_SAVE, "snd_playerchannel5volume", "1", "volume multiplier of the 5th entity channel of player entities"};
206 cvar_t snd_playerchannel6volume = {CVAR_SAVE, "snd_playerchannel6volume", "1", "volume multiplier of the 6th entity channel of player entities"};
207 cvar_t snd_playerchannel7volume = {CVAR_SAVE, "snd_playerchannel7volume", "1", "volume multiplier of the 7th entity channel of player entities"};
208 cvar_t snd_worldchannel0volume = {CVAR_SAVE, "snd_worldchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of the world entity"};
209 cvar_t snd_worldchannel1volume = {CVAR_SAVE, "snd_worldchannel1volume", "1", "volume multiplier of the 1st entity channel of the world entity"};
210 cvar_t snd_worldchannel2volume = {CVAR_SAVE, "snd_worldchannel2volume", "1", "volume multiplier of the 2nd entity channel of the world entity"};
211 cvar_t snd_worldchannel3volume = {CVAR_SAVE, "snd_worldchannel3volume", "1", "volume multiplier of the 3rd entity channel of the world entity"};
212 cvar_t snd_worldchannel4volume = {CVAR_SAVE, "snd_worldchannel4volume", "1", "volume multiplier of the 4th entity channel of the world entity"};
213 cvar_t snd_worldchannel5volume = {CVAR_SAVE, "snd_worldchannel5volume", "1", "volume multiplier of the 5th entity channel of the world entity"};
214 cvar_t snd_worldchannel6volume = {CVAR_SAVE, "snd_worldchannel6volume", "1", "volume multiplier of the 6th entity channel of the world entity"};
215 cvar_t snd_worldchannel7volume = {CVAR_SAVE, "snd_worldchannel7volume", "1", "volume multiplier of the 7th entity channel of the world entity"};
216 cvar_t snd_csqcchannel0volume = {CVAR_SAVE, "snd_csqcchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of the world entity"};
217 cvar_t snd_csqcchannel1volume = {CVAR_SAVE, "snd_csqcchannel1volume", "1", "volume multiplier of the 1st entity channel of the world entity"};
218 cvar_t snd_csqcchannel2volume = {CVAR_SAVE, "snd_csqcchannel2volume", "1", "volume multiplier of the 2nd entity channel of the world entity"};
219 cvar_t snd_csqcchannel3volume = {CVAR_SAVE, "snd_csqcchannel3volume", "1", "volume multiplier of the 3rd entity channel of the world entity"};
220 cvar_t snd_csqcchannel4volume = {CVAR_SAVE, "snd_csqcchannel4volume", "1", "volume multiplier of the 4th entity channel of the world entity"};
221 cvar_t snd_csqcchannel5volume = {CVAR_SAVE, "snd_csqcchannel5volume", "1", "volume multiplier of the 5th entity channel of the world entity"};
222 cvar_t snd_csqcchannel6volume = {CVAR_SAVE, "snd_csqcchannel6volume", "1", "volume multiplier of the 6th entity channel of the world entity"};
223 cvar_t snd_csqcchannel7volume = {CVAR_SAVE, "snd_csqcchannel7volume", "1", "volume multiplier of the 7th entity channel of the world entity"};
226 static cvar_t nosound = {0, "nosound", "0", "disables sound"};
227 static cvar_t snd_precache = {0, "snd_precache", "1", "loads sounds before they are used"};
228 static cvar_t ambient_level = {0, "ambient_level", "0.3", "volume of environment noises (water and wind)"};
229 static cvar_t ambient_fade = {0, "ambient_fade", "100", "rate of volume fading when moving from one environment to another"};
230 static cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0", "disables extra sound mixer calls that are meant to reduce the chance of sound breakup at very low framerates"};
231 static cvar_t snd_show = {0, "snd_show", "0", "shows some statistics about sound mixing"};
233 // Default sound format is 48KHz, 16-bit, stereo
234 // (48KHz because a lot of onboard sound cards sucks at any other speed)
235 static cvar_t snd_speed = {CVAR_SAVE, "snd_speed", "48000", "sound output frequency, in hertz"};
236 static cvar_t snd_width = {CVAR_SAVE, "snd_width", "2", "sound output precision, in bytes (1 and 2 supported)"};
237 static cvar_t snd_channels = {CVAR_SAVE, "snd_channels", "2", "number of channels for the sound ouput (2 for stereo; up to 8 supported for 3D sound)"};
240 static sfx_t* ambient_sfxs [2] = { NULL, NULL };
241 static const char* ambient_names [2] = { "sound/ambience/water1.wav", "sound/ambience/wind2.wav" };
244 // ====================================================================
246 // ====================================================================
248 void S_FreeSfx (sfx_t *sfx, qboolean force);
250 static void S_Play_Common (float fvol, float attenuation)
253 char name [MAX_QPATH];
257 while (i < Cmd_Argc ())
259 // Get the name, and appends ".wav" as an extension if there's none
260 strlcpy (name, Cmd_Argv (i), sizeof (name));
261 if (!strrchr (name, '.'))
262 strlcat (name, ".wav", sizeof (name));
265 // If we need to get the volume from the command line
268 fvol = atof (Cmd_Argv (i));
272 sfx = S_PrecacheSound (name, true, false);
275 ch_ind = S_StartSound (-1, 0, sfx, listener_origin, fvol, attenuation);
277 // Free the sfx if the file didn't exist
279 S_FreeSfx (sfx, false);
281 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
286 static void S_Play_f(void)
288 S_Play_Common (1.0f, 1.0f);
291 static void S_Play2_f(void)
293 S_Play_Common (1.0f, 0.0f);
296 static void S_PlayVol_f(void)
298 S_Play_Common (-1.0f, 0.0f);
301 static void S_SoundList_f (void)
308 for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
310 if (sfx->fetcher != NULL)
313 const snd_format_t* format;
316 format = sfx->fetcher->getfmt(sfx);
317 Con_Printf ("%c%c%c%c(%2db, %6s) %8i : %s\n",
318 (sfx->loopstart < sfx->total_length) ? 'L' : ' ',
319 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
320 (sfx->locks > 0) ? 'K' : ' ',
321 (sfx->flags & SFXFLAG_PERMANENTLOCK) ? 'P' : ' ',
323 (format->channels == 1) ? "mono" : "stereo",
329 Con_Printf (" ( unknown ) unloaded : %s\n", sfx->name);
331 Con_Printf("Total resident: %i\n", total);
335 void S_SoundInfo_f(void)
337 if (snd_renderbuffer == NULL)
339 Con_Print("sound system not started\n");
343 Con_Printf("%5d speakers\n", snd_renderbuffer->format.channels);
344 Con_Printf("%5d frames\n", snd_renderbuffer->maxframes);
345 Con_Printf("%5d samplebits\n", snd_renderbuffer->format.width * 8);
346 Con_Printf("%5d speed\n", snd_renderbuffer->format.speed);
347 Con_Printf("%5u total_channels\n", total_channels);
351 int S_GetSoundRate(void)
353 return snd_renderbuffer ? snd_renderbuffer->format.speed : 0;
357 static qboolean S_ChooseCheaperFormat (snd_format_t* format, qboolean fixed_speed, qboolean fixed_width, qboolean fixed_channels)
359 static const snd_format_t thresholds [] =
361 // speed width channels
362 { SND_MIN_SPEED, SND_MIN_WIDTH, SND_MIN_CHANNELS },
368 { SND_MAX_SPEED, SND_MAX_WIDTH, SND_MAX_CHANNELS },
370 const unsigned int nb_thresholds = sizeof(thresholds) / sizeof(thresholds[0]);
371 unsigned int speed_level, width_level, channels_level;
373 // If we have reached the minimum values, there's nothing more we can do
374 if ((format->speed == thresholds[0].speed || fixed_speed) &&
375 (format->width == thresholds[0].width || fixed_width) &&
376 (format->channels == thresholds[0].channels || fixed_channels))
379 // Check the min and max values
380 #define CHECK_BOUNDARIES(param) \
381 if (format->param < thresholds[0].param) \
383 format->param = thresholds[0].param; \
386 if (format->param > thresholds[nb_thresholds - 1].param) \
388 format->param = thresholds[nb_thresholds - 1].param; \
391 CHECK_BOUNDARIES(speed);
392 CHECK_BOUNDARIES(width);
393 CHECK_BOUNDARIES(channels);
394 #undef CHECK_BOUNDARIES
396 // Find the level of each parameter
397 #define FIND_LEVEL(param) \
399 while (param##_level < nb_thresholds - 1) \
401 if (format->param <= thresholds[param##_level].param) \
408 FIND_LEVEL(channels);
411 // Decrease the parameter with the highest level to the previous level
412 if (channels_level >= speed_level && channels_level >= width_level && !fixed_channels)
414 format->channels = thresholds[channels_level - 1].channels;
417 if (speed_level >= width_level && !fixed_speed)
419 format->speed = thresholds[speed_level - 1].speed;
423 format->width = thresholds[width_level - 1].width;
428 #define SWAP_LISTENERS(l1, l2, tmpl) { tmpl = (l1); (l1) = (l2); (l2) = tmpl; }
430 static void S_SetChannelLayout (void)
433 listener_t swaplistener;
434 listener_t *listeners;
437 for (i = 0; i < SND_SPEAKERLAYOUTS; i++)
438 if (snd_speakerlayouts[i].channels == snd_renderbuffer->format.channels)
440 if (i >= SND_SPEAKERLAYOUTS)
442 Con_Printf("S_SetChannelLayout: can't find the speaker layout for %hu channels. Defaulting to mono output\n",
443 snd_renderbuffer->format.channels);
444 i = SND_SPEAKERLAYOUTS - 1;
447 snd_speakerlayout = snd_speakerlayouts[i];
448 listeners = snd_speakerlayout.listeners;
450 // Swap the left and right channels if snd_swapstereo is set
451 if (boolxor(snd_swapstereo.integer, v_flipped.integer))
453 switch (snd_speakerlayout.channels)
456 SWAP_LISTENERS(listeners[6], listeners[7], swaplistener);
460 SWAP_LISTENERS(listeners[2], listeners[3], swaplistener);
463 SWAP_LISTENERS(listeners[0], listeners[1], swaplistener);
474 if (snd_channellayout.integer < SND_CHANNELLAYOUT_AUTO ||
475 snd_channellayout.integer > SND_CHANNELLAYOUT_ALSA)
476 Cvar_SetValueQuick (&snd_channellayout, SND_CHANNELLAYOUT_STANDARD);
478 if (snd_channellayout.integer == SND_CHANNELLAYOUT_AUTO)
480 // If we're in the sound engine initialization
481 if (current_channellayout_used == SND_CHANNELLAYOUT_AUTO)
483 layout = SND_CHANNELLAYOUT_STANDARD;
484 Cvar_SetValueQuick (&snd_channellayout, layout);
487 layout = current_channellayout_used;
490 layout = snd_channellayout.integer;
492 // Convert our layout (= ALSA) to the standard layout if necessary
493 if (snd_speakerlayout.channels == 6 || snd_speakerlayout.channels == 8)
495 if (layout == SND_CHANNELLAYOUT_STANDARD)
497 SWAP_LISTENERS(listeners[2], listeners[4], swaplistener);
498 SWAP_LISTENERS(listeners[3], listeners[5], swaplistener);
501 Con_Printf("S_SetChannelLayout: using %s speaker layout for 3D sound\n",
502 (layout == SND_CHANNELLAYOUT_ALSA) ? "ALSA" : "standard");
505 current_swapstereo = boolxor(snd_swapstereo.integer, v_flipped.integer);
506 current_channellayout = snd_channellayout.integer;
507 current_channellayout_used = layout;
511 void S_Startup (void)
513 qboolean fixed_speed, fixed_width, fixed_channels;
514 snd_format_t chosen_fmt;
515 static snd_format_t prev_render_format = {0, 0, 0};
522 if (!snd_initialized.integer)
527 fixed_channels = false;
529 // Get the starting sound format from the cvars
530 chosen_fmt.speed = snd_speed.integer;
531 chosen_fmt.width = snd_width.integer;
532 chosen_fmt.channels = snd_channels.integer;
534 // Check the environment variables to see if the player wants a particular sound format
536 _dupenv_s(&env, &envlen, "QUAKE_SOUND_CHANNELS");
538 env = getenv("QUAKE_SOUND_CHANNELS");
542 chosen_fmt.channels = atoi (env);
546 fixed_channels = true;
549 _dupenv_s(&env, &envlen, "QUAKE_SOUND_SPEED");
551 env = getenv("QUAKE_SOUND_SPEED");
555 chosen_fmt.speed = atoi (env);
562 _dupenv_s(&env, &envlen, "QUAKE_SOUND_SAMPLEBITS");
564 env = getenv("QUAKE_SOUND_SAMPLEBITS");
568 chosen_fmt.width = atoi (env) / 8;
575 // Parse the command line to see if the player wants a particular sound format
576 // COMMANDLINEOPTION: Sound: -sndquad sets sound output to 4 channel surround
577 if (COM_CheckParm ("-sndquad") != 0)
579 chosen_fmt.channels = 4;
580 fixed_channels = true;
582 // COMMANDLINEOPTION: Sound: -sndstereo sets sound output to stereo
583 else if (COM_CheckParm ("-sndstereo") != 0)
585 chosen_fmt.channels = 2;
586 fixed_channels = true;
588 // COMMANDLINEOPTION: Sound: -sndmono sets sound output to mono
589 else if (COM_CheckParm ("-sndmono") != 0)
591 chosen_fmt.channels = 1;
592 fixed_channels = true;
594 // COMMANDLINEOPTION: Sound: -sndspeed <hz> chooses sound output rate (supported values are 48000, 44100, 32000, 24000, 22050, 16000, 11025 (quake), 8000)
595 i = COM_CheckParm ("-sndspeed");
596 if (0 < i && i < com_argc - 1)
598 chosen_fmt.speed = atoi (com_argv[i + 1]);
601 // COMMANDLINEOPTION: Sound: -sndbits <bits> chooses 8 bit or 16 bit sound output
602 i = COM_CheckParm ("-sndbits");
603 if (0 < i && i < com_argc - 1)
605 chosen_fmt.width = atoi (com_argv[i + 1]) / 8;
609 // You can't change sound speed after start time (not yet supported)
610 if (prev_render_format.speed != 0)
613 if (chosen_fmt.speed != prev_render_format.speed)
615 Con_Printf("S_Startup: sound speed has changed! This is NOT supported yet. Falling back to previous speed (%u Hz)\n",
616 prev_render_format.speed);
617 chosen_fmt.speed = prev_render_format.speed;
622 if (chosen_fmt.speed < SND_MIN_SPEED)
624 chosen_fmt.speed = SND_MIN_SPEED;
627 else if (chosen_fmt.speed > SND_MAX_SPEED)
629 chosen_fmt.speed = SND_MAX_SPEED;
633 if (chosen_fmt.width < SND_MIN_WIDTH)
635 chosen_fmt.width = SND_MIN_WIDTH;
638 else if (chosen_fmt.width > SND_MAX_WIDTH)
640 chosen_fmt.width = SND_MAX_WIDTH;
644 if (chosen_fmt.channels < SND_MIN_CHANNELS)
646 chosen_fmt.channels = SND_MIN_CHANNELS;
647 fixed_channels = false;
649 else if (chosen_fmt.channels > SND_MAX_CHANNELS)
651 chosen_fmt.channels = SND_MAX_CHANNELS;
652 fixed_channels = false;
655 // create the sound buffer used for sumitting the samples to the plaform-dependent module
658 snd_format_t suggest_fmt;
664 Con_Printf("S_Startup: initializing sound output format: %dHz, %d bit, %d channels...\n",
665 chosen_fmt.speed, chosen_fmt.width * 8,
666 chosen_fmt.channels);
668 memset(&suggest_fmt, 0, sizeof(suggest_fmt));
669 accepted = SndSys_Init(&chosen_fmt, &suggest_fmt);
673 Con_Printf("S_Startup: sound output initialization FAILED\n");
675 // If the module is suggesting another one
676 if (suggest_fmt.speed != 0)
678 memcpy(&chosen_fmt, &suggest_fmt, sizeof(chosen_fmt));
679 Con_Printf (" Driver has suggested %dHz, %d bit, %d channels. Retrying...\n",
680 suggest_fmt.speed, suggest_fmt.width * 8,
681 suggest_fmt.channels);
683 // Else, try to find a less resource-demanding format
684 else if (!S_ChooseCheaperFormat (&chosen_fmt, fixed_speed, fixed_width, fixed_channels))
689 // If we haven't found a suitable format
692 Con_Print("S_Startup: SndSys_Init failed.\n");
693 sound_spatialized = false;
699 snd_renderbuffer = Snd_CreateRingBuffer(&chosen_fmt, 0, NULL);
700 Con_Print ("S_Startup: simulating sound output\n");
703 memcpy(&prev_render_format, &snd_renderbuffer->format, sizeof(prev_render_format));
704 Con_Printf("Sound format: %dHz, %d channels, %d bits per sample\n",
705 chosen_fmt.speed, chosen_fmt.channels, chosen_fmt.width * 8);
708 if (snd_speed.integer != (int)chosen_fmt.speed)
709 Cvar_SetValueQuick(&snd_speed, chosen_fmt.speed);
710 if (snd_width.integer != chosen_fmt.width)
711 Cvar_SetValueQuick(&snd_width, chosen_fmt.width);
712 if (snd_channels.integer != chosen_fmt.channels)
713 Cvar_SetValueQuick(&snd_channels, chosen_fmt.channels);
715 current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
716 S_SetChannelLayout();
718 snd_starttime = realtime;
720 // If the sound module has already run, add an extra time to make sure
721 // the sound time doesn't decrease, to not confuse playing SFXs
722 if (oldpaintedtime != 0)
724 // The extra time must be a multiple of the render buffer size
725 // to avoid modifying the current position in the buffer,
726 // some modules write directly to a shared (DMA) buffer
727 extrasoundtime = oldpaintedtime + snd_renderbuffer->maxframes - 1;
728 extrasoundtime -= extrasoundtime % snd_renderbuffer->maxframes;
729 Con_Printf("S_Startup: extra sound time = %u\n", extrasoundtime);
731 soundtime = extrasoundtime;
735 snd_renderbuffer->startframe = soundtime;
736 snd_renderbuffer->endframe = soundtime;
737 recording_sound = false;
740 void S_Shutdown(void)
742 if (snd_renderbuffer == NULL)
745 oldpaintedtime = snd_renderbuffer->endframe;
749 Mem_Free(snd_renderbuffer->ring);
750 Mem_Free(snd_renderbuffer);
751 snd_renderbuffer = NULL;
756 sound_spatialized = false;
759 void S_Restart_f(void)
761 // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
762 // So, refuse to do this if we are connected.
763 if(cls.state == ca_connected)
765 Con_Printf("snd_restart would wreak havoc if you do that while connected!\n");
780 Cvar_RegisterVariable(&volume);
781 Cvar_RegisterVariable(&bgmvolume);
782 Cvar_RegisterVariable(&snd_staticvolume);
783 Cvar_RegisterVariable(&snd_entchannel0volume);
784 Cvar_RegisterVariable(&snd_entchannel1volume);
785 Cvar_RegisterVariable(&snd_entchannel2volume);
786 Cvar_RegisterVariable(&snd_entchannel3volume);
787 Cvar_RegisterVariable(&snd_entchannel4volume);
788 Cvar_RegisterVariable(&snd_entchannel5volume);
789 Cvar_RegisterVariable(&snd_entchannel6volume);
790 Cvar_RegisterVariable(&snd_entchannel7volume);
791 Cvar_RegisterVariable(&snd_worldchannel0volume);
792 Cvar_RegisterVariable(&snd_worldchannel1volume);
793 Cvar_RegisterVariable(&snd_worldchannel2volume);
794 Cvar_RegisterVariable(&snd_worldchannel3volume);
795 Cvar_RegisterVariable(&snd_worldchannel4volume);
796 Cvar_RegisterVariable(&snd_worldchannel5volume);
797 Cvar_RegisterVariable(&snd_worldchannel6volume);
798 Cvar_RegisterVariable(&snd_worldchannel7volume);
799 Cvar_RegisterVariable(&snd_playerchannel0volume);
800 Cvar_RegisterVariable(&snd_playerchannel1volume);
801 Cvar_RegisterVariable(&snd_playerchannel2volume);
802 Cvar_RegisterVariable(&snd_playerchannel3volume);
803 Cvar_RegisterVariable(&snd_playerchannel4volume);
804 Cvar_RegisterVariable(&snd_playerchannel5volume);
805 Cvar_RegisterVariable(&snd_playerchannel6volume);
806 Cvar_RegisterVariable(&snd_playerchannel7volume);
807 Cvar_RegisterVariable(&snd_csqcchannel0volume);
808 Cvar_RegisterVariable(&snd_csqcchannel1volume);
809 Cvar_RegisterVariable(&snd_csqcchannel2volume);
810 Cvar_RegisterVariable(&snd_csqcchannel3volume);
811 Cvar_RegisterVariable(&snd_csqcchannel4volume);
812 Cvar_RegisterVariable(&snd_csqcchannel5volume);
813 Cvar_RegisterVariable(&snd_csqcchannel6volume);
814 Cvar_RegisterVariable(&snd_csqcchannel7volume);
816 Cvar_RegisterVariable(&snd_spatialization_min_radius);
817 Cvar_RegisterVariable(&snd_spatialization_max_radius);
818 Cvar_RegisterVariable(&snd_spatialization_min);
819 Cvar_RegisterVariable(&snd_spatialization_max);
820 Cvar_RegisterVariable(&snd_spatialization_power);
821 Cvar_RegisterVariable(&snd_spatialization_control);
823 Cvar_RegisterVariable(&snd_speed);
824 Cvar_RegisterVariable(&snd_width);
825 Cvar_RegisterVariable(&snd_channels);
826 Cvar_RegisterVariable(&snd_mutewhenidle);
828 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
829 if (COM_CheckParm("-nosound"))
831 // dummy out Play and Play2 because mods stuffcmd that
832 Cmd_AddCommand("play", Host_NoOperation_f, "does nothing because -nosound was specified");
833 Cmd_AddCommand("play2", Host_NoOperation_f, "does nothing because -nosound was specified");
837 snd_mempool = Mem_AllocPool("sound", 0, NULL);
839 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
840 if (COM_CheckParm("-simsound"))
843 Cmd_AddCommand("play", S_Play_f, "play a sound at your current location (not heard by anyone else)");
844 Cmd_AddCommand("play2", S_Play2_f, "play a sound globally throughout the level (not heard by anyone else)");
845 Cmd_AddCommand("playvol", S_PlayVol_f, "play a sound at the specified volume level at your current location (not heard by anyone else)");
846 Cmd_AddCommand("stopsound", S_StopAllSounds, "silence");
847 Cmd_AddCommand("soundlist", S_SoundList_f, "list loaded sounds");
848 Cmd_AddCommand("soundinfo", S_SoundInfo_f, "print sound system information (such as channels and speed)");
849 Cmd_AddCommand("snd_restart", S_Restart_f, "restart sound system");
850 Cmd_AddCommand("snd_unloadallsounds", S_UnloadAllSounds_f, "unload all sound files");
852 Cvar_RegisterVariable(&nosound);
853 Cvar_RegisterVariable(&snd_precache);
854 Cvar_RegisterVariable(&snd_initialized);
855 Cvar_RegisterVariable(&snd_streaming);
856 Cvar_RegisterVariable(&ambient_level);
857 Cvar_RegisterVariable(&ambient_fade);
858 Cvar_RegisterVariable(&snd_noextraupdate);
859 Cvar_RegisterVariable(&snd_show);
860 Cvar_RegisterVariable(&_snd_mixahead);
861 Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
862 Cvar_RegisterVariable(&snd_channellayout);
863 Cvar_RegisterVariable(&snd_soundradius);
865 Cvar_SetValueQuick(&snd_initialized, true);
869 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
870 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
873 ModPlug_OpenLibrary ();
881 Shutdown and free all resources
884 void S_Terminate (void)
887 ModPlug_CloseLibrary ();
891 while (known_sfx != NULL)
892 S_FreeSfx (known_sfx, true);
894 Cvar_SetValueQuick (&snd_initialized, false);
895 Mem_FreePool (&snd_mempool);
904 void S_UnloadAllSounds_f (void)
908 // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
909 // So, refuse to do this if we are connected.
910 if(cls.state == ca_connected)
912 Con_Printf("snd_unloadallsounds would wreak havoc if you do that while connected!\n");
916 // stop any active sounds
919 // because the ambient sounds will be freed, clear the pointers
920 for (i = 0;i < (int)sizeof (ambient_sfxs) / (int)sizeof (ambient_sfxs[0]);i++)
921 ambient_sfxs[i] = NULL;
923 // now free all sounds
924 while (known_sfx != NULL)
925 S_FreeSfx (known_sfx, true);
934 sfx_t *S_FindName (const char *name)
938 if (!snd_initialized.integer)
941 if (strlen (name) >= sizeof (sfx->name))
943 Con_Printf ("S_FindName: sound name too long (%s)\n", name);
947 // Look for this sound in the list of known sfx
948 // TODO: hash table search?
949 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
950 if(!strcmp (sfx->name, name))
953 // Add a sfx_t struct for this sound
954 sfx = (sfx_t *)Mem_Alloc (snd_mempool, sizeof (*sfx));
955 memset (sfx, 0, sizeof(*sfx));
956 strlcpy (sfx->name, name, sizeof (sfx->name));
957 sfx->memsize = sizeof(*sfx);
958 sfx->next = known_sfx;
970 void S_FreeSfx (sfx_t *sfx, qboolean force)
974 // Never free a locked sfx unless forced
975 if (!force && (sfx->locks > 0 || (sfx->flags & SFXFLAG_PERMANENTLOCK)))
978 if (developer_loading.integer)
979 Con_Printf ("unloading sound %s\n", sfx->name);
981 // Remove it from the list of known sfx
982 if (sfx == known_sfx)
983 known_sfx = known_sfx->next;
988 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
989 if (prev_sfx->next == sfx)
991 prev_sfx->next = sfx->next;
994 if (prev_sfx == NULL)
996 Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
1001 // Stop all channels using this sfx
1002 for (i = 0; i < total_channels; i++)
1003 if (channels[i].sfx == sfx)
1004 S_StopChannel (i, true);
1007 if (sfx->fetcher != NULL && sfx->fetcher->free != NULL)
1008 sfx->fetcher->free (sfx->fetcher_data);
1018 void S_ServerSounds (char serversound [][MAX_QPATH], unsigned int numsounds)
1024 // Start the ambient sounds and make them loop
1025 for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
1027 // Precache it if it's not done (request a lock to make sure it will never be freed)
1028 if (ambient_sfxs[i] == NULL)
1029 ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, true);
1030 if (ambient_sfxs[i] != NULL)
1032 // Add a lock to the SFX while playing. It will be
1033 // removed by S_StopAllSounds at the end of the level
1034 S_LockSfx (ambient_sfxs[i]);
1036 channels[i].sfx = ambient_sfxs[i];
1037 channels[i].flags |= CHANNELFLAG_FORCELOOP;
1038 channels[i].master_vol = 0;
1042 // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
1043 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
1044 if (sfx->flags & SFXFLAG_SERVERSOUND)
1047 sfx->flags &= ~SFXFLAG_SERVERSOUND;
1050 // Add 1 lock and the SFXFLAG_SERVERSOUND flag to each sfx in "serversound"
1051 for (i = 1; i < numsounds; i++)
1053 sfx = S_FindName (serversound[i]);
1056 // clear the FILEMISSING flag so that S_LoadSound will try again on a
1057 // previously missing file
1058 sfx->flags &= ~ SFXFLAG_FILEMISSING;
1060 sfx->flags |= SFXFLAG_SERVERSOUND;
1064 // Free all unlocked sfx
1065 for (sfx = known_sfx;sfx;sfx = sfxnext)
1067 sfxnext = sfx->next;
1068 S_FreeSfx (sfx, false);
1078 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean lock)
1082 if (!snd_initialized.integer)
1085 if (name == NULL || name[0] == 0)
1088 sfx = S_FindName (name);
1093 // clear the FILEMISSING flag so that S_LoadSound will try again on a
1094 // previously missing file
1095 sfx->flags &= ~ SFXFLAG_FILEMISSING;
1100 if (!nosound.integer && snd_precache.integer)
1101 S_LoadSound(sfx, complain);
1111 qboolean S_IsSoundPrecached (const sfx_t *sfx)
1113 return (sfx != NULL && sfx->fetcher != NULL);
1123 void S_LockSfx (sfx_t *sfx)
1132 Remove a lock from a SFX
1135 void S_UnlockSfx (sfx_t *sfx)
1146 void S_BlockSound (void)
1157 void S_UnblockSound (void)
1167 Picks a channel based on priorities, empty slots, number of channels
1170 channel_t *SND_PickChannel(int entnum, int entchannel)
1174 int first_life_left, life_left;
1177 // Check for replacement sound, or find the best one to replace
1179 first_life_left = 0x7fffffff;
1181 // entity channels try to replace the existing sound on the channel
1182 if (entchannel != 0)
1184 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1186 ch = &channels[ch_idx];
1187 if (ch->entnum == entnum && (ch->entchannel == entchannel || entchannel == -1) )
1189 // always override sound from same entity
1190 S_StopChannel (ch_idx, true);
1191 return &channels[ch_idx];
1196 // there was no channel to override, so look for the first empty one
1197 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1199 ch = &channels[ch_idx];
1202 // no sound on this channel
1203 first_to_die = ch_idx;
1207 // don't let monster sounds override player sounds
1208 if (ch->entnum == cl.viewentity && entnum != cl.viewentity)
1211 // don't override looped sounds
1212 if ((ch->flags & CHANNELFLAG_FORCELOOP) || ch->sfx->loopstart < ch->sfx->total_length)
1214 life_left = ch->sfx->total_length - ch->pos;
1216 if (life_left < first_life_left)
1218 first_life_left = life_left;
1219 first_to_die = ch_idx;
1223 if (first_to_die == -1)
1226 return &channels[first_to_die];
1233 Spatializes a channel
1236 extern cvar_t cl_gameplayfix_soundsmovewithentities;
1237 void SND_Spatialize(channel_t *ch, qboolean isstatic)
1241 vec_t dist, mastervol, intensity, vol;
1244 // update sound origin if we know about the entity
1245 if (ch->entnum > 0 && cls.state == ca_connected && cl_gameplayfix_soundsmovewithentities.integer)
1247 if (ch->entnum >= 32768)
1249 // TODO: sounds that follow CSQC entities?
1251 else if (cl.entities[ch->entnum].state_current.active)
1253 //Con_Printf("-- entnum %i origin %f %f %f neworigin %f %f %f\n", ch->entnum, ch->origin[0], ch->origin[1], ch->origin[2], cl.entities[ch->entnum].state_current.origin[0], cl.entities[ch->entnum].state_current.origin[1], cl.entities[ch->entnum].state_current.origin[2]);
1254 VectorCopy(cl.entities[ch->entnum].state_current.origin, ch->origin);
1255 if (cl.entities[ch->entnum].state_current.modelindex && cl.model_precache[cl.entities[ch->entnum].state_current.modelindex] && cl.model_precache[cl.entities[ch->entnum].state_current.modelindex]->soundfromcenter)
1256 VectorMAMAM(1.0f, ch->origin, 0.5f, cl.model_precache[cl.entities[ch->entnum].state_current.modelindex]->normalmins, 0.5f, cl.model_precache[cl.entities[ch->entnum].state_current.modelindex]->normalmaxs, ch->origin);
1260 mastervol = ch->master_vol;
1262 // Adjust volume of static sounds
1264 mastervol *= snd_staticvolume.value;
1265 else if(!(ch->flags & CHANNELFLAG_FULLVOLUME)) // same as SND_PaintChannel uses
1267 if(ch->entnum >= 32768)
1269 switch(ch->entchannel)
1271 case 0: mastervol *= snd_csqcchannel0volume.value; break;
1272 case 1: mastervol *= snd_csqcchannel1volume.value; break;
1273 case 2: mastervol *= snd_csqcchannel2volume.value; break;
1274 case 3: mastervol *= snd_csqcchannel3volume.value; break;
1275 case 4: mastervol *= snd_csqcchannel4volume.value; break;
1276 case 5: mastervol *= snd_csqcchannel5volume.value; break;
1277 case 6: mastervol *= snd_csqcchannel6volume.value; break;
1278 case 7: mastervol *= snd_csqcchannel7volume.value; break;
1282 else if(ch->entnum == 0)
1284 switch(ch->entchannel)
1286 case 0: mastervol *= snd_worldchannel0volume.value; break;
1287 case 1: mastervol *= snd_worldchannel1volume.value; break;
1288 case 2: mastervol *= snd_worldchannel2volume.value; break;
1289 case 3: mastervol *= snd_worldchannel3volume.value; break;
1290 case 4: mastervol *= snd_worldchannel4volume.value; break;
1291 case 5: mastervol *= snd_worldchannel5volume.value; break;
1292 case 6: mastervol *= snd_worldchannel6volume.value; break;
1293 case 7: mastervol *= snd_worldchannel7volume.value; break;
1297 else if(ch->entnum > 0 && ch->entnum <= cl.maxclients)
1299 switch(ch->entchannel)
1301 case 0: mastervol *= snd_playerchannel0volume.value; break;
1302 case 1: mastervol *= snd_playerchannel1volume.value; break;
1303 case 2: mastervol *= snd_playerchannel2volume.value; break;
1304 case 3: mastervol *= snd_playerchannel3volume.value; break;
1305 case 4: mastervol *= snd_playerchannel4volume.value; break;
1306 case 5: mastervol *= snd_playerchannel5volume.value; break;
1307 case 6: mastervol *= snd_playerchannel6volume.value; break;
1308 case 7: mastervol *= snd_playerchannel7volume.value; break;
1314 switch(ch->entchannel)
1316 case 0: mastervol *= snd_entchannel0volume.value; break;
1317 case 1: mastervol *= snd_entchannel1volume.value; break;
1318 case 2: mastervol *= snd_entchannel2volume.value; break;
1319 case 3: mastervol *= snd_entchannel3volume.value; break;
1320 case 4: mastervol *= snd_entchannel4volume.value; break;
1321 case 5: mastervol *= snd_entchannel5volume.value; break;
1322 case 6: mastervol *= snd_entchannel6volume.value; break;
1323 case 7: mastervol *= snd_entchannel7volume.value; break;
1329 // anything coming from the view entity will always be full volume
1330 // LordHavoc: make sounds with ATTN_NONE have no spatialization
1331 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
1333 for (i = 0;i < SND_LISTENERS;i++)
1335 vol = mastervol * snd_speakerlayout.listeners[i].ambientvolume;
1336 ch->listener_volume[i] = (int)bound(0, vol, 255);
1341 // calculate stereo seperation and distance attenuation
1342 VectorSubtract(listener_origin, ch->origin, source_vec);
1343 dist = VectorLength(source_vec);
1344 intensity = mastervol * (1.0 - dist * ch->dist_mult);
1347 for (i = 0;i < SND_LISTENERS;i++)
1349 Matrix4x4_Transform(&listener_matrix[i], ch->origin, source_vec);
1350 VectorNormalize(source_vec);
1352 switch(spatialmethod)
1356 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1358 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1359 VectorScale(source_vec, f, source_vec);
1362 f = spatialmin + spatialdiff * bound(0, (pow(dist, spatialpower) - spatialoffset) * spatialfactor, 1);
1363 VectorScale(source_vec, f, source_vec);
1365 case SPATIAL_THRESH:
1366 f = spatialmin + spatialdiff * (dist < spatialoffset);
1367 VectorScale(source_vec, f, source_vec);
1374 vol = intensity * max(0, source_vec[0] * snd_speakerlayout.listeners[i].dotscale + snd_speakerlayout.listeners[i].dotbias);
1375 ch->listener_volume[i] = (int)bound(0, vol, 255);
1379 for (i = 0;i < SND_LISTENERS;i++)
1380 ch->listener_volume[i] = 0;
1385 // =======================================================================
1386 // Start a sound effect
1387 // =======================================================================
1389 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
1391 // Initialize the channel
1392 // We MUST set sfx LAST because otherwise we could crash a threaded mixer
1393 // (otherwise we'd have to call SndSys_LockRenderBuffer here)
1394 memset (target_chan, 0, sizeof (*target_chan));
1395 VectorCopy (origin, target_chan->origin);
1396 target_chan->flags = flags;
1397 target_chan->pos = 0; // start of the sound
1399 // If it's a static sound
1402 if (sfx->loopstart >= sfx->total_length)
1403 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
1404 target_chan->dist_mult = attenuation / (64.0f * snd_soundradius.value);
1407 target_chan->dist_mult = attenuation / snd_soundradius.value;
1409 // Lock the SFX during play
1412 // finally, set the sfx pointer, so the channel becomes valid for playback
1413 // and will be noticed by the mixer
1414 target_chan->sfx = sfx;
1416 // we have to set the channel volume AFTER the sfx because the function
1417 // needs it for replaygain support
1418 S_SetChannelVolume(target_chan - channels, fvol);
1422 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1424 channel_t *target_chan, *check;
1427 if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1430 if (sfx->fetcher == NULL)
1433 // Pick a channel to play on
1434 target_chan = SND_PickChannel(entnum, entchannel);
1438 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
1439 target_chan->entnum = entnum;
1440 target_chan->entchannel = entchannel;
1442 SND_Spatialize(target_chan, false);
1444 // if an identical sound has also been started this frame, offset the pos
1445 // a bit to keep it from just making the first one louder
1446 check = &channels[NUM_AMBIENTS];
1447 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
1449 if (check == target_chan)
1451 if (check->sfx == sfx && !check->pos)
1453 // use negative pos offset to delay this sound effect
1454 target_chan->pos += (int)lhrandom(0, -0.1 * snd_renderbuffer->format.speed);
1459 return (target_chan - channels);
1462 void S_StopChannel (unsigned int channel_ind, qboolean lockmutex)
1466 if (channel_ind >= total_channels)
1469 ch = &channels[channel_ind];
1470 if (ch->sfx != NULL)
1472 sfx_t *sfx = ch->sfx;
1474 // we have to lock an audio mutex to prevent crashes if an audio mixer
1475 // thread is currently mixing this channel
1476 // the SndSys_LockRenderBuffer function uses such a mutex in
1477 // threaded sound backends
1479 SndSys_LockRenderBuffer();
1480 if (sfx->fetcher != NULL)
1482 snd_fetcher_endsb_t fetcher_endsb = sfx->fetcher->endsb;
1483 if (fetcher_endsb != NULL)
1484 fetcher_endsb (ch->fetcher_data);
1487 // Remove the lock it holds
1490 ch->fetcher_data = NULL;
1493 SndSys_UnlockRenderBuffer();
1498 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
1500 if (ch_ind >= total_channels)
1503 if (flag != CHANNELFLAG_FORCELOOP &&
1504 flag != CHANNELFLAG_PAUSED &&
1505 flag != CHANNELFLAG_FULLVOLUME)
1509 channels[ch_ind].flags |= flag;
1511 channels[ch_ind].flags &= ~flag;
1516 void S_StopSound(int entnum, int entchannel)
1520 for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
1521 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
1523 S_StopChannel (i, true);
1528 extern void CDAudio_Stop(void);
1529 void S_StopAllSounds (void)
1533 // TOCHECK: is this test necessary?
1534 if (snd_renderbuffer == NULL)
1537 // stop CD audio because it may be using a faketrack
1540 for (i = 0; i < total_channels; i++)
1541 S_StopChannel (i, true);
1543 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
1544 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
1546 // Mute the contents of the submittion buffer
1547 if (simsound || SndSys_LockRenderBuffer ())
1552 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1553 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1554 memset(snd_renderbuffer->ring, clear, memsize);
1557 SndSys_UnlockRenderBuffer ();
1561 void S_PauseGameSounds (qboolean toggle)
1565 for (i = 0; i < total_channels; i++)
1570 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
1571 S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
1575 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
1577 sfx_t *sfx = channels[ch_ind].sfx;
1578 if(sfx->volume_peak > 0)
1580 // Replaygain support
1581 // Con_DPrintf("Setting volume on ReplayGain-enabled track... %f -> ", fvol);
1582 fvol *= sfx->volume_mult;
1583 if(fvol * sfx->volume_peak > 1)
1584 fvol = 1 / sfx->volume_peak;
1585 // Con_DPrintf("%f\n", fvol);
1587 channels[ch_ind].master_vol = (int)(fvol * 255.0f);
1596 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1598 channel_t *target_chan;
1600 if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1604 Con_Printf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
1608 if (total_channels == MAX_CHANNELS)
1610 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
1614 target_chan = &channels[total_channels++];
1615 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
1617 SND_Spatialize (target_chan, true);
1623 S_UpdateAmbientSounds
1626 void S_UpdateAmbientSounds (void)
1630 int ambient_channel;
1632 unsigned char ambientlevels[NUM_AMBIENTS];
1634 memset(ambientlevels, 0, sizeof(ambientlevels));
1635 if (cl.worldmodel && cl.worldmodel->brush.AmbientSoundLevelsForPoint)
1636 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
1638 // Calc ambient sound levels
1639 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
1641 chan = &channels[ambient_channel];
1642 if (chan->sfx == NULL || chan->sfx->fetcher == NULL)
1645 vol = (int)ambientlevels[ambient_channel];
1649 // Don't adjust volume too fast
1650 // FIXME: this rounds off to an int each frame, meaning there is little to no fade at extremely high framerates!
1651 if (cl.time > cl.oldtime)
1653 if (chan->master_vol < vol)
1655 chan->master_vol += (int)((cl.time - cl.oldtime) * ambient_fade.value);
1656 if (chan->master_vol > vol)
1657 chan->master_vol = vol;
1659 else if (chan->master_vol > vol)
1661 chan->master_vol -= (int)((cl.time - cl.oldtime) * ambient_fade.value);
1662 if (chan->master_vol < vol)
1663 chan->master_vol = vol;
1667 for (i = 0;i < SND_LISTENERS;i++)
1668 chan->listener_volume[i] = (int)(chan->master_vol * ambient_level.value * snd_speakerlayout.listeners[i].ambientvolume);
1672 static void S_PaintAndSubmit (void)
1674 unsigned int newsoundtime, paintedtime, endtime, maxtime, usedframes;
1675 int usesoundtimehack;
1676 static int soundtimehack = -1;
1677 static int oldsoundtime = 0;
1679 if (snd_renderbuffer == NULL || nosound.integer)
1682 // Update sound time
1683 snd_usethreadedmixing = false;
1684 usesoundtimehack = true;
1685 if (cls.timedemo) // SUPER NASTY HACK to mix non-realtime sound for more reliable benchmarking
1687 usesoundtimehack = 1;
1688 newsoundtime = (unsigned int)((double)cl.mtime[0] * (double)snd_renderbuffer->format.speed);
1690 else if (cls.capturevideo.soundrate && !cls.capturevideo.realtime) // SUPER NASTY HACK to record non-realtime sound
1692 usesoundtimehack = 2;
1693 newsoundtime = (unsigned int)((double)cls.capturevideo.frame * (double)snd_renderbuffer->format.speed / (double)cls.capturevideo.framerate);
1697 usesoundtimehack = 3;
1698 newsoundtime = (unsigned int)((realtime - snd_starttime) * (double)snd_renderbuffer->format.speed);
1702 snd_usethreadedmixing = snd_threaded && !cls.capturevideo.soundrate;
1703 usesoundtimehack = 0;
1704 newsoundtime = SndSys_GetSoundTime();
1706 // if the soundtimehack state changes we need to reset the soundtime
1707 if (soundtimehack != usesoundtimehack)
1709 snd_renderbuffer->startframe = snd_renderbuffer->endframe = soundtime = newsoundtime;
1711 // Mute the contents of the submission buffer
1712 if (simsound || SndSys_LockRenderBuffer ())
1717 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1718 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1719 memset(snd_renderbuffer->ring, clear, memsize);
1722 SndSys_UnlockRenderBuffer ();
1725 soundtimehack = usesoundtimehack;
1727 if (!soundtimehack && snd_blocked > 0)
1730 if (snd_usethreadedmixing)
1731 return; // the audio thread will mix its own data
1733 newsoundtime += extrasoundtime;
1734 if (newsoundtime < soundtime)
1736 if ((cls.capturevideo.soundrate != 0) != recording_sound)
1738 unsigned int additionaltime;
1740 // add some time to extrasoundtime make newsoundtime higher
1742 // The extra time must be a multiple of the render buffer size
1743 // to avoid modifying the current position in the buffer,
1744 // some modules write directly to a shared (DMA) buffer
1745 additionaltime = (soundtime - newsoundtime) + snd_renderbuffer->maxframes - 1;
1746 additionaltime -= additionaltime % snd_renderbuffer->maxframes;
1748 extrasoundtime += additionaltime;
1749 newsoundtime += additionaltime;
1750 Con_DPrintf("S_PaintAndSubmit: new extra sound time = %u\n",
1753 else if (!soundtimehack)
1754 Con_Printf("S_PaintAndSubmit: WARNING: newsoundtime < soundtime (%u < %u)\n",
1755 newsoundtime, soundtime);
1757 soundtime = newsoundtime;
1758 recording_sound = (cls.capturevideo.soundrate != 0);
1760 // Lock submitbuffer
1761 if (!simsound && !SndSys_LockRenderBuffer())
1763 // If the lock failed, stop here
1764 Con_DPrint(">> S_PaintAndSubmit: SndSys_LockRenderBuffer() failed\n");
1768 // Check to make sure that we haven't overshot
1769 paintedtime = snd_renderbuffer->endframe;
1770 if (paintedtime < soundtime)
1771 paintedtime = soundtime;
1773 // mix ahead of current position
1775 endtime = soundtime + (unsigned int)(_snd_mixahead.value * (float)snd_renderbuffer->format.speed);
1777 endtime = soundtime + (unsigned int)(max(_snd_mixahead.value * (float)snd_renderbuffer->format.speed, min(3 * (soundtime - oldsoundtime), 0.3 * (float)snd_renderbuffer->format.speed)));
1778 usedframes = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
1779 maxtime = paintedtime + snd_renderbuffer->maxframes - usedframes;
1780 endtime = min(endtime, maxtime);
1782 while (paintedtime < endtime)
1784 unsigned int startoffset;
1785 unsigned int nbframes;
1787 // see how much we can fit in the paint buffer
1788 nbframes = endtime - paintedtime;
1789 // limit to the end of the ring buffer (in case of wrapping)
1790 startoffset = paintedtime % snd_renderbuffer->maxframes;
1791 nbframes = min(nbframes, snd_renderbuffer->maxframes - startoffset);
1793 // mix into the buffer
1794 S_MixToBuffer(&snd_renderbuffer->ring[startoffset * snd_renderbuffer->format.width * snd_renderbuffer->format.channels], nbframes);
1796 paintedtime += nbframes;
1797 snd_renderbuffer->endframe = paintedtime;
1800 SndSys_UnlockRenderBuffer();
1802 // Remove outdated samples from the ring buffer, if any
1803 if (snd_renderbuffer->startframe < soundtime)
1804 snd_renderbuffer->startframe = soundtime;
1807 snd_renderbuffer->startframe = snd_renderbuffer->endframe;
1811 oldsoundtime = soundtime;
1813 cls.soundstats.latency_milliseconds = (snd_renderbuffer->endframe - snd_renderbuffer->startframe) * 1000 / snd_renderbuffer->format.speed;
1820 Called once each time through the main loop
1823 void S_Update(const matrix4x4_t *listenermatrix)
1825 unsigned int i, j, k;
1826 channel_t *ch, *combine;
1827 matrix4x4_t basematrix, rotatematrix;
1829 if (snd_renderbuffer == NULL || nosound.integer)
1833 double mindist_trans, maxdist_trans;
1835 spatialmin = snd_spatialization_min.value;
1836 spatialdiff = snd_spatialization_max.value - spatialmin;
1838 if(snd_spatialization_control.value)
1840 spatialpower = snd_spatialization_power.value;
1842 if(spatialpower == 0)
1844 spatialmethod = SPATIAL_LOG;
1845 mindist_trans = log(max(1, snd_spatialization_min_radius.value));
1846 maxdist_trans = log(max(1, snd_spatialization_max_radius.value));
1850 spatialmethod = SPATIAL_POW;
1851 mindist_trans = pow(snd_spatialization_min_radius.value, spatialpower);
1852 maxdist_trans = pow(snd_spatialization_max_radius.value, spatialpower);
1855 if(mindist_trans - maxdist_trans == 0)
1857 spatialmethod = SPATIAL_THRESH;
1858 mindist_trans = snd_spatialization_min_radius.value;
1862 spatialoffset = mindist_trans;
1863 spatialfactor = 1 / (maxdist_trans - mindist_trans);
1867 spatialmethod = SPATIAL_NONE;
1871 // If snd_swapstereo or snd_channellayout has changed, recompute the channel layout
1872 if (current_swapstereo != boolxor(snd_swapstereo.integer, v_flipped.integer) ||
1873 current_channellayout != snd_channellayout.integer)
1874 S_SetChannelLayout();
1876 Matrix4x4_Invert_Simple(&basematrix, listenermatrix);
1877 Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
1879 // calculate the current matrices
1880 for (j = 0;j < SND_LISTENERS;j++)
1882 Matrix4x4_CreateFromQuakeEntity(&rotatematrix, 0, 0, 0, 0, -snd_speakerlayout.listeners[j].yawangle, 0, 1);
1883 Matrix4x4_Concat(&listener_matrix[j], &rotatematrix, &basematrix);
1884 // I think this should now do this:
1885 // 1. create a rotation matrix for rotating by e.g. -90 degrees CCW
1886 // (note: the matrix will rotate the OBJECT, not the VIEWER, so its
1887 // angle has to be taken negative)
1888 // 2. create a transform which first rotates and moves its argument
1889 // into the player's view coordinates (using basematrix which is
1890 // an inverted "absolute" listener matrix), then applies the
1891 // rotation matrix for the ear
1892 // Isn't Matrix4x4_CreateFromQuakeEntity a bit misleading because this
1893 // does not actually refer to an entity?
1896 // update general area ambient sound sources
1897 S_UpdateAmbientSounds ();
1901 // update spatialization for static and dynamic sounds
1902 cls.soundstats.totalsounds = 0;
1903 cls.soundstats.mixedsounds = 0;
1904 ch = channels+NUM_AMBIENTS;
1905 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
1909 cls.soundstats.totalsounds++;
1911 // respatialize channel
1912 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);
1914 // try to combine static sounds with a previous channel of the same
1915 // sound effect so we don't mix five torches every frame
1916 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
1918 // no need to merge silent channels
1919 for (j = 0;j < SND_LISTENERS;j++)
1920 if (ch->listener_volume[j])
1922 if (j == SND_LISTENERS)
1924 // if the last combine chosen isn't suitable, find a new one
1925 if (!(combine && combine != ch && combine->sfx == ch->sfx))
1929 for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;j < i;j++)
1931 if (channels[j].sfx == ch->sfx)
1933 combine = channels + j;
1938 if (combine && combine != ch && combine->sfx == ch->sfx)
1940 for (j = 0;j < SND_LISTENERS;j++)
1942 combine->listener_volume[j] += ch->listener_volume[j];
1943 ch->listener_volume[j] = 0;
1947 for (k = 0;k < SND_LISTENERS;k++)
1948 if (ch->listener_volume[k])
1950 if (k < SND_LISTENERS)
1951 cls.soundstats.mixedsounds++;
1954 sound_spatialized = true;
1957 if (snd_show.integer)
1958 Con_Printf("----(%u)----\n", cls.soundstats.mixedsounds);
1963 void S_ExtraUpdate (void)
1965 if (snd_noextraupdate.integer || !sound_spatialized)
1971 qboolean S_LocalSound (const char *sound)
1976 if (!snd_initialized.integer || nosound.integer)
1979 sfx = S_PrecacheSound (sound, true, false);
1982 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1986 // Local sounds must not be freed
1987 sfx->flags |= SFXFLAG_PERMANENTLOCK;
1989 ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 0);
1993 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;