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"
28 #include "cl_collision.h"
31 #define SND_MIN_SPEED 8000
32 #define SND_MAX_SPEED 96000
33 #define SND_MIN_WIDTH 1
34 #define SND_MAX_WIDTH 2
35 #define SND_MIN_CHANNELS 1
36 #define SND_MAX_CHANNELS 8
37 #if SND_LISTENERS != 8
38 # error this data only supports up to 8 channel, update it!
41 speakerlayout_t snd_speakerlayout;
43 // Our speaker layouts are based on ALSA. They differ from those
44 // Win32 and Mac OS X APIs use when there's more than 4 channels.
45 // (rear left + rear right, and front center + LFE are swapped).
46 #define SND_SPEAKERLAYOUTS (sizeof(snd_speakerlayouts) / sizeof(snd_speakerlayouts[0]))
47 static const speakerlayout_t snd_speakerlayouts[] =
52 {0, 45, 0.2, 0.2, 0.5}, // front left
53 {1, 315, 0.2, 0.2, 0.5}, // front right
54 {2, 135, 0.2, 0.2, 0.5}, // rear left
55 {3, 225, 0.2, 0.2, 0.5}, // rear right
56 {4, 0, 0.2, 0.2, 0.5}, // front center
57 {5, 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)
58 {6, 90, 0.2, 0.2, 0.5}, // side left
59 {7, 180, 0.2, 0.2, 0.5}, // side right
65 {0, 45, 0.2, 0.2, 0.5}, // front left
66 {1, 315, 0.2, 0.2, 0.5}, // front right
67 {2, 135, 0.2, 0.2, 0.5}, // rear left
68 {3, 225, 0.2, 0.2, 0.5}, // rear right
69 {4, 0, 0.2, 0.2, 0.5}, // front center
70 {5, 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)
76 // these systems sometimes have a subwoofer as well, but it has no
80 {0, 45, 0.3, 0.3, 0.8}, // front left
81 {1, 315, 0.3, 0.3, 0.8}, // front right
82 {2, 135, 0.3, 0.3, 0.8}, // rear left
83 {3, 225, 0.3, 0.3, 0.8}, // rear right
91 // these systems sometimes have a subwoofer as well, but it has no
95 {0, 90, 0.5, 0.5, 1}, // side left
96 {1, 270, 0.5, 0.5, 1}, // side right
108 {0, 0, 0, 1, 1}, // center
121 // =======================================================================
122 // Internal sound data & structures
123 // =======================================================================
125 channel_t channels[MAX_CHANNELS];
126 unsigned int total_channels;
128 snd_ringbuffer_t *snd_renderbuffer = NULL;
129 static unsigned int soundtime = 0;
130 static unsigned int oldpaintedtime = 0;
131 static unsigned int extrasoundtime = 0;
132 static double snd_starttime = 0.0;
133 qboolean snd_threaded = false;
134 qboolean snd_usethreadedmixing = false;
136 vec3_t listener_origin;
137 matrix4x4_t listener_basematrix;
138 static unsigned char *listener_pvs = NULL;
139 static int listener_pvsbytes = 0;
140 matrix4x4_t listener_matrix[SND_LISTENERS];
141 mempool_t *snd_mempool;
143 // Linked list of known sfx
144 static sfx_t *known_sfx = NULL;
146 static qboolean sound_spatialized = false;
148 qboolean simsound = false;
150 static qboolean recording_sound = false;
153 static int current_swapstereo = false;
154 static int current_channellayout = SND_CHANNELLAYOUT_AUTO;
155 static int current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
157 static float spatialpower, spatialmin, spatialdiff, spatialoffset, spatialfactor;
158 typedef enum { SPATIAL_NONE, SPATIAL_LOG, SPATIAL_POW, SPATIAL_THRESH } spatialmethod_t;
159 spatialmethod_t spatialmethod;
161 // Cvars declared in sound.h (part of the sound API)
162 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1", "volume of background music (such as CD music or replacement files such as sound/cdtracks/track002.ogg)"};
163 cvar_t mastervolume = {CVAR_SAVE, "mastervolume", "0.7", "master volume"};
164 cvar_t volume = {CVAR_SAVE, "volume", "0.7", "volume of sound effects"};
165 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0", "indicates the sound subsystem is active"};
166 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1", "volume of ambient sound effects (such as swampy sounds at the start of e1m2)"};
167 cvar_t snd_soundradius = {CVAR_SAVE, "snd_soundradius", "1200", "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)"};
168 cvar_t snd_spatialization_min_radius = {CVAR_SAVE, "snd_spatialization_min_radius", "10000", "use minimum spatialization above to this radius"};
169 cvar_t snd_spatialization_max_radius = {CVAR_SAVE, "snd_spatialization_max_radius", "100", "use maximum spatialization below this radius"};
170 cvar_t snd_spatialization_min = {CVAR_SAVE, "snd_spatialization_min", "0.70", "minimum spatializazion of sounds"};
171 cvar_t snd_spatialization_max = {CVAR_SAVE, "snd_spatialization_max", "0.95", "maximum spatialization of sounds"};
172 cvar_t snd_spatialization_power = {CVAR_SAVE, "snd_spatialization_power", "0", "exponent of the spatialization falloff curve (0: logarithmic)"};
173 cvar_t snd_spatialization_control = {CVAR_SAVE, "snd_spatialization_control", "0", "enable spatialization control (headphone friendly mode)"};
174 cvar_t snd_spatialization_prologic = {CVAR_SAVE, "snd_spatialization_prologic", "0", "use dolby prologic (I, II or IIx) encoding (snd_channels must be 2)"};
175 cvar_t snd_spatialization_prologic_frontangle = {CVAR_SAVE, "snd_spatialization_prologic_frontangle", "30", "the angle between the front speakers and the center speaker"};
176 cvar_t snd_spatialization_occlusion = {CVAR_SAVE, "snd_spatialization_occlusion", "1", "enable occlusion testing on spatialized sounds, which simply quiets sounds that are blocked by the world; 1 enables PVS method, 2 enables LineOfSight method, 3 enables both"};
178 // Cvars declared in snd_main.h (shared with other snd_*.c files)
179 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.15", "how much sound to mix ahead of time"};
180 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); when set to 2, streaming is performed even if this would waste memory"};
181 cvar_t snd_streaming_length = { CVAR_SAVE, "snd_streaming_length", "0", "When set, sound files are only streamed if longer than the given length in seconds"};
182 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0", "swaps left/right speakers for old ISA soundblaster cards"};
183 extern cvar_t v_flipped;
184 cvar_t snd_channellayout = {0, "snd_channellayout", "0", "channel layout. Can be 0 (auto - snd_restart needed), 1 (standard layout), or 2 (ALSA layout)"};
185 cvar_t snd_mutewhenidle = {CVAR_SAVE, "snd_mutewhenidle", "1", "whether to disable sound output when game window is inactive"};
186 cvar_t snd_entchannel0volume = {CVAR_SAVE, "snd_entchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of regular entities (DEPRECATED)"};
187 cvar_t snd_entchannel1volume = {CVAR_SAVE, "snd_entchannel1volume", "1", "volume multiplier of the 1st entity channel of regular entities (DEPRECATED)"};
188 cvar_t snd_entchannel2volume = {CVAR_SAVE, "snd_entchannel2volume", "1", "volume multiplier of the 2nd entity channel of regular entities (DEPRECATED)"};
189 cvar_t snd_entchannel3volume = {CVAR_SAVE, "snd_entchannel3volume", "1", "volume multiplier of the 3rd entity channel of regular entities (DEPRECATED)"};
190 cvar_t snd_entchannel4volume = {CVAR_SAVE, "snd_entchannel4volume", "1", "volume multiplier of the 4th entity channel of regular entities (DEPRECATED)"};
191 cvar_t snd_entchannel5volume = {CVAR_SAVE, "snd_entchannel5volume", "1", "volume multiplier of the 5th entity channel of regular entities (DEPRECATED)"};
192 cvar_t snd_entchannel6volume = {CVAR_SAVE, "snd_entchannel6volume", "1", "volume multiplier of the 6th entity channel of regular entities (DEPRECATED)"};
193 cvar_t snd_entchannel7volume = {CVAR_SAVE, "snd_entchannel7volume", "1", "volume multiplier of the 7th entity channel of regular entities (DEPRECATED)"};
194 cvar_t snd_playerchannel0volume = {CVAR_SAVE, "snd_playerchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of player entities (DEPRECATED)"};
195 cvar_t snd_playerchannel1volume = {CVAR_SAVE, "snd_playerchannel1volume", "1", "volume multiplier of the 1st entity channel of player entities (DEPRECATED)"};
196 cvar_t snd_playerchannel2volume = {CVAR_SAVE, "snd_playerchannel2volume", "1", "volume multiplier of the 2nd entity channel of player entities (DEPRECATED)"};
197 cvar_t snd_playerchannel3volume = {CVAR_SAVE, "snd_playerchannel3volume", "1", "volume multiplier of the 3rd entity channel of player entities (DEPRECATED)"};
198 cvar_t snd_playerchannel4volume = {CVAR_SAVE, "snd_playerchannel4volume", "1", "volume multiplier of the 4th entity channel of player entities (DEPRECATED)"};
199 cvar_t snd_playerchannel5volume = {CVAR_SAVE, "snd_playerchannel5volume", "1", "volume multiplier of the 5th entity channel of player entities (DEPRECATED)"};
200 cvar_t snd_playerchannel6volume = {CVAR_SAVE, "snd_playerchannel6volume", "1", "volume multiplier of the 6th entity channel of player entities (DEPRECATED)"};
201 cvar_t snd_playerchannel7volume = {CVAR_SAVE, "snd_playerchannel7volume", "1", "volume multiplier of the 7th entity channel of player entities (DEPRECATED)"};
202 cvar_t snd_worldchannel0volume = {CVAR_SAVE, "snd_worldchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of the world entity (DEPRECATED)"};
203 cvar_t snd_worldchannel1volume = {CVAR_SAVE, "snd_worldchannel1volume", "1", "volume multiplier of the 1st entity channel of the world entity (DEPRECATED)"};
204 cvar_t snd_worldchannel2volume = {CVAR_SAVE, "snd_worldchannel2volume", "1", "volume multiplier of the 2nd entity channel of the world entity (DEPRECATED)"};
205 cvar_t snd_worldchannel3volume = {CVAR_SAVE, "snd_worldchannel3volume", "1", "volume multiplier of the 3rd entity channel of the world entity (DEPRECATED)"};
206 cvar_t snd_worldchannel4volume = {CVAR_SAVE, "snd_worldchannel4volume", "1", "volume multiplier of the 4th entity channel of the world entity (DEPRECATED)"};
207 cvar_t snd_worldchannel5volume = {CVAR_SAVE, "snd_worldchannel5volume", "1", "volume multiplier of the 5th entity channel of the world entity (DEPRECATED)"};
208 cvar_t snd_worldchannel6volume = {CVAR_SAVE, "snd_worldchannel6volume", "1", "volume multiplier of the 6th entity channel of the world entity (DEPRECATED)"};
209 cvar_t snd_worldchannel7volume = {CVAR_SAVE, "snd_worldchannel7volume", "1", "volume multiplier of the 7th entity channel of the world entity (DEPRECATED)"};
210 cvar_t snd_csqcchannel0volume = {CVAR_SAVE, "snd_csqcchannel0volume", "1", "volume multiplier of the auto-allocate entity channel CSQC entities (DEPRECATED)"};
211 cvar_t snd_csqcchannel1volume = {CVAR_SAVE, "snd_csqcchannel1volume", "1", "volume multiplier of the 1st entity channel of CSQC entities (DEPRECATED)"};
212 cvar_t snd_csqcchannel2volume = {CVAR_SAVE, "snd_csqcchannel2volume", "1", "volume multiplier of the 2nd entity channel of CSQC entities (DEPRECATED)"};
213 cvar_t snd_csqcchannel3volume = {CVAR_SAVE, "snd_csqcchannel3volume", "1", "volume multiplier of the 3rd entity channel of CSQC entities (DEPRECATED)"};
214 cvar_t snd_csqcchannel4volume = {CVAR_SAVE, "snd_csqcchannel4volume", "1", "volume multiplier of the 4th entity channel of CSQC entities (DEPRECATED)"};
215 cvar_t snd_csqcchannel5volume = {CVAR_SAVE, "snd_csqcchannel5volume", "1", "volume multiplier of the 5th entity channel of CSQC entities (DEPRECATED)"};
216 cvar_t snd_csqcchannel6volume = {CVAR_SAVE, "snd_csqcchannel6volume", "1", "volume multiplier of the 6th entity channel of CSQC entities (DEPRECATED)"};
217 cvar_t snd_csqcchannel7volume = {CVAR_SAVE, "snd_csqcchannel7volume", "1", "volume multiplier of the 7th entity channel of CSQC entities (DEPRECATED)"};
218 cvar_t snd_channel0volume = {CVAR_SAVE, "snd_channel0volume", "1", "volume multiplier of the auto-allocate entity channel"};
219 cvar_t snd_channel1volume = {CVAR_SAVE, "snd_channel1volume", "1", "volume multiplier of the 1st entity channel"};
220 cvar_t snd_channel2volume = {CVAR_SAVE, "snd_channel2volume", "1", "volume multiplier of the 2nd entity channel"};
221 cvar_t snd_channel3volume = {CVAR_SAVE, "snd_channel3volume", "1", "volume multiplier of the 3rd entity channel"};
222 cvar_t snd_channel4volume = {CVAR_SAVE, "snd_channel4volume", "1", "volume multiplier of the 4th entity channel"};
223 cvar_t snd_channel5volume = {CVAR_SAVE, "snd_channel5volume", "1", "volume multiplier of the 5th entity channel"};
224 cvar_t snd_channel6volume = {CVAR_SAVE, "snd_channel6volume", "1", "volume multiplier of the 6th entity channel"};
225 cvar_t snd_channel7volume = {CVAR_SAVE, "snd_channel7volume", "1", "volume multiplier of the 7th entity channel"};
228 static cvar_t nosound = {0, "nosound", "0", "disables sound"};
229 static cvar_t snd_precache = {0, "snd_precache", "1", "loads sounds before they are used"};
230 static cvar_t ambient_level = {0, "ambient_level", "0.3", "volume of environment noises (water and wind)"};
231 static cvar_t ambient_fade = {0, "ambient_fade", "100", "rate of volume fading when moving from one environment to another"};
232 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"};
233 static cvar_t snd_show = {0, "snd_show", "0", "shows some statistics about sound mixing"};
235 // Default sound format is 48KHz, 16-bit, stereo
236 // (48KHz because a lot of onboard sound cards sucks at any other speed)
237 static cvar_t snd_speed = {CVAR_SAVE, "snd_speed", "48000", "sound output frequency, in hertz"};
238 static cvar_t snd_width = {CVAR_SAVE, "snd_width", "2", "sound output precision, in bytes (1 and 2 supported)"};
239 static cvar_t snd_channels = {CVAR_SAVE, "snd_channels", "2", "number of channels for the sound output (2 for stereo; up to 8 supported for 3D sound)"};
241 static cvar_t snd_startloopingsounds = {0, "snd_startloopingsounds", "1", "whether to start sounds that would loop (you want this to be 1); existing sounds are not affected"};
242 static cvar_t snd_startnonloopingsounds = {0, "snd_startnonloopingsounds", "1", "whether to start sounds that would not loop (you want this to be 1); existing sounds are not affected"};
245 static sfx_t* ambient_sfxs [2] = { NULL, NULL };
246 static const char* ambient_names [2] = { "sound/ambience/water1.wav", "sound/ambience/wind2.wav" };
249 // ====================================================================
251 // ====================================================================
253 void S_FreeSfx (sfx_t *sfx, qboolean force);
255 static void S_Play_Common (float fvol, float attenuation)
258 char name [MAX_QPATH];
262 while (i < Cmd_Argc ())
264 // Get the name, and appends ".wav" as an extension if there's none
265 strlcpy (name, Cmd_Argv (i), sizeof (name));
266 if (!strrchr (name, '.'))
267 strlcat (name, ".wav", sizeof (name));
270 // If we need to get the volume from the command line
273 fvol = atof (Cmd_Argv (i));
277 sfx = S_PrecacheSound (name, true, true);
280 ch_ind = S_StartSound (-1, 0, sfx, listener_origin, fvol, attenuation);
282 // Free the sfx if the file didn't exist
284 S_FreeSfx (sfx, false);
286 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
291 static void S_Play_f(void)
293 S_Play_Common (1.0f, 1.0f);
296 static void S_Play2_f(void)
298 S_Play_Common (1.0f, 0.0f);
301 static void S_PlayVol_f(void)
303 S_Play_Common (-1.0f, 0.0f);
306 static void S_SoundList_f (void)
313 for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
315 if (sfx->fetcher != NULL)
318 const snd_format_t* format;
321 format = sfx->fetcher->getfmt(sfx);
322 Con_Printf ("%c%c%c(%2db, %6s) %8i : %s\n",
323 (sfx->loopstart < sfx->total_length) ? 'L' : ' ',
324 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
325 (sfx->flags & SFXFLAG_MENUSOUND) ? 'P' : ' ',
327 (format->channels == 1) ? "mono" : "stereo",
333 Con_Printf (" ( unknown ) unloaded : %s\n", sfx->name);
335 Con_Printf("Total resident: %i\n", total);
339 void S_SoundInfo_f(void)
341 if (snd_renderbuffer == NULL)
343 Con_Print("sound system not started\n");
347 Con_Printf("%5d speakers\n", snd_renderbuffer->format.channels);
348 Con_Printf("%5d frames\n", snd_renderbuffer->maxframes);
349 Con_Printf("%5d samplebits\n", snd_renderbuffer->format.width * 8);
350 Con_Printf("%5d speed\n", snd_renderbuffer->format.speed);
351 Con_Printf("%5u total_channels\n", total_channels);
355 int S_GetSoundRate(void)
357 return snd_renderbuffer ? snd_renderbuffer->format.speed : 0;
360 int S_GetSoundChannels(void)
362 return snd_renderbuffer ? snd_renderbuffer->format.channels : 0;
366 static qboolean S_ChooseCheaperFormat (snd_format_t* format, qboolean fixed_speed, qboolean fixed_width, qboolean fixed_channels)
368 static const snd_format_t thresholds [] =
370 // speed width channels
371 { SND_MIN_SPEED, SND_MIN_WIDTH, SND_MIN_CHANNELS },
377 { SND_MAX_SPEED, SND_MAX_WIDTH, SND_MAX_CHANNELS },
379 const unsigned int nb_thresholds = sizeof(thresholds) / sizeof(thresholds[0]);
380 unsigned int speed_level, width_level, channels_level;
382 // If we have reached the minimum values, there's nothing more we can do
383 if ((format->speed == thresholds[0].speed || fixed_speed) &&
384 (format->width == thresholds[0].width || fixed_width) &&
385 (format->channels == thresholds[0].channels || fixed_channels))
388 // Check the min and max values
389 #define CHECK_BOUNDARIES(param) \
390 if (format->param < thresholds[0].param) \
392 format->param = thresholds[0].param; \
395 if (format->param > thresholds[nb_thresholds - 1].param) \
397 format->param = thresholds[nb_thresholds - 1].param; \
400 CHECK_BOUNDARIES(speed);
401 CHECK_BOUNDARIES(width);
402 CHECK_BOUNDARIES(channels);
403 #undef CHECK_BOUNDARIES
405 // Find the level of each parameter
406 #define FIND_LEVEL(param) \
408 while (param##_level < nb_thresholds - 1) \
410 if (format->param <= thresholds[param##_level].param) \
417 FIND_LEVEL(channels);
420 // Decrease the parameter with the highest level to the previous level
421 if (channels_level >= speed_level && channels_level >= width_level && !fixed_channels)
423 format->channels = thresholds[channels_level - 1].channels;
426 if (speed_level >= width_level && !fixed_speed)
428 format->speed = thresholds[speed_level - 1].speed;
432 format->width = thresholds[width_level - 1].width;
437 #define SWAP_LISTENERS(l1, l2, tmpl) { tmpl = (l1); (l1) = (l2); (l2) = tmpl; }
439 static void S_SetChannelLayout (void)
442 listener_t swaplistener;
443 listener_t *listeners;
446 for (i = 0; i < SND_SPEAKERLAYOUTS; i++)
447 if (snd_speakerlayouts[i].channels == snd_renderbuffer->format.channels)
449 if (i >= SND_SPEAKERLAYOUTS)
451 Con_Printf("S_SetChannelLayout: can't find the speaker layout for %hu channels. Defaulting to mono output\n",
452 snd_renderbuffer->format.channels);
453 i = SND_SPEAKERLAYOUTS - 1;
456 snd_speakerlayout = snd_speakerlayouts[i];
457 listeners = snd_speakerlayout.listeners;
459 // Swap the left and right channels if snd_swapstereo is set
460 if (boolxor(snd_swapstereo.integer, v_flipped.integer))
462 switch (snd_speakerlayout.channels)
465 SWAP_LISTENERS(listeners[6], listeners[7], swaplistener);
469 SWAP_LISTENERS(listeners[2], listeners[3], swaplistener);
472 SWAP_LISTENERS(listeners[0], listeners[1], swaplistener);
483 if (snd_channellayout.integer < SND_CHANNELLAYOUT_AUTO ||
484 snd_channellayout.integer > SND_CHANNELLAYOUT_ALSA)
485 Cvar_SetValueQuick (&snd_channellayout, SND_CHANNELLAYOUT_STANDARD);
487 if (snd_channellayout.integer == SND_CHANNELLAYOUT_AUTO)
489 // If we're in the sound engine initialization
490 if (current_channellayout_used == SND_CHANNELLAYOUT_AUTO)
492 layout = SND_CHANNELLAYOUT_STANDARD;
493 Cvar_SetValueQuick (&snd_channellayout, layout);
496 layout = current_channellayout_used;
499 layout = snd_channellayout.integer;
501 // Convert our layout (= ALSA) to the standard layout if necessary
502 if (snd_speakerlayout.channels == 6 || snd_speakerlayout.channels == 8)
504 if (layout == SND_CHANNELLAYOUT_STANDARD)
506 SWAP_LISTENERS(listeners[2], listeners[4], swaplistener);
507 SWAP_LISTENERS(listeners[3], listeners[5], swaplistener);
510 Con_Printf("S_SetChannelLayout: using %s speaker layout for 3D sound\n",
511 (layout == SND_CHANNELLAYOUT_ALSA) ? "ALSA" : "standard");
514 current_swapstereo = boolxor(snd_swapstereo.integer, v_flipped.integer);
515 current_channellayout = snd_channellayout.integer;
516 current_channellayout_used = layout;
520 void S_Startup (void)
522 qboolean fixed_speed, fixed_width, fixed_channels;
523 snd_format_t chosen_fmt;
524 static snd_format_t prev_render_format = {0, 0, 0};
531 if (!snd_initialized.integer)
536 fixed_channels = false;
538 // Get the starting sound format from the cvars
539 chosen_fmt.speed = snd_speed.integer;
540 chosen_fmt.width = snd_width.integer;
541 chosen_fmt.channels = snd_channels.integer;
543 // Check the environment variables to see if the player wants a particular sound format
545 _dupenv_s(&env, &envlen, "QUAKE_SOUND_CHANNELS");
547 env = getenv("QUAKE_SOUND_CHANNELS");
551 chosen_fmt.channels = atoi (env);
555 fixed_channels = true;
558 _dupenv_s(&env, &envlen, "QUAKE_SOUND_SPEED");
560 env = getenv("QUAKE_SOUND_SPEED");
564 chosen_fmt.speed = atoi (env);
571 _dupenv_s(&env, &envlen, "QUAKE_SOUND_SAMPLEBITS");
573 env = getenv("QUAKE_SOUND_SAMPLEBITS");
577 chosen_fmt.width = atoi (env) / 8;
584 // Parse the command line to see if the player wants a particular sound format
585 // COMMANDLINEOPTION: Sound: -sndquad sets sound output to 4 channel surround
586 if (COM_CheckParm ("-sndquad") != 0)
588 chosen_fmt.channels = 4;
589 fixed_channels = true;
591 // COMMANDLINEOPTION: Sound: -sndstereo sets sound output to stereo
592 else if (COM_CheckParm ("-sndstereo") != 0)
594 chosen_fmt.channels = 2;
595 fixed_channels = true;
597 // COMMANDLINEOPTION: Sound: -sndmono sets sound output to mono
598 else if (COM_CheckParm ("-sndmono") != 0)
600 chosen_fmt.channels = 1;
601 fixed_channels = true;
603 // COMMANDLINEOPTION: Sound: -sndspeed <hz> chooses sound output rate (supported values are 48000, 44100, 32000, 24000, 22050, 16000, 11025 (quake), 8000)
604 i = COM_CheckParm ("-sndspeed");
605 if (0 < i && i < com_argc - 1)
607 chosen_fmt.speed = atoi (com_argv[i + 1]);
610 // COMMANDLINEOPTION: Sound: -sndbits <bits> chooses 8 bit or 16 bit sound output
611 i = COM_CheckParm ("-sndbits");
612 if (0 < i && i < com_argc - 1)
614 chosen_fmt.width = atoi (com_argv[i + 1]) / 8;
618 // You can't change sound speed after start time (not yet supported)
619 if (prev_render_format.speed != 0)
622 if (chosen_fmt.speed != prev_render_format.speed)
624 Con_Printf("S_Startup: sound speed has changed! This is NOT supported yet. Falling back to previous speed (%u Hz)\n",
625 prev_render_format.speed);
626 chosen_fmt.speed = prev_render_format.speed;
631 if (chosen_fmt.speed < SND_MIN_SPEED)
633 chosen_fmt.speed = SND_MIN_SPEED;
636 else if (chosen_fmt.speed > SND_MAX_SPEED)
638 chosen_fmt.speed = SND_MAX_SPEED;
642 if (chosen_fmt.width < SND_MIN_WIDTH)
644 chosen_fmt.width = SND_MIN_WIDTH;
647 else if (chosen_fmt.width > SND_MAX_WIDTH)
649 chosen_fmt.width = SND_MAX_WIDTH;
653 if (chosen_fmt.channels < SND_MIN_CHANNELS)
655 chosen_fmt.channels = SND_MIN_CHANNELS;
656 fixed_channels = false;
658 else if (chosen_fmt.channels > SND_MAX_CHANNELS)
660 chosen_fmt.channels = SND_MAX_CHANNELS;
661 fixed_channels = false;
664 // create the sound buffer used for sumitting the samples to the plaform-dependent module
667 snd_format_t suggest_fmt;
673 Con_Printf("S_Startup: initializing sound output format: %dHz, %d bit, %d channels...\n",
674 chosen_fmt.speed, chosen_fmt.width * 8,
675 chosen_fmt.channels);
677 memset(&suggest_fmt, 0, sizeof(suggest_fmt));
678 accepted = SndSys_Init(&chosen_fmt, &suggest_fmt);
682 Con_Printf("S_Startup: sound output initialization FAILED\n");
684 // If the module is suggesting another one
685 if (suggest_fmt.speed != 0)
687 memcpy(&chosen_fmt, &suggest_fmt, sizeof(chosen_fmt));
688 Con_Printf (" Driver has suggested %dHz, %d bit, %d channels. Retrying...\n",
689 suggest_fmt.speed, suggest_fmt.width * 8,
690 suggest_fmt.channels);
692 // Else, try to find a less resource-demanding format
693 else if (!S_ChooseCheaperFormat (&chosen_fmt, fixed_speed, fixed_width, fixed_channels))
698 // If we haven't found a suitable format
701 Con_Print("S_Startup: SndSys_Init failed.\n");
702 sound_spatialized = false;
708 snd_renderbuffer = Snd_CreateRingBuffer(&chosen_fmt, 0, NULL);
709 Con_Print ("S_Startup: simulating sound output\n");
712 memcpy(&prev_render_format, &snd_renderbuffer->format, sizeof(prev_render_format));
713 Con_Printf("Sound format: %dHz, %d channels, %d bits per sample\n",
714 chosen_fmt.speed, chosen_fmt.channels, chosen_fmt.width * 8);
717 if (snd_speed.integer != (int)chosen_fmt.speed)
718 Cvar_SetValueQuick(&snd_speed, chosen_fmt.speed);
719 if (snd_width.integer != chosen_fmt.width)
720 Cvar_SetValueQuick(&snd_width, chosen_fmt.width);
721 if (snd_channels.integer != chosen_fmt.channels)
722 Cvar_SetValueQuick(&snd_channels, chosen_fmt.channels);
724 current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
725 S_SetChannelLayout();
727 snd_starttime = realtime;
729 // If the sound module has already run, add an extra time to make sure
730 // the sound time doesn't decrease, to not confuse playing SFXs
731 if (oldpaintedtime != 0)
733 // The extra time must be a multiple of the render buffer size
734 // to avoid modifying the current position in the buffer,
735 // some modules write directly to a shared (DMA) buffer
736 extrasoundtime = oldpaintedtime + snd_renderbuffer->maxframes - 1;
737 extrasoundtime -= extrasoundtime % snd_renderbuffer->maxframes;
738 Con_Printf("S_Startup: extra sound time = %u\n", extrasoundtime);
740 soundtime = extrasoundtime;
744 snd_renderbuffer->startframe = soundtime;
745 snd_renderbuffer->endframe = soundtime;
746 recording_sound = false;
749 void S_Shutdown(void)
751 if (snd_renderbuffer == NULL)
754 oldpaintedtime = snd_renderbuffer->endframe;
758 Mem_Free(snd_renderbuffer->ring);
759 Mem_Free(snd_renderbuffer);
760 snd_renderbuffer = NULL;
765 sound_spatialized = false;
768 void S_Restart_f(void)
770 // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
771 // So, refuse to do this if we are connected.
772 if(cls.state == ca_connected)
774 Con_Printf("snd_restart would wreak havoc if you do that while connected!\n");
789 Cvar_RegisterVariable(&volume);
790 Cvar_RegisterVariable(&bgmvolume);
791 Cvar_RegisterVariable(&mastervolume);
792 Cvar_RegisterVariable(&snd_staticvolume);
793 Cvar_RegisterVariable(&snd_entchannel0volume);
794 Cvar_RegisterVariable(&snd_entchannel1volume);
795 Cvar_RegisterVariable(&snd_entchannel2volume);
796 Cvar_RegisterVariable(&snd_entchannel3volume);
797 Cvar_RegisterVariable(&snd_entchannel4volume);
798 Cvar_RegisterVariable(&snd_entchannel5volume);
799 Cvar_RegisterVariable(&snd_entchannel6volume);
800 Cvar_RegisterVariable(&snd_entchannel7volume);
801 Cvar_RegisterVariable(&snd_worldchannel0volume);
802 Cvar_RegisterVariable(&snd_worldchannel1volume);
803 Cvar_RegisterVariable(&snd_worldchannel2volume);
804 Cvar_RegisterVariable(&snd_worldchannel3volume);
805 Cvar_RegisterVariable(&snd_worldchannel4volume);
806 Cvar_RegisterVariable(&snd_worldchannel5volume);
807 Cvar_RegisterVariable(&snd_worldchannel6volume);
808 Cvar_RegisterVariable(&snd_worldchannel7volume);
809 Cvar_RegisterVariable(&snd_playerchannel0volume);
810 Cvar_RegisterVariable(&snd_playerchannel1volume);
811 Cvar_RegisterVariable(&snd_playerchannel2volume);
812 Cvar_RegisterVariable(&snd_playerchannel3volume);
813 Cvar_RegisterVariable(&snd_playerchannel4volume);
814 Cvar_RegisterVariable(&snd_playerchannel5volume);
815 Cvar_RegisterVariable(&snd_playerchannel6volume);
816 Cvar_RegisterVariable(&snd_playerchannel7volume);
817 Cvar_RegisterVariable(&snd_csqcchannel0volume);
818 Cvar_RegisterVariable(&snd_csqcchannel1volume);
819 Cvar_RegisterVariable(&snd_csqcchannel2volume);
820 Cvar_RegisterVariable(&snd_csqcchannel3volume);
821 Cvar_RegisterVariable(&snd_csqcchannel4volume);
822 Cvar_RegisterVariable(&snd_csqcchannel5volume);
823 Cvar_RegisterVariable(&snd_csqcchannel6volume);
824 Cvar_RegisterVariable(&snd_csqcchannel7volume);
825 Cvar_RegisterVariable(&snd_channel0volume);
826 Cvar_RegisterVariable(&snd_channel1volume);
827 Cvar_RegisterVariable(&snd_channel2volume);
828 Cvar_RegisterVariable(&snd_channel3volume);
829 Cvar_RegisterVariable(&snd_channel4volume);
830 Cvar_RegisterVariable(&snd_channel5volume);
831 Cvar_RegisterVariable(&snd_channel6volume);
832 Cvar_RegisterVariable(&snd_channel7volume);
834 Cvar_RegisterVariable(&snd_spatialization_min_radius);
835 Cvar_RegisterVariable(&snd_spatialization_max_radius);
836 Cvar_RegisterVariable(&snd_spatialization_min);
837 Cvar_RegisterVariable(&snd_spatialization_max);
838 Cvar_RegisterVariable(&snd_spatialization_power);
839 Cvar_RegisterVariable(&snd_spatialization_control);
840 Cvar_RegisterVariable(&snd_spatialization_occlusion);
841 Cvar_RegisterVariable(&snd_spatialization_prologic);
842 Cvar_RegisterVariable(&snd_spatialization_prologic_frontangle);
844 Cvar_RegisterVariable(&snd_speed);
845 Cvar_RegisterVariable(&snd_width);
846 Cvar_RegisterVariable(&snd_channels);
847 Cvar_RegisterVariable(&snd_mutewhenidle);
849 Cvar_RegisterVariable(&snd_startloopingsounds);
850 Cvar_RegisterVariable(&snd_startnonloopingsounds);
852 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
853 if (COM_CheckParm("-nosound"))
855 // dummy out Play and Play2 because mods stuffcmd that
856 Cmd_AddCommand("play", Host_NoOperation_f, "does nothing because -nosound was specified");
857 Cmd_AddCommand("play2", Host_NoOperation_f, "does nothing because -nosound was specified");
861 snd_mempool = Mem_AllocPool("sound", 0, NULL);
863 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
864 if (COM_CheckParm("-simsound"))
867 Cmd_AddCommand("play", S_Play_f, "play a sound at your current location (not heard by anyone else)");
868 Cmd_AddCommand("play2", S_Play2_f, "play a sound globally throughout the level (not heard by anyone else)");
869 Cmd_AddCommand("playvol", S_PlayVol_f, "play a sound at the specified volume level at your current location (not heard by anyone else)");
870 Cmd_AddCommand("stopsound", S_StopAllSounds, "silence");
871 Cmd_AddCommand("soundlist", S_SoundList_f, "list loaded sounds");
872 Cmd_AddCommand("soundinfo", S_SoundInfo_f, "print sound system information (such as channels and speed)");
873 Cmd_AddCommand("snd_restart", S_Restart_f, "restart sound system");
874 Cmd_AddCommand("snd_unloadallsounds", S_UnloadAllSounds_f, "unload all sound files");
876 Cvar_RegisterVariable(&nosound);
877 Cvar_RegisterVariable(&snd_precache);
878 Cvar_RegisterVariable(&snd_initialized);
879 Cvar_RegisterVariable(&snd_streaming);
880 Cvar_RegisterVariable(&snd_streaming_length);
881 Cvar_RegisterVariable(&ambient_level);
882 Cvar_RegisterVariable(&ambient_fade);
883 Cvar_RegisterVariable(&snd_noextraupdate);
884 Cvar_RegisterVariable(&snd_show);
885 Cvar_RegisterVariable(&_snd_mixahead);
886 Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
887 Cvar_RegisterVariable(&snd_channellayout);
888 Cvar_RegisterVariable(&snd_soundradius);
890 Cvar_SetValueQuick(&snd_initialized, true);
894 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
895 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
898 ModPlug_OpenLibrary ();
906 Shutdown and free all resources
909 void S_Terminate (void)
912 ModPlug_CloseLibrary ();
916 while (known_sfx != NULL)
917 S_FreeSfx (known_sfx, true);
919 Cvar_SetValueQuick (&snd_initialized, false);
920 Mem_FreePool (&snd_mempool);
929 void S_UnloadAllSounds_f (void)
933 // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
934 // So, refuse to do this if we are connected.
935 if(cls.state == ca_connected)
937 Con_Printf("snd_unloadallsounds would wreak havoc if you do that while connected!\n");
941 // stop any active sounds
944 // because the ambient sounds will be freed, clear the pointers
945 for (i = 0;i < (int)sizeof (ambient_sfxs) / (int)sizeof (ambient_sfxs[0]);i++)
946 ambient_sfxs[i] = NULL;
948 // now free all sounds
949 while (known_sfx != NULL)
950 S_FreeSfx (known_sfx, true);
959 sfx_t changevolume_sfx = {""};
960 sfx_t *S_FindName (const char *name)
964 if (!snd_initialized.integer)
967 if(!strcmp(name, changevolume_sfx.name))
968 return &changevolume_sfx;
970 if (strlen (name) >= sizeof (sfx->name))
972 Con_Printf ("S_FindName: sound name too long (%s)\n", name);
976 // Look for this sound in the list of known sfx
977 // TODO: hash table search?
978 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
979 if(!strcmp (sfx->name, name))
982 // check for # in the beginning, try lookup by soundindex
983 if (name[0] == '#' && name[1])
985 int soundindex = atoi(name + 1);
986 if (soundindex > 0 && soundindex < MAX_SOUNDS)
987 if (cl.sound_precache[soundindex]->name[0])
988 return cl.sound_precache[soundindex];
991 // Add a sfx_t struct for this sound
992 sfx = (sfx_t *)Mem_Alloc (snd_mempool, sizeof (*sfx));
993 memset (sfx, 0, sizeof(*sfx));
994 strlcpy (sfx->name, name, sizeof (sfx->name));
995 sfx->memsize = sizeof(*sfx);
996 sfx->next = known_sfx;
1008 void S_FreeSfx (sfx_t *sfx, qboolean force)
1012 // Do not free a precached sound during purge
1013 if (!force && (sfx->flags & (SFXFLAG_LEVELSOUND | SFXFLAG_MENUSOUND)))
1016 if (developer_loading.integer)
1017 Con_Printf ("unloading sound %s\n", sfx->name);
1019 // Remove it from the list of known sfx
1020 if (sfx == known_sfx)
1021 known_sfx = known_sfx->next;
1026 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
1027 if (prev_sfx->next == sfx)
1029 prev_sfx->next = sfx->next;
1032 if (prev_sfx == NULL)
1034 Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
1039 // Stop all channels using this sfx
1040 for (i = 0; i < total_channels; i++)
1042 if (channels[i].sfx == sfx)
1044 Con_Printf("S_FreeSfx: stopping channel %i for sfx \"%s\"\n", i, sfx->name);
1045 S_StopChannel (i, true, false);
1050 if (sfx->fetcher != NULL && sfx->fetcher->free != NULL)
1051 sfx->fetcher->free (sfx->fetcher_data);
1061 void S_ClearUsed (void)
1067 // Start the ambient sounds and make them loop
1068 for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
1070 // Precache it if it's not done (and pass false for levelsound because these are permanent)
1071 if (ambient_sfxs[i] == NULL)
1072 ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, false);
1073 if (ambient_sfxs[i] != NULL)
1075 channels[i].sfx = ambient_sfxs[i];
1076 channels[i].sfx->flags |= SFXFLAG_MENUSOUND;
1077 channels[i].flags |= CHANNELFLAG_FORCELOOP;
1078 channels[i].master_vol = 0;
1082 // Clear SFXFLAG_LEVELSOUND flag so that sounds not precached this level will be purged
1083 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
1084 sfx->flags &= ~SFXFLAG_LEVELSOUND;
1092 void S_PurgeUnused(void)
1097 // Free all not-precached per-level sfx
1098 for (sfx = known_sfx;sfx;sfx = sfxnext)
1100 sfxnext = sfx->next;
1101 if (!(sfx->flags & (SFXFLAG_LEVELSOUND | SFXFLAG_MENUSOUND)))
1102 S_FreeSfx (sfx, false);
1112 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean levelsound)
1116 if (!snd_initialized.integer)
1119 if (name == NULL || name[0] == 0)
1122 sfx = S_FindName (name);
1127 // clear the FILEMISSING flag so that S_LoadSound will try again on a
1128 // previously missing file
1129 sfx->flags &= ~ SFXFLAG_FILEMISSING;
1131 // set a flag to indicate this has been precached for this level or permanently
1133 sfx->flags |= SFXFLAG_LEVELSOUND;
1135 sfx->flags |= SFXFLAG_MENUSOUND;
1137 if (!nosound.integer && snd_precache.integer)
1138 S_LoadSound(sfx, complain);
1149 float S_SoundLength(const char *name)
1153 if (!snd_initialized.integer)
1155 if (name == NULL || name[0] == 0)
1158 sfx = S_FindName(name);
1161 return sfx->total_length / (float) S_GetSoundRate();
1169 qboolean S_IsSoundPrecached (const sfx_t *sfx)
1171 return (sfx != NULL && sfx->fetcher != NULL) || (sfx == &changevolume_sfx);
1179 void S_BlockSound (void)
1190 void S_UnblockSound (void)
1200 Picks a channel based on priorities, empty slots, number of channels
1203 channel_t *SND_PickChannel(int entnum, int entchannel)
1207 int first_life_left, life_left;
1209 sfx_t *sfx; // use this instead of ch->sfx->, because that is volatile.
1211 // Check for replacement sound, or find the best one to replace
1213 first_life_left = 0x7fffffff;
1215 // entity channels try to replace the existing sound on the channel
1216 // channels <= 0 are autochannels
1217 if (IS_CHAN_SINGLE(entchannel))
1219 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1221 ch = &channels[ch_idx];
1222 if (ch->entnum == entnum && ch->entchannel == entchannel)
1224 // always override sound from same entity
1225 S_StopChannel (ch_idx, true, false);
1226 return &channels[ch_idx];
1231 // there was no channel to override, so look for the first empty one
1232 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1234 ch = &channels[ch_idx];
1235 sfx = ch->sfx; // fetch the volatile variable
1238 // no sound on this channel
1239 first_to_die = ch_idx;
1240 goto emptychan_found;
1243 // don't let monster sounds override player sounds
1244 if (ch->entnum == cl.viewentity && entnum != cl.viewentity)
1247 // don't override looped sounds
1248 if ((ch->flags & CHANNELFLAG_FORCELOOP) || sfx->loopstart < sfx->total_length)
1250 life_left = sfx->total_length - ch->pos;
1252 if (life_left < first_life_left)
1254 first_life_left = life_left;
1255 first_to_die = ch_idx;
1259 if (first_to_die == -1)
1262 S_StopChannel (first_to_die, true, false);
1265 return &channels[first_to_die];
1272 Spatializes a channel
1275 extern cvar_t cl_gameplayfix_soundsmovewithentities;
1276 void SND_Spatialize_WithSfx(channel_t *ch, qboolean isstatic, sfx_t *sfx)
1280 float angle_side, angle_front, angle_factor;
1281 vec_t dist, mastervol, intensity, vol;
1284 // update sound origin if we know about the entity
1285 if (ch->entnum > 0 && cls.state == ca_connected && cl_gameplayfix_soundsmovewithentities.integer)
1287 if (ch->entnum >= MAX_EDICTS)
1289 //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]);
1291 if (ch->entnum > MAX_EDICTS)
1292 if (!CL_VM_GetEntitySoundOrigin(ch->entnum, ch->origin))
1293 ch->entnum = MAX_EDICTS; // entity was removed, disown sound
1295 else if (cl.entities[ch->entnum].state_current.active)
1298 //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]);
1299 model = CL_GetModelByIndex(cl.entities[ch->entnum].state_current.modelindex);
1300 if (model && model->soundfromcenter)
1301 VectorMAM(0.5f, cl.entities[ch->entnum].render.mins, 0.5f, cl.entities[ch->entnum].render.maxs, ch->origin);
1303 Matrix4x4_OriginFromMatrix(&cl.entities[ch->entnum].render.matrix, ch->origin);
1307 mastervol = ch->master_vol;
1309 // Adjust volume of static sounds
1311 mastervol *= snd_staticvolume.value;
1312 else if(!(ch->flags & CHANNELFLAG_FULLVOLUME)) // same as SND_PaintChannel uses
1314 // old legacy separated cvars
1315 if(ch->entnum >= MAX_EDICTS)
1317 switch(ch->entchannel)
1319 case 0: mastervol *= snd_csqcchannel0volume.value; break;
1320 case 1: mastervol *= snd_csqcchannel1volume.value; break;
1321 case 2: mastervol *= snd_csqcchannel2volume.value; break;
1322 case 3: mastervol *= snd_csqcchannel3volume.value; break;
1323 case 4: mastervol *= snd_csqcchannel4volume.value; break;
1324 case 5: mastervol *= snd_csqcchannel5volume.value; break;
1325 case 6: mastervol *= snd_csqcchannel6volume.value; break;
1326 case 7: mastervol *= snd_csqcchannel7volume.value; break;
1330 else if(ch->entnum == 0)
1332 switch(ch->entchannel)
1334 case 0: mastervol *= snd_worldchannel0volume.value; break;
1335 case 1: mastervol *= snd_worldchannel1volume.value; break;
1336 case 2: mastervol *= snd_worldchannel2volume.value; break;
1337 case 3: mastervol *= snd_worldchannel3volume.value; break;
1338 case 4: mastervol *= snd_worldchannel4volume.value; break;
1339 case 5: mastervol *= snd_worldchannel5volume.value; break;
1340 case 6: mastervol *= snd_worldchannel6volume.value; break;
1341 case 7: mastervol *= snd_worldchannel7volume.value; break;
1345 else if(ch->entnum > 0 && ch->entnum <= cl.maxclients)
1347 switch(ch->entchannel)
1349 case 0: mastervol *= snd_playerchannel0volume.value; break;
1350 case 1: mastervol *= snd_playerchannel1volume.value; break;
1351 case 2: mastervol *= snd_playerchannel2volume.value; break;
1352 case 3: mastervol *= snd_playerchannel3volume.value; break;
1353 case 4: mastervol *= snd_playerchannel4volume.value; break;
1354 case 5: mastervol *= snd_playerchannel5volume.value; break;
1355 case 6: mastervol *= snd_playerchannel6volume.value; break;
1356 case 7: mastervol *= snd_playerchannel7volume.value; break;
1362 switch(ch->entchannel)
1364 case 0: mastervol *= snd_entchannel0volume.value; break;
1365 case 1: mastervol *= snd_entchannel1volume.value; break;
1366 case 2: mastervol *= snd_entchannel2volume.value; break;
1367 case 3: mastervol *= snd_entchannel3volume.value; break;
1368 case 4: mastervol *= snd_entchannel4volume.value; break;
1369 case 5: mastervol *= snd_entchannel5volume.value; break;
1370 case 6: mastervol *= snd_entchannel6volume.value; break;
1371 case 7: mastervol *= snd_entchannel7volume.value; break;
1376 switch(ch->entchannel)
1378 case 0: mastervol *= snd_channel0volume.value; break;
1379 case 1: mastervol *= snd_channel1volume.value; break;
1380 case 2: mastervol *= snd_channel2volume.value; break;
1381 case 3: mastervol *= snd_channel3volume.value; break;
1382 case 4: mastervol *= snd_channel4volume.value; break;
1383 case 5: mastervol *= snd_channel5volume.value; break;
1384 case 6: mastervol *= snd_channel6volume.value; break;
1385 case 7: mastervol *= snd_channel7volume.value; break;
1386 default: mastervol *= Cvar_VariableValueOr(va("snd_channel%dvolume", CHAN_ENGINE2CVAR(ch->entchannel)), 1.0); break;
1390 // If this channel does not manage its own volume (like CD tracks)
1391 if (!(ch->flags & CHANNELFLAG_FULLVOLUME))
1392 mastervol *= volume.value;
1394 // clamp HERE to allow to go at most 10dB past mastervolume (before clamping), when mastervolume < -10dB (so relative volumes don't get too messy)
1395 mastervol = bound(0, mastervol, 655360);
1397 // always apply "master"
1398 mastervol *= mastervolume.value;
1400 // add in ReplayGain very late; prevent clipping when close
1402 if(sfx->volume_peak > 0)
1404 // Replaygain support
1405 // Con_DPrintf("Setting volume on ReplayGain-enabled track... %f -> ", fvol);
1406 mastervol *= sfx->volume_mult;
1407 if(mastervol * sfx->volume_peak > 65536)
1408 mastervol = 65536 / sfx->volume_peak;
1409 // Con_DPrintf("%f\n", fvol);
1412 // clamp HERE to keep relative volumes of the channels correct
1413 mastervol = bound(0, mastervol, 65536);
1415 // anything coming from the view entity will always be full volume
1416 // LordHavoc: make sounds with ATTN_NONE have no spatialization
1417 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
1419 ch->prologic_invert = 1;
1420 if (snd_spatialization_prologic.integer != 0)
1422 vol = mastervol * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5);
1423 ch->listener_volume[0] = (int)bound(0, vol, 65536);
1424 vol = mastervol * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5);
1425 ch->listener_volume[1] = (int)bound(0, vol, 65536);
1426 for (i = 2;i < SND_LISTENERS;i++)
1427 ch->listener_volume[i] = 0;
1431 for (i = 0;i < SND_LISTENERS;i++)
1433 vol = mastervol * snd_speakerlayout.listeners[i].ambientvolume;
1434 ch->listener_volume[i] = (int)bound(0, vol, 65536);
1440 // calculate stereo seperation and distance attenuation
1441 VectorSubtract(listener_origin, ch->origin, source_vec);
1442 dist = VectorLength(source_vec);
1443 intensity = mastervol * (1.0 - dist * ch->dist_mult);
1446 qboolean occluded = false;
1447 if (snd_spatialization_occlusion.integer)
1449 if(snd_spatialization_occlusion.integer & 1)
1452 int cluster = cl.worldmodel->brush.PointInLeaf(cl.worldmodel, ch->origin)->clusterindex;
1453 if(cluster >= 0 && cluster < 8 * listener_pvsbytes && !CHECKPVSBIT(listener_pvs, cluster))
1457 if(snd_spatialization_occlusion.integer & 2)
1459 if(cl.worldmodel && cl.worldmodel->brush.TraceLineOfSight && !cl.worldmodel->brush.TraceLineOfSight(cl.worldmodel, listener_origin, ch->origin))
1465 ch->prologic_invert = 1;
1466 if (snd_spatialization_prologic.integer != 0)
1472 Matrix4x4_Transform(&listener_basematrix, ch->origin, source_vec);
1473 VectorNormalize(source_vec);
1475 switch(spatialmethod)
1479 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1481 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1482 VectorScale(source_vec, f, source_vec);
1485 f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1486 f = spatialmin + spatialdiff * bound(0, f, 1);
1487 VectorScale(source_vec, f, source_vec);
1489 case SPATIAL_THRESH:
1490 f = spatialmin + spatialdiff * (dist < spatialoffset);
1491 VectorScale(source_vec, f, source_vec);
1498 // the z axis needs to be removed and normalized because otherwise the volume would get lower as the sound source goes higher or lower then normal
1500 VectorNormalize(source_vec);
1501 angle_side = acos(source_vec[0]) / M_PI * 180; // angle between 0 and 180 degrees
1502 angle_front = asin(source_vec[1]) / M_PI * 180; // angle between -90 and 90 degrees
1503 if (angle_side > snd_spatialization_prologic_frontangle.value)
1505 ch->prologic_invert = -1; // this will cause the right channel to do a 180 degrees phase shift (turning the sound wave upside down),
1506 // but the best would be 90 degrees phase shift left and a -90 degrees phase shift right.
1507 angle_factor = (angle_side - snd_spatialization_prologic_frontangle.value) / (360 - 2 * snd_spatialization_prologic_frontangle.value);
1508 // angle_factor is between 0 and 1 and represents the angle range from the front left, to all the surround speakers (amount may vary,
1509 // 1 in prologic I 2 in prologic II and 3 or 4 in prologic IIx) to the front right speaker.
1510 if (angle_front > 0)
1511 angle_factor = 1 - angle_factor;
1514 angle_factor = angle_front / snd_spatialization_prologic_frontangle.value / 2.0 + 0.5;
1515 //angle_factor is between 0 and 1 and represents the angle range from the front left to the center to the front right speaker
1518 vol = intensity * sqrt(angle_factor);
1519 ch->listener_volume[0] = (int)bound(0, vol, 65536);
1520 vol = intensity * sqrt(1 - angle_factor);
1521 ch->listener_volume[1] = (int)bound(0, vol, 65536);
1522 for (i = 2;i < SND_LISTENERS;i++)
1523 ch->listener_volume[i] = 0;
1527 for (i = 0;i < SND_LISTENERS;i++)
1529 Matrix4x4_Transform(&listener_matrix[i], ch->origin, source_vec);
1530 VectorNormalize(source_vec);
1532 switch(spatialmethod)
1536 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1538 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1539 VectorScale(source_vec, f, source_vec);
1542 f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1543 f = spatialmin + spatialdiff * bound(0, f, 1);
1544 VectorScale(source_vec, f, source_vec);
1546 case SPATIAL_THRESH:
1547 f = spatialmin + spatialdiff * (dist < spatialoffset);
1548 VectorScale(source_vec, f, source_vec);
1555 vol = intensity * max(0, source_vec[0] * snd_speakerlayout.listeners[i].dotscale + snd_speakerlayout.listeners[i].dotbias);
1557 ch->listener_volume[i] = (int)bound(0, vol, 65536);
1562 for (i = 0;i < SND_LISTENERS;i++)
1563 ch->listener_volume[i] = 0;
1566 void SND_Spatialize(channel_t *ch, qboolean isstatic)
1568 sfx_t *sfx = ch->sfx;
1569 SND_Spatialize_WithSfx(ch, isstatic, sfx);
1573 // =======================================================================
1574 // Start a sound effect
1575 // =======================================================================
1577 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic, int entnum, int entchannel, int startpos)
1581 Con_Printf("S_PlaySfxOnChannel called with NULL??\n");
1585 if ((sfx->loopstart < sfx->total_length) || (flags & CHANNELFLAG_FORCELOOP))
1587 if(!snd_startloopingsounds.integer)
1592 if(!snd_startnonloopingsounds.integer)
1596 // Initialize the channel
1597 // a crash was reported on an in-use channel, so check here...
1598 if (target_chan->sfx)
1600 int channelindex = (int)(target_chan - channels);
1601 Con_Printf("S_PlaySfxOnChannel(%s): channel %i already in use?? Clearing.\n", sfx->name, channelindex);
1602 S_StopChannel (channelindex, true, false);
1604 // We MUST set sfx LAST because otherwise we could crash a threaded mixer
1605 // (otherwise we'd have to call SndSys_LockRenderBuffer here)
1606 memset (target_chan, 0, sizeof (*target_chan));
1607 VectorCopy (origin, target_chan->origin);
1608 target_chan->flags = flags;
1609 target_chan->pos = startpos; // start of the sound
1610 target_chan->entnum = entnum;
1611 target_chan->entchannel = entchannel;
1613 // If it's a static sound
1616 if (sfx->loopstart >= sfx->total_length && (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEWORLD))
1617 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
1618 target_chan->dist_mult = attenuation / (64.0f * snd_soundradius.value);
1621 target_chan->dist_mult = attenuation / snd_soundradius.value;
1623 // set the listener volumes
1624 S_SetChannelVolume(target_chan - channels, fvol);
1625 SND_Spatialize_WithSfx (target_chan, isstatic, sfx);
1627 // finally, set the sfx pointer, so the channel becomes valid for playback
1628 // and will be noticed by the mixer
1629 target_chan->sfx = sfx;
1633 int S_StartSound_StartPosition_Flags (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation, float startposition, int flags)
1635 channel_t *target_chan, *check, *ch;
1636 int ch_idx, startpos;
1638 if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1641 if(sfx == &changevolume_sfx)
1643 if (!IS_CHAN_SINGLE(entchannel))
1645 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1647 ch = &channels[ch_idx];
1648 if (ch->entnum == entnum && ch->entchannel == entchannel)
1650 S_SetChannelVolume(ch_idx, fvol);
1651 ch->dist_mult = attenuation / snd_soundradius.value;
1652 SND_Spatialize(ch, false);
1659 if (sfx->fetcher == NULL)
1662 // Pick a channel to play on
1663 target_chan = SND_PickChannel(entnum, entchannel);
1667 // if an identical sound has also been started this frame, offset the pos
1668 // a bit to keep it from just making the first one louder
1669 check = &channels[NUM_AMBIENTS];
1670 startpos = (int)(startposition * S_GetSoundRate());
1673 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
1675 if (check == target_chan)
1677 if (check->sfx == sfx && check->pos == 0)
1679 // use negative pos offset to delay this sound effect
1680 startpos = (int)lhrandom(0, -0.1 * snd_renderbuffer->format.speed);
1686 S_PlaySfxOnChannel (sfx, target_chan, flags, origin, fvol, attenuation, false, entnum, entchannel, startpos);
1688 return (target_chan - channels);
1691 int S_StartSound_StartPosition (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation, float startposition)
1693 return S_StartSound_StartPosition_Flags(entnum, entchannel, sfx, origin, fvol, attenuation, startposition, CHANNELFLAG_NONE);
1696 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1698 return S_StartSound_StartPosition(entnum, entchannel, sfx, origin, fvol, attenuation, 0);
1701 void S_StopChannel (unsigned int channel_ind, qboolean lockmutex, qboolean freesfx)
1706 if (channel_ind >= total_channels)
1709 // we have to lock an audio mutex to prevent crashes if an audio mixer
1710 // thread is currently mixing this channel
1711 // the SndSys_LockRenderBuffer function uses such a mutex in
1712 // threaded sound backends
1713 if (lockmutex && !simsound)
1714 SndSys_LockRenderBuffer();
1716 ch = &channels[channel_ind];
1718 if (ch->sfx != NULL)
1720 if (sfx->fetcher != NULL)
1722 snd_fetcher_endsb_t fetcher_endsb = sfx->fetcher->endsb;
1723 if (fetcher_endsb != NULL)
1724 fetcher_endsb (ch->fetcher_data);
1727 ch->fetcher_data = NULL;
1730 if (lockmutex && !simsound)
1731 SndSys_UnlockRenderBuffer();
1733 S_FreeSfx(sfx, true);
1737 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
1739 if (ch_ind >= total_channels)
1742 if (flag != CHANNELFLAG_FORCELOOP &&
1743 flag != CHANNELFLAG_PAUSED &&
1744 flag != CHANNELFLAG_FULLVOLUME &&
1745 flag != CHANNELFLAG_LOCALSOUND)
1749 channels[ch_ind].flags |= flag;
1751 channels[ch_ind].flags &= ~flag;
1756 void S_StopSound(int entnum, int entchannel)
1760 for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
1761 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
1763 S_StopChannel (i, true, false);
1768 extern void CDAudio_Stop(void);
1769 void S_StopAllSounds (void)
1773 // TOCHECK: is this test necessary?
1774 if (snd_renderbuffer == NULL)
1777 // stop CD audio because it may be using a faketrack
1780 if (simsound || SndSys_LockRenderBuffer ())
1785 for (i = 0; i < total_channels; i++)
1786 if (channels[i].sfx)
1787 S_StopChannel (i, false, false);
1789 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
1790 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
1792 // Mute the contents of the submittion buffer
1793 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1794 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1795 memset(snd_renderbuffer->ring, clear, memsize);
1798 SndSys_UnlockRenderBuffer ();
1802 void S_PauseGameSounds (qboolean toggle)
1806 for (i = 0; i < total_channels; i++)
1811 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
1812 S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
1816 void S_SetChannelVolume(unsigned int ch_ind, float fvol)
1818 channels[ch_ind].master_vol = (int)(fvol * 65536.0f);
1821 float S_GetChannelPosition (unsigned int ch_ind)
1823 // note: this is NOT accurate yet
1825 channel_t *ch = &channels[ch_ind];
1826 sfx_t *sfx = ch->sfx;
1832 if(!snd_usethreadedmixing)
1833 s += _snd_mixahead.value * S_GetSoundRate();
1835 return (s % sfx->total_length) / (float) S_GetSoundRate();
1838 float S_GetEntChannelPosition(int entnum, int entchannel)
1843 for (i = 0; i < total_channels; i++)
1846 if (ch->entnum == entnum && ch->entchannel == entchannel)
1847 return S_GetChannelPosition(i);
1849 return -1; // no playing sound in this channel
1857 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1859 channel_t *target_chan;
1861 if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1865 Con_Printf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
1869 if (total_channels == MAX_CHANNELS)
1871 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
1875 target_chan = &channels[total_channels++];
1876 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true, 0, 0, 0);
1882 S_UpdateAmbientSounds
1885 void S_UpdateAmbientSounds (void)
1889 int ambient_channel;
1891 unsigned char ambientlevels[NUM_AMBIENTS];
1894 memset(ambientlevels, 0, sizeof(ambientlevels));
1895 if (cl.worldmodel && cl.worldmodel->brush.AmbientSoundLevelsForPoint)
1896 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
1898 // Calc ambient sound levels
1899 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
1901 chan = &channels[ambient_channel];
1902 sfx = chan->sfx; // fetch the volatile variable
1903 if (sfx == NULL || sfx->fetcher == NULL)
1906 vol = (int)ambientlevels[ambient_channel];
1911 // Don't adjust volume too fast
1912 // FIXME: this rounds off to an int each frame, meaning there is little to no fade at extremely high framerates!
1913 if (cl.time > cl.oldtime)
1915 if (chan->master_vol < vol)
1917 chan->master_vol += (int)((cl.time - cl.oldtime) * 256.0 * ambient_fade.value);
1918 if (chan->master_vol > vol)
1919 chan->master_vol = vol;
1921 else if (chan->master_vol > vol)
1923 chan->master_vol -= (int)((cl.time - cl.oldtime) * 256.0 * ambient_fade.value);
1924 if (chan->master_vol < vol)
1925 chan->master_vol = vol;
1929 if (snd_spatialization_prologic.integer != 0)
1931 chan->listener_volume[0] = (int)bound(0, chan->master_vol * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5), 65536);
1932 chan->listener_volume[1] = (int)bound(0, chan->master_vol * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5), 65536);
1933 for (i = 2;i < SND_LISTENERS;i++)
1934 chan->listener_volume[i] = 0;
1938 for (i = 0;i < SND_LISTENERS;i++)
1939 chan->listener_volume[i] = (int)bound(0, chan->master_vol * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[i].ambientvolume, 65536);
1944 static void S_PaintAndSubmit (void)
1946 unsigned int newsoundtime, paintedtime, endtime, maxtime, usedframes;
1947 int usesoundtimehack;
1948 static int soundtimehack = -1;
1949 static int oldsoundtime = 0;
1951 if (snd_renderbuffer == NULL || nosound.integer)
1954 // Update sound time
1955 snd_usethreadedmixing = false;
1956 usesoundtimehack = true;
1957 if (cls.timedemo) // SUPER NASTY HACK to mix non-realtime sound for more reliable benchmarking
1959 usesoundtimehack = 1;
1960 newsoundtime = (unsigned int)((double)cl.mtime[0] * (double)snd_renderbuffer->format.speed);
1962 else if (cls.capturevideo.soundrate && !cls.capturevideo.realtime) // SUPER NASTY HACK to record non-realtime sound
1964 usesoundtimehack = 2;
1965 newsoundtime = (unsigned int)((double)cls.capturevideo.frame * (double)snd_renderbuffer->format.speed / (double)cls.capturevideo.framerate);
1969 usesoundtimehack = 3;
1970 newsoundtime = (unsigned int)((realtime - snd_starttime) * (double)snd_renderbuffer->format.speed);
1974 snd_usethreadedmixing = snd_threaded && !cls.capturevideo.soundrate;
1975 usesoundtimehack = 0;
1976 newsoundtime = SndSys_GetSoundTime();
1978 // if the soundtimehack state changes we need to reset the soundtime
1979 if (soundtimehack != usesoundtimehack)
1981 snd_renderbuffer->startframe = snd_renderbuffer->endframe = soundtime = newsoundtime;
1983 // Mute the contents of the submission buffer
1984 if (simsound || SndSys_LockRenderBuffer ())
1989 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1990 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1991 memset(snd_renderbuffer->ring, clear, memsize);
1994 SndSys_UnlockRenderBuffer ();
1997 soundtimehack = usesoundtimehack;
1999 if (!soundtimehack && snd_blocked > 0)
2002 if (snd_usethreadedmixing)
2003 return; // the audio thread will mix its own data
2005 newsoundtime += extrasoundtime;
2006 if (newsoundtime < soundtime)
2008 if ((cls.capturevideo.soundrate != 0) != recording_sound)
2010 unsigned int additionaltime;
2012 // add some time to extrasoundtime make newsoundtime higher
2014 // The extra time must be a multiple of the render buffer size
2015 // to avoid modifying the current position in the buffer,
2016 // some modules write directly to a shared (DMA) buffer
2017 additionaltime = (soundtime - newsoundtime) + snd_renderbuffer->maxframes - 1;
2018 additionaltime -= additionaltime % snd_renderbuffer->maxframes;
2020 extrasoundtime += additionaltime;
2021 newsoundtime += additionaltime;
2022 Con_DPrintf("S_PaintAndSubmit: new extra sound time = %u\n",
2025 else if (!soundtimehack)
2026 Con_Printf("S_PaintAndSubmit: WARNING: newsoundtime < soundtime (%u < %u)\n",
2027 newsoundtime, soundtime);
2029 soundtime = newsoundtime;
2030 recording_sound = (cls.capturevideo.soundrate != 0);
2032 // Lock submitbuffer
2033 if (!simsound && !SndSys_LockRenderBuffer())
2035 // If the lock failed, stop here
2036 Con_DPrint(">> S_PaintAndSubmit: SndSys_LockRenderBuffer() failed\n");
2040 // Check to make sure that we haven't overshot
2041 paintedtime = snd_renderbuffer->endframe;
2042 if (paintedtime < soundtime)
2043 paintedtime = soundtime;
2045 // mix ahead of current position
2047 endtime = soundtime + (unsigned int)(_snd_mixahead.value * (float)snd_renderbuffer->format.speed);
2049 endtime = soundtime + (unsigned int)(max(_snd_mixahead.value * (float)snd_renderbuffer->format.speed, min(3 * (soundtime - oldsoundtime), 0.3 * (float)snd_renderbuffer->format.speed)));
2050 usedframes = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
2051 maxtime = paintedtime + snd_renderbuffer->maxframes - usedframes;
2052 endtime = min(endtime, maxtime);
2054 while (paintedtime < endtime)
2056 unsigned int startoffset;
2057 unsigned int nbframes;
2059 // see how much we can fit in the paint buffer
2060 nbframes = endtime - paintedtime;
2061 // limit to the end of the ring buffer (in case of wrapping)
2062 startoffset = paintedtime % snd_renderbuffer->maxframes;
2063 nbframes = min(nbframes, snd_renderbuffer->maxframes - startoffset);
2065 // mix into the buffer
2066 S_MixToBuffer(&snd_renderbuffer->ring[startoffset * snd_renderbuffer->format.width * snd_renderbuffer->format.channels], nbframes);
2068 paintedtime += nbframes;
2069 snd_renderbuffer->endframe = paintedtime;
2072 SndSys_UnlockRenderBuffer();
2074 // Remove outdated samples from the ring buffer, if any
2075 if (snd_renderbuffer->startframe < soundtime)
2076 snd_renderbuffer->startframe = soundtime;
2079 snd_renderbuffer->startframe = snd_renderbuffer->endframe;
2083 oldsoundtime = soundtime;
2085 cls.soundstats.latency_milliseconds = (snd_renderbuffer->endframe - snd_renderbuffer->startframe) * 1000 / snd_renderbuffer->format.speed;
2086 R_TimeReport("audiomix");
2093 Called once each time through the main loop
2096 void S_Update(const matrix4x4_t *listenermatrix)
2098 unsigned int i, j, k;
2099 channel_t *ch, *combine;
2100 matrix4x4_t rotatematrix;
2102 if (snd_renderbuffer == NULL || nosound.integer)
2106 double mindist_trans, maxdist_trans;
2108 spatialmin = snd_spatialization_min.value;
2109 spatialdiff = snd_spatialization_max.value - spatialmin;
2111 if(snd_spatialization_control.value)
2113 spatialpower = snd_spatialization_power.value;
2115 if(spatialpower == 0)
2117 spatialmethod = SPATIAL_LOG;
2118 mindist_trans = log(max(1, snd_spatialization_min_radius.value));
2119 maxdist_trans = log(max(1, snd_spatialization_max_radius.value));
2123 spatialmethod = SPATIAL_POW;
2124 mindist_trans = pow(snd_spatialization_min_radius.value, spatialpower);
2125 maxdist_trans = pow(snd_spatialization_max_radius.value, spatialpower);
2128 if(mindist_trans - maxdist_trans == 0)
2130 spatialmethod = SPATIAL_THRESH;
2131 mindist_trans = snd_spatialization_min_radius.value;
2135 spatialoffset = mindist_trans;
2136 spatialfactor = 1 / (maxdist_trans - mindist_trans);
2140 spatialmethod = SPATIAL_NONE;
2144 // If snd_swapstereo or snd_channellayout has changed, recompute the channel layout
2145 if (current_swapstereo != boolxor(snd_swapstereo.integer, v_flipped.integer) ||
2146 current_channellayout != snd_channellayout.integer)
2147 S_SetChannelLayout();
2149 Matrix4x4_Invert_Simple(&listener_basematrix, listenermatrix);
2150 Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
2151 if (cl.worldmodel && cl.worldmodel->brush.FatPVS && cl.worldmodel->brush.num_pvsclusterbytes && cl.worldmodel->brush.PointInLeaf)
2153 if(cl.worldmodel->brush.num_pvsclusterbytes != listener_pvsbytes)
2156 Mem_Free(listener_pvs);
2157 listener_pvsbytes = cl.worldmodel->brush.num_pvsclusterbytes;
2158 listener_pvs = (unsigned char *) Mem_Alloc(snd_mempool, listener_pvsbytes);
2160 cl.worldmodel->brush.FatPVS(cl.worldmodel, listener_origin, 2, listener_pvs, listener_pvsbytes, 0);
2166 Mem_Free(listener_pvs);
2167 listener_pvs = NULL;
2169 listener_pvsbytes = 0;
2172 // calculate the current matrices
2173 for (j = 0;j < SND_LISTENERS;j++)
2175 Matrix4x4_CreateFromQuakeEntity(&rotatematrix, 0, 0, 0, 0, -snd_speakerlayout.listeners[j].yawangle, 0, 1);
2176 Matrix4x4_Concat(&listener_matrix[j], &rotatematrix, &listener_basematrix);
2177 // I think this should now do this:
2178 // 1. create a rotation matrix for rotating by e.g. -90 degrees CCW
2179 // (note: the matrix will rotate the OBJECT, not the VIEWER, so its
2180 // angle has to be taken negative)
2181 // 2. create a transform which first rotates and moves its argument
2182 // into the player's view coordinates (using basematrix which is
2183 // an inverted "absolute" listener matrix), then applies the
2184 // rotation matrix for the ear
2185 // Isn't Matrix4x4_CreateFromQuakeEntity a bit misleading because this
2186 // does not actually refer to an entity?
2189 // update general area ambient sound sources
2190 S_UpdateAmbientSounds ();
2193 R_TimeReport("audioprep");
2195 // update spatialization for static and dynamic sounds
2196 cls.soundstats.totalsounds = 0;
2197 cls.soundstats.mixedsounds = 0;
2198 ch = channels+NUM_AMBIENTS;
2199 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
2203 cls.soundstats.totalsounds++;
2205 // respatialize channel
2206 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);
2208 // try to combine static sounds with a previous channel of the same
2209 // sound effect so we don't mix five torches every frame
2210 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
2212 // no need to merge silent channels
2213 for (j = 0;j < SND_LISTENERS;j++)
2214 if (ch->listener_volume[j])
2216 if (j == SND_LISTENERS)
2218 // if the last combine chosen isn't suitable, find a new one
2219 if (!(combine && combine != ch && combine->sfx == ch->sfx))
2223 for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;j < i;j++)
2225 if (channels[j].sfx == ch->sfx)
2227 combine = channels + j;
2232 if (combine && combine != ch && combine->sfx == ch->sfx)
2234 for (j = 0;j < SND_LISTENERS;j++)
2236 combine->listener_volume[j] = bound(0, combine->listener_volume[j] + ch->listener_volume[j], 65536);
2237 ch->listener_volume[j] = 0;
2241 for (k = 0;k < SND_LISTENERS;k++)
2242 if (ch->listener_volume[k])
2244 if (k < SND_LISTENERS)
2245 cls.soundstats.mixedsounds++;
2247 R_TimeReport("audiospatialize");
2249 sound_spatialized = true;
2252 if (snd_show.integer)
2253 Con_Printf("----(%u)----\n", cls.soundstats.mixedsounds);
2258 void S_ExtraUpdate (void)
2260 if (snd_noextraupdate.integer || !sound_spatialized)
2266 qboolean S_LocalSound (const char *sound)
2271 if (!snd_initialized.integer || nosound.integer)
2274 sfx = S_PrecacheSound (sound, true, false);
2277 Con_Printf("S_LocalSound: can't precache %s\n", sound);
2281 // menu sounds must not be freed on level change
2282 sfx->flags |= SFXFLAG_MENUSOUND;
2284 // fun fact: in Quake 1, this used -1 "replace any entity channel",
2285 // which we no longer support anyway
2286 // changed by Black in r4297 "Changed S_LocalSound to play multiple sounds at a time."
2287 ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 0);
2291 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;