]> git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_main.c
cmd: reinstate execution of aliases with the same name as a command
[xonotic/darkplaces.git] / snd_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // snd_main.c -- main control for any streaming sound output device
21
22 #include "quakedef.h"
23
24 #include "snd_main.h"
25 #include "snd_ogg.h"
26 #ifdef USEXMP
27 #include "snd_xmp.h"
28 #endif
29 #include "csprogs.h"
30 #include "cl_collision.h"
31 #include "cdaudio.h"
32
33
34 #define SND_MIN_SPEED 8000
35 #define SND_MAX_SPEED 192000
36 #define SND_MIN_WIDTH 1
37 #define SND_MAX_WIDTH 2
38 #define SND_MIN_CHANNELS 1
39 #define SND_MAX_CHANNELS 8
40 #if SND_LISTENERS != 8
41 #       error this data only supports up to 8 channel, update it!
42 #endif
43
44 speakerlayout_t snd_speakerlayout;
45
46 // Our speaker layouts are based on ALSA. They differ from those
47 // Win32 and Mac OS X APIs use when there's more than 4 channels.
48 // (rear left + rear right, and front center + LFE are swapped).
49 #define SND_SPEAKERLAYOUTS (sizeof(snd_speakerlayouts) / sizeof(snd_speakerlayouts[0]))
50 static const speakerlayout_t snd_speakerlayouts[] =
51 {
52         {
53                 "surround71", 8,
54                 {
55                         {0, 45, 0.2f, 0.2f, 0.5f}, // front left
56                         {1, 315, 0.2f, 0.2f, 0.5f}, // front right
57                         {2, 135, 0.2f, 0.2f, 0.5f}, // rear left
58                         {3, 225, 0.2f, 0.2f, 0.5f}, // rear right
59                         {4, 0, 0.2f, 0.2f, 0.5f}, // front center
60                         {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)
61                         {6, 90, 0.2f, 0.2f, 0.5f}, // side left
62                         {7, 180, 0.2f, 0.2f, 0.5f}, // side right
63                 }
64         },
65         {
66                 "surround51", 6,
67                 {
68                         {0, 45, 0.2f, 0.2f, 0.5f}, // front left
69                         {1, 315, 0.2f, 0.2f, 0.5f}, // front right
70                         {2, 135, 0.2f, 0.2f, 0.5f}, // rear left
71                         {3, 225, 0.2f, 0.2f, 0.5f}, // rear right
72                         {4, 0, 0.2f, 0.2f, 0.5f}, // front center
73                         {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)
74                         {0, 0, 0, 0, 0},
75                         {0, 0, 0, 0, 0},
76                 }
77         },
78         {
79                 // these systems sometimes have a subwoofer as well, but it has no
80                 // channel of its own
81                 "surround40", 4,
82                 {
83                         {0, 45, 0.3f, 0.3f, 0.8f}, // front left
84                         {1, 315, 0.3f, 0.3f, 0.8f}, // front right
85                         {2, 135, 0.3f, 0.3f, 0.8f}, // rear left
86                         {3, 225, 0.3f, 0.3f, 0.8f}, // rear right
87                         {0, 0, 0, 0, 0},
88                         {0, 0, 0, 0, 0},
89                         {0, 0, 0, 0, 0},
90                         {0, 0, 0, 0, 0},
91                 }
92         },
93         {
94                 // these systems sometimes have a subwoofer as well, but it has no
95                 // channel of its own
96                 "stereo", 2,
97                 {
98                         {0, 90, 0.5f, 0.5f, 1}, // side left
99                         {1, 270, 0.5f, 0.5f, 1}, // side right
100                         {0, 0, 0, 0, 0},
101                         {0, 0, 0, 0, 0},
102                         {0, 0, 0, 0, 0},
103                         {0, 0, 0, 0, 0},
104                         {0, 0, 0, 0, 0},
105                         {0, 0, 0, 0, 0},
106                 }
107         },
108         {
109                 "mono", 1,
110                 {
111                         {0, 0, 0, 1, 1}, // center
112                         {0, 0, 0, 0, 0},
113                         {0, 0, 0, 0, 0},
114                         {0, 0, 0, 0, 0},
115                         {0, 0, 0, 0, 0},
116                         {0, 0, 0, 0, 0},
117                         {0, 0, 0, 0, 0},
118                         {0, 0, 0, 0, 0},
119                 }
120         }
121 };
122
123
124 // =======================================================================
125 // Internal sound data & structures
126 // =======================================================================
127
128 channel_t channels[MAX_CHANNELS];
129 unsigned int total_channels;
130
131 snd_ringbuffer_t *snd_renderbuffer = NULL;
132 static unsigned int soundtime = 0;
133 static unsigned int oldpaintedtime = 0;
134 static unsigned int extrasoundtime = 0;
135 static double snd_starttime = 0.0;
136 qbool snd_threaded = false;
137 qbool snd_usethreadedmixing = false;
138
139 vec3_t listener_origin;
140 matrix4x4_t listener_basematrix;
141 static unsigned char *listener_pvs = NULL;
142 static int listener_pvsbytes = 0;
143 matrix4x4_t listener_matrix[SND_LISTENERS];
144 mempool_t *snd_mempool;
145
146 // Linked list of known sfx
147 static sfx_t *known_sfx = NULL;
148
149 static qbool sound_spatialized = false;
150
151 qbool simsound = false;
152
153 #ifdef CONFIG_VIDEO_CAPTURE
154 static qbool recording_sound = false;
155 #endif
156
157 int snd_blocked = 0;
158 static int current_swapstereo = false;
159 static int current_channellayout = SND_CHANNELLAYOUT_AUTO;
160 static int current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
161
162 static float spatialpower, spatialmin, spatialdiff, spatialoffset, spatialfactor;
163 typedef enum { SPATIAL_NONE, SPATIAL_LOG, SPATIAL_POW, SPATIAL_THRESH } spatialmethod_t;
164 spatialmethod_t spatialmethod;
165
166 // Cvars declared in sound.h (part of the sound API)
167 cvar_t bgmvolume = {CF_CLIENT | CF_ARCHIVE, "bgmvolume", "1", "volume of background music (such as CD music or replacement files such as sound/cdtracks/track002.ogg)"};
168 cvar_t mastervolume = {CF_CLIENT | CF_ARCHIVE, "mastervolume", "0.7", "master volume"};
169 cvar_t volume = {CF_CLIENT | CF_ARCHIVE, "volume", "0.7", "volume of sound effects"};
170 cvar_t snd_initialized = {CF_CLIENT | CF_READONLY, "snd_initialized", "0", "indicates the sound subsystem is active"};
171 cvar_t snd_staticvolume = {CF_CLIENT | CF_ARCHIVE, "snd_staticvolume", "1", "volume of ambient sound effects (such as swampy sounds at the start of e1m2)"};
172 cvar_t snd_soundradius = {CF_CLIENT | CF_ARCHIVE, "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)"};
173 cvar_t snd_attenuation_exponent = {CF_CLIENT | CF_ARCHIVE, "snd_attenuation_exponent", "1", "Exponent of (1-radius) in sound attenuation formula"};
174 cvar_t snd_attenuation_decibel = {CF_CLIENT | CF_ARCHIVE, "snd_attenuation_decibel", "0", "Decibel sound attenuation per sound radius distance"};
175 cvar_t snd_spatialization_min_radius = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_min_radius", "10000", "use minimum spatialization above to this radius"};
176 cvar_t snd_spatialization_max_radius = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_max_radius", "100", "use maximum spatialization below this radius"};
177 cvar_t snd_spatialization_min = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_min", "0.70", "minimum spatializazion of sounds"};
178 cvar_t snd_spatialization_max = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_max", "0.95", "maximum spatialization of sounds"};
179 cvar_t snd_spatialization_power = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_power", "0", "exponent of the spatialization falloff curve (0: logarithmic)"};
180 cvar_t snd_spatialization_control = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_control", "0", "enable spatialization control (headphone friendly mode)"};
181 cvar_t snd_spatialization_prologic = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_prologic", "0", "use dolby prologic (I, II or IIx) encoding (snd_channels must be 2)"};
182 cvar_t snd_spatialization_prologic_frontangle = {CF_CLIENT | CF_ARCHIVE, "snd_spatialization_prologic_frontangle", "30", "the angle between the front speakers and the center speaker"};
183 cvar_t snd_spatialization_occlusion = {CF_CLIENT | CF_ARCHIVE, "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"};
184
185 // Cvars declared in snd_main.h (shared with other snd_*.c files)
186 cvar_t _snd_mixahead = {CF_CLIENT | CF_ARCHIVE, "_snd_mixahead", "0.15", "how much sound to mix ahead of time"};
187 cvar_t snd_streaming = {CF_CLIENT | CF_ARCHIVE, "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"};
188 cvar_t snd_streaming_length = {CF_CLIENT | CF_ARCHIVE, "snd_streaming_length", "1", "decompress sounds completely if they are less than this play time when snd_streaming is 1"};
189 cvar_t snd_swapstereo = {CF_CLIENT | CF_ARCHIVE, "snd_swapstereo", "0", "swaps left/right speakers for old ISA soundblaster cards"};
190 extern cvar_t v_flipped;
191 cvar_t snd_channellayout = {CF_CLIENT, "snd_channellayout", "0", "channel layout. Can be 0 (auto - snd_restart needed), 1 (standard layout), or 2 (ALSA layout)"};
192 cvar_t snd_mutewhenidle = {CF_CLIENT | CF_ARCHIVE, "snd_mutewhenidle", "1", "whether to disable sound output when game window is inactive"};
193 cvar_t snd_maxchannelvolume = {CF_CLIENT | CF_ARCHIVE, "snd_maxchannelvolume", "10", "maximum volume of a single sound"};
194 cvar_t snd_softclip = {CF_CLIENT | CF_ARCHIVE, "snd_softclip", "0", "Use soft-clipping. Soft-clipping can make the sound more smooth if very high volume levels are used. Enable this option if the dynamic range of the loudspeakers is very low. WARNING: This feature creates distortion and should be considered a last resort."};
195 //cvar_t snd_softclip = {CF_CLIENT | CF_ARCHIVE, "snd_softclip", "0", "Use soft-clipping (when set to 2, use it even if output is floating point). Soft-clipping can make the sound more smooth if very high volume levels are used. Enable this option if the dynamic range of the loudspeakers is very low. WARNING: This feature creates distortion and should be considered a last resort."};
196 cvar_t snd_entchannel0volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of regular entities (DEPRECATED)"};
197 cvar_t snd_entchannel1volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel1volume", "1", "volume multiplier of the 1st entity channel of regular entities (DEPRECATED)"};
198 cvar_t snd_entchannel2volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel2volume", "1", "volume multiplier of the 2nd entity channel of regular entities (DEPRECATED)"};
199 cvar_t snd_entchannel3volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel3volume", "1", "volume multiplier of the 3rd entity channel of regular entities (DEPRECATED)"};
200 cvar_t snd_entchannel4volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel4volume", "1", "volume multiplier of the 4th entity channel of regular entities (DEPRECATED)"};
201 cvar_t snd_entchannel5volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel5volume", "1", "volume multiplier of the 5th entity channel of regular entities (DEPRECATED)"};
202 cvar_t snd_entchannel6volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel6volume", "1", "volume multiplier of the 6th entity channel of regular entities (DEPRECATED)"};
203 cvar_t snd_entchannel7volume = {CF_CLIENT | CF_ARCHIVE, "snd_entchannel7volume", "1", "volume multiplier of the 7th entity channel of regular entities (DEPRECATED)"};
204 cvar_t snd_playerchannel0volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of player entities (DEPRECATED)"};
205 cvar_t snd_playerchannel1volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel1volume", "1", "volume multiplier of the 1st entity channel of player entities (DEPRECATED)"};
206 cvar_t snd_playerchannel2volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel2volume", "1", "volume multiplier of the 2nd entity channel of player entities (DEPRECATED)"};
207 cvar_t snd_playerchannel3volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel3volume", "1", "volume multiplier of the 3rd entity channel of player entities (DEPRECATED)"};
208 cvar_t snd_playerchannel4volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel4volume", "1", "volume multiplier of the 4th entity channel of player entities (DEPRECATED)"};
209 cvar_t snd_playerchannel5volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel5volume", "1", "volume multiplier of the 5th entity channel of player entities (DEPRECATED)"};
210 cvar_t snd_playerchannel6volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel6volume", "1", "volume multiplier of the 6th entity channel of player entities (DEPRECATED)"};
211 cvar_t snd_playerchannel7volume = {CF_CLIENT | CF_ARCHIVE, "snd_playerchannel7volume", "1", "volume multiplier of the 7th entity channel of player entities (DEPRECATED)"};
212 cvar_t snd_worldchannel0volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of the world entity (DEPRECATED)"};
213 cvar_t snd_worldchannel1volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel1volume", "1", "volume multiplier of the 1st entity channel of the world entity (DEPRECATED)"};
214 cvar_t snd_worldchannel2volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel2volume", "1", "volume multiplier of the 2nd entity channel of the world entity (DEPRECATED)"};
215 cvar_t snd_worldchannel3volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel3volume", "1", "volume multiplier of the 3rd entity channel of the world entity (DEPRECATED)"};
216 cvar_t snd_worldchannel4volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel4volume", "1", "volume multiplier of the 4th entity channel of the world entity (DEPRECATED)"};
217 cvar_t snd_worldchannel5volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel5volume", "1", "volume multiplier of the 5th entity channel of the world entity (DEPRECATED)"};
218 cvar_t snd_worldchannel6volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel6volume", "1", "volume multiplier of the 6th entity channel of the world entity (DEPRECATED)"};
219 cvar_t snd_worldchannel7volume = {CF_CLIENT | CF_ARCHIVE, "snd_worldchannel7volume", "1", "volume multiplier of the 7th entity channel of the world entity (DEPRECATED)"};
220 cvar_t snd_csqcchannel0volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel0volume", "1", "volume multiplier of the auto-allocate entity channel CSQC entities (DEPRECATED)"};
221 cvar_t snd_csqcchannel1volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel1volume", "1", "volume multiplier of the 1st entity channel of CSQC entities (DEPRECATED)"};
222 cvar_t snd_csqcchannel2volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel2volume", "1", "volume multiplier of the 2nd entity channel of CSQC entities (DEPRECATED)"};
223 cvar_t snd_csqcchannel3volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel3volume", "1", "volume multiplier of the 3rd entity channel of CSQC entities (DEPRECATED)"};
224 cvar_t snd_csqcchannel4volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel4volume", "1", "volume multiplier of the 4th entity channel of CSQC entities (DEPRECATED)"};
225 cvar_t snd_csqcchannel5volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel5volume", "1", "volume multiplier of the 5th entity channel of CSQC entities (DEPRECATED)"};
226 cvar_t snd_csqcchannel6volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel6volume", "1", "volume multiplier of the 6th entity channel of CSQC entities (DEPRECATED)"};
227 cvar_t snd_csqcchannel7volume = {CF_CLIENT | CF_ARCHIVE, "snd_csqcchannel7volume", "1", "volume multiplier of the 7th entity channel of CSQC entities (DEPRECATED)"};
228 cvar_t snd_channel0volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel0volume", "1", "volume multiplier of the auto-allocate entity channel"};
229 cvar_t snd_channel1volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel1volume", "1", "volume multiplier of the 1st entity channel"};
230 cvar_t snd_channel2volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel2volume", "1", "volume multiplier of the 2nd entity channel"};
231 cvar_t snd_channel3volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel3volume", "1", "volume multiplier of the 3rd entity channel"};
232 cvar_t snd_channel4volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel4volume", "1", "volume multiplier of the 4th entity channel"};
233 cvar_t snd_channel5volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel5volume", "1", "volume multiplier of the 5th entity channel"};
234 cvar_t snd_channel6volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel6volume", "1", "volume multiplier of the 6th entity channel"};
235 cvar_t snd_channel7volume = {CF_CLIENT | CF_ARCHIVE, "snd_channel7volume", "1", "volume multiplier of the 7th entity channel"};
236
237 // Local cvars
238 static cvar_t nosound = {CF_CLIENT, "nosound", "0", "disables sound"};
239 static cvar_t snd_precache = {CF_CLIENT, "snd_precache", "1", "loads sounds before they are used"};
240 static cvar_t ambient_level = {CF_CLIENT, "ambient_level", "0.3", "volume of environment noises (water and wind)"};
241 static cvar_t ambient_fade = {CF_CLIENT, "ambient_fade", "100", "rate of volume fading when moving from one environment to another"};
242 static cvar_t snd_noextraupdate = {CF_CLIENT, "snd_noextraupdate", "0", "disables extra sound mixer calls that are meant to reduce the chance of sound breakup at very low framerates"};
243 static cvar_t snd_show = {CF_CLIENT, "snd_show", "0", "shows some statistics about sound mixing"};
244
245 // Default sound format is 48KHz, 32bit float, stereo
246 // (48KHz because a lot of onboard sound cards sucks at any other speed)
247 static cvar_t snd_speed = {CF_CLIENT | CF_ARCHIVE, "snd_speed", "48000", "sound output frequency, in hertz"};
248 static cvar_t snd_width = {CF_CLIENT | CF_ARCHIVE, "snd_width", "4", "sound output precision, in bytes - 1 = 8bit, 2 = 16bit, 4 = 32bit float"};
249 static cvar_t snd_channels = {CF_CLIENT | CF_ARCHIVE, "snd_channels", "2", "number of channels for the sound output (2 for stereo; up to 8 supported for 3D sound)"};
250
251 static cvar_t snd_startloopingsounds = {CF_CLIENT, "snd_startloopingsounds", "1", "whether to start sounds that would loop (you want this to be 1); existing sounds are not affected"};
252 static cvar_t snd_startnonloopingsounds = {CF_CLIENT, "snd_startnonloopingsounds", "1", "whether to start sounds that would not loop (you want this to be 1); existing sounds are not affected"};
253
254 // randomization
255 static cvar_t snd_identicalsoundrandomization_time = {CF_CLIENT, "snd_identicalsoundrandomization_time", "0.1", "how much seconds to randomly skip (positive) or delay (negative) sounds when multiple identical sounds are started on the same frame"};
256 static cvar_t snd_identicalsoundrandomization_tics = {CF_CLIENT, "snd_identicalsoundrandomization_tics", "0", "if nonzero, how many tics to limit sound randomization as defined by snd_identicalsoundrandomization_time"};
257
258 // Ambient sounds
259 static sfx_t* ambient_sfxs [2] = { NULL, NULL };
260 static const char* ambient_names [2] = { "sound/ambience/water1.wav", "sound/ambience/wind2.wav" };
261
262
263 // ====================================================================
264 // Functions
265 // ====================================================================
266
267 void S_FreeSfx (sfx_t *sfx, qbool force);
268
269 static void S_Play_Common (cmd_state_t *cmd, float fvol, float attenuation)
270 {
271         int i, ch_ind;
272         char name [MAX_QPATH];
273         sfx_t *sfx;
274
275         i = 1;
276         while (i < Cmd_Argc (cmd))
277         {
278                 // Get the name, and appends ".wav" as an extension if there's none
279                 strlcpy (name, Cmd_Argv(cmd, i), sizeof (name));
280                 if (!strrchr (name, '.'))
281                         strlcat (name, ".wav", sizeof (name));
282                 i++;
283
284                 // If we need to get the volume from the command line
285                 if (fvol == -1.0f)
286                 {
287                         fvol = atof (Cmd_Argv(cmd, i));
288                         i++;
289                 }
290
291                 sfx = S_PrecacheSound (name, true, true);
292                 if (sfx)
293                 {
294                         ch_ind = S_StartSound (-1, 0, sfx, listener_origin, fvol, attenuation);
295
296                         // Free the sfx if the file didn't exist
297                         if (!sfx->fetcher)
298                                 S_FreeSfx (sfx, false);
299                         else
300                                 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
301                 }
302         }
303 }
304
305 static void S_Play_f(cmd_state_t *cmd)
306 {
307         S_Play_Common(cmd, 1.0f, 1.0f);
308 }
309
310 static void S_Play2_f(cmd_state_t *cmd)
311 {
312         S_Play_Common(cmd, 1.0f, 0.0f);
313 }
314
315 static void S_PlayVol_f(cmd_state_t *cmd)
316 {
317         S_Play_Common(cmd, -1.0f, 0.0f);
318 }
319
320 static void S_SoundList_f(cmd_state_t *cmd)
321 {
322         unsigned int i;
323         sfx_t *sfx;
324         unsigned int total;
325
326         total = 0;
327         for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
328         {
329                 if (sfx->fetcher != NULL)
330                 {
331                         unsigned int size;
332
333                         size = (unsigned int)sfx->memsize;
334                         Con_Printf ("%c%c%c(%5iHz %2db %6s) %8i : %s\n",
335                                                 (sfx->loopstart < sfx->total_length) ? 'L' : ' ',
336                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
337                                                 (sfx->flags & SFXFLAG_MENUSOUND) ? 'P' : ' ',
338                                                 sfx->format.speed,
339                                                 sfx->format.width * 8,
340                                                 (sfx->format.channels == 1) ? "mono" : "stereo",
341                                                 size,
342                                                 sfx->name);
343                         total += size;
344                 }
345                 else
346                         Con_Printf ("    (  unknown  ) unloaded : %s\n", sfx->name);
347         }
348         Con_Printf("Total resident: %i\n", total);
349 }
350
351
352 static void S_SoundInfo_f(cmd_state_t *cmd)
353 {
354         if (snd_renderbuffer == NULL)
355         {
356                 Con_Print("sound system not started\n");
357                 return;
358         }
359
360         Con_Printf("%5d speakers\n", snd_renderbuffer->format.channels);
361         Con_Printf("%5d frames\n", snd_renderbuffer->maxframes);
362         Con_Printf("%5d samplebits\n", snd_renderbuffer->format.width * 8);
363         Con_Printf("%5d speed\n", snd_renderbuffer->format.speed);
364         Con_Printf("%5u total_channels\n", total_channels);
365 }
366
367 static void S_PauseSound_f(cmd_state_t *cmd)
368 {
369         if( Cmd_Argc(cmd) != 2 ) {
370                 Con_Print("pausesound <pause>\n");
371                 return;
372         }
373         S_PauseGameSounds(atoi( Cmd_Argv(cmd, 1 ) ) != 0);
374 }
375
376 int S_GetSoundRate(void)
377 {
378         return snd_renderbuffer ? snd_renderbuffer->format.speed : 0;
379 }
380
381 int S_GetSoundChannels(void)
382 {
383         return snd_renderbuffer ? snd_renderbuffer->format.channels : 0;
384 }
385
386 int S_GetSoundWidth(void)
387 {
388         return snd_renderbuffer ? snd_renderbuffer->format.width : 0;
389 }
390
391
392 #define SWAP_LISTENERS(l1, l2, tmpl) { tmpl = (l1); (l1) = (l2); (l2) = tmpl; }
393
394 static void S_SetChannelLayout (void)
395 {
396         unsigned int i;
397         listener_t swaplistener;
398         listener_t *listeners;
399         int layout;
400
401         for (i = 0; i < SND_SPEAKERLAYOUTS; i++)
402                 if (snd_speakerlayouts[i].channels == snd_renderbuffer->format.channels)
403                         break;
404         if (i >= SND_SPEAKERLAYOUTS)
405         {
406                 Con_Printf("S_SetChannelLayout: can't find the speaker layout for %hu channels. Defaulting to mono output\n",
407                                    snd_renderbuffer->format.channels);
408                 i = SND_SPEAKERLAYOUTS - 1;
409         }
410
411         snd_speakerlayout = snd_speakerlayouts[i];
412         listeners = snd_speakerlayout.listeners;
413
414         // Swap the left and right channels if snd_swapstereo is set
415         if (boolxor(snd_swapstereo.integer, v_flipped.integer))
416         {
417                 switch (snd_speakerlayout.channels)
418                 {
419                         case 8:
420                                 SWAP_LISTENERS(listeners[6], listeners[7], swaplistener);
421                                 // no break
422                         case 4:
423                         case 6:
424                                 SWAP_LISTENERS(listeners[2], listeners[3], swaplistener);
425                                 // no break
426                         case 2:
427                                 SWAP_LISTENERS(listeners[0], listeners[1], swaplistener);
428                                 break;
429
430                         default:
431                         case 1:
432                                 // Nothing to do
433                                 break;
434                 }
435         }
436
437         // Sanity check
438         if (snd_channellayout.integer < SND_CHANNELLAYOUT_AUTO ||
439                 snd_channellayout.integer > SND_CHANNELLAYOUT_ALSA)
440                 Cvar_SetValueQuick (&snd_channellayout, SND_CHANNELLAYOUT_STANDARD);
441
442         if (snd_channellayout.integer == SND_CHANNELLAYOUT_AUTO)
443         {
444                 // If we're in the sound engine initialization
445                 if (current_channellayout_used == SND_CHANNELLAYOUT_AUTO)
446                 {
447                         layout = SND_CHANNELLAYOUT_STANDARD;
448                         Cvar_SetValueQuick (&snd_channellayout, layout);
449                 }
450                 else
451                         layout = current_channellayout_used;
452         }
453         else
454                 layout = snd_channellayout.integer;
455
456         // Convert our layout (= ALSA) to the standard layout if necessary
457         if (snd_speakerlayout.channels == 6 || snd_speakerlayout.channels == 8)
458         {
459                 if (layout == SND_CHANNELLAYOUT_STANDARD)
460                 {
461                         SWAP_LISTENERS(listeners[2], listeners[4], swaplistener);
462                         SWAP_LISTENERS(listeners[3], listeners[5], swaplistener);
463                 }
464
465                 Con_Printf("S_SetChannelLayout: using %s speaker layout for 3D sound\n",
466                                    (layout == SND_CHANNELLAYOUT_ALSA) ? "ALSA" : "standard");
467         }
468
469         current_swapstereo = boolxor(snd_swapstereo.integer, v_flipped.integer);
470         current_channellayout = snd_channellayout.integer;
471         current_channellayout_used = layout;
472 }
473
474
475 void S_Startup (void)
476 {
477         snd_format_t chosen_fmt;
478         static snd_format_t prev_render_format = {0, 0, 0};
479         char* env;
480 #if _MSC_VER >= 1400
481         size_t envlen;
482 #endif
483         int i;
484
485         if (!snd_initialized.integer)
486                 return;
487
488         // Get the starting sound format from the cvars
489         chosen_fmt.speed = snd_speed.integer;
490         chosen_fmt.width = snd_width.integer;
491         chosen_fmt.channels = snd_channels.integer;
492
493         // Check the environment variables to see if the player wants a particular sound format
494 #if _MSC_VER >= 1400
495         _dupenv_s(&env, &envlen, "QUAKE_SOUND_CHANNELS");
496 #else
497         env = getenv("QUAKE_SOUND_CHANNELS");
498 #endif
499         if (env != NULL)
500         {
501                 chosen_fmt.channels = atoi (env);
502 #if _MSC_VER >= 1400
503                 free(env);
504 #endif
505         }
506 #if _MSC_VER >= 1400
507         _dupenv_s(&env, &envlen, "QUAKE_SOUND_SPEED");
508 #else
509         env = getenv("QUAKE_SOUND_SPEED");
510 #endif
511         if (env != NULL)
512         {
513                 chosen_fmt.speed = atoi (env);
514 #if _MSC_VER >= 1400
515                 free(env);
516 #endif
517         }
518 #if _MSC_VER >= 1400
519         _dupenv_s(&env, &envlen, "QUAKE_SOUND_SAMPLEBITS");
520 #else
521         env = getenv("QUAKE_SOUND_SAMPLEBITS");
522 #endif
523         if (env != NULL)
524         {
525                 chosen_fmt.width = atoi (env) / 8;
526 #if _MSC_VER >= 1400
527                 free(env);
528 #endif
529         }
530
531         // Parse the command line to see if the player wants a particular sound format
532 // COMMANDLINEOPTION: Sound: -sndquad sets sound output to 4 channel surround
533         if (Sys_CheckParm ("-sndquad") != 0)
534         {
535                 chosen_fmt.channels = 4;
536         }
537 // COMMANDLINEOPTION: Sound: -sndstereo sets sound output to stereo
538         else if (Sys_CheckParm ("-sndstereo") != 0)
539         {
540                 chosen_fmt.channels = 2;
541         }
542 // COMMANDLINEOPTION: Sound: -sndmono sets sound output to mono
543         else if (Sys_CheckParm ("-sndmono") != 0)
544         {
545                 chosen_fmt.channels = 1;
546         }
547 // COMMANDLINEOPTION: Sound: -sndspeed <hz> chooses sound output rate (supported values are 48000, 44100, 32000, 24000, 22050, 16000, 11025 (quake), 8000)
548         i = Sys_CheckParm ("-sndspeed");
549         if (0 < i && i < sys.argc - 1)
550         {
551                 chosen_fmt.speed = atoi (sys.argv[i + 1]);
552         }
553 // COMMANDLINEOPTION: Sound: -sndbits <bits> chooses 8 bit or 16 bit or 32bit float sound output
554         i = Sys_CheckParm ("-sndbits");
555         if (0 < i && i < sys.argc - 1)
556         {
557                 chosen_fmt.width = atoi (sys.argv[i + 1]) / 8;
558         }
559
560 #if 0
561         // LadyHavoc: now you can with the resampler...
562         // You can't change sound speed after start time (not yet supported)
563         if (prev_render_format.speed != 0)
564         {
565                 if (chosen_fmt.speed != prev_render_format.speed)
566                 {
567                         Con_Printf("S_Startup: sound speed has changed! This is NOT supported yet. Falling back to previous speed (%u Hz)\n",
568                                            prev_render_format.speed);
569                         chosen_fmt.speed = prev_render_format.speed;
570                 }
571         }
572 #endif
573
574         // Sanity checks
575         if (chosen_fmt.speed < SND_MIN_SPEED)
576         {
577                 chosen_fmt.speed = SND_MIN_SPEED;
578         }
579         else if (chosen_fmt.speed > SND_MAX_SPEED)
580         {
581                 chosen_fmt.speed = SND_MAX_SPEED;
582         }
583
584         if (chosen_fmt.width < SND_MIN_WIDTH)
585         {
586                 chosen_fmt.width = SND_MIN_WIDTH;
587         }
588         else if (chosen_fmt.width == 3)
589         {
590                 chosen_fmt.width = 4;
591         }
592         else if (chosen_fmt.width > SND_MAX_WIDTH)
593         {
594                 chosen_fmt.width = SND_MAX_WIDTH;
595         }
596
597         if (chosen_fmt.channels < SND_MIN_CHANNELS)
598         {
599                 chosen_fmt.channels = SND_MIN_CHANNELS;
600         }
601         else if (chosen_fmt.channels > SND_MAX_CHANNELS)
602         {
603                 chosen_fmt.channels = SND_MAX_CHANNELS;
604         }
605
606         // create the sound buffer used for sumitting the samples to the plaform-dependent module
607         if (!simsound)
608         {
609                 Con_Printf("S_Startup: initializing sound output format: %dHz, %d bit, %d channels...\n",
610                                         chosen_fmt.speed,
611                                         chosen_fmt.width,
612                                         chosen_fmt.channels);
613
614                 if (!SndSys_Init(&chosen_fmt))
615                 {
616                         Con_Print("S_Startup: SndSys_Init failed.\n");
617                         sound_spatialized = false;
618                         return;
619                 }
620         }
621         else
622         {
623                 snd_renderbuffer = Snd_CreateRingBuffer(&chosen_fmt, 0, NULL);
624                 Con_Print ("S_Startup: simulating sound output\n");
625         }
626
627         memcpy(&prev_render_format, &snd_renderbuffer->format, sizeof(prev_render_format));
628         Con_Printf("Sound format: %dHz, %d channels, %d bits per sample\n",
629                            chosen_fmt.speed, chosen_fmt.channels, chosen_fmt.width * 8);
630
631         // Update the cvars
632         if (snd_speed.integer != (int)chosen_fmt.speed)
633                 Cvar_SetValueQuick(&snd_speed, chosen_fmt.speed);
634         if (snd_width.integer != chosen_fmt.width)
635                 Cvar_SetValueQuick(&snd_width, chosen_fmt.width);
636         if (snd_channels.integer != chosen_fmt.channels)
637                 Cvar_SetValueQuick(&snd_channels, chosen_fmt.channels);
638
639         current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
640         S_SetChannelLayout();
641
642         snd_starttime = host.realtime;
643
644         // If the sound module has already run, add an extra time to make sure
645         // the sound time doesn't decrease, to not confuse playing SFXs
646         if (oldpaintedtime != 0)
647         {
648                 // The extra time must be a multiple of the render buffer size
649                 // to avoid modifying the current position in the buffer,
650                 // some modules write directly to a shared (DMA) buffer
651                 extrasoundtime = oldpaintedtime + snd_renderbuffer->maxframes - 1;
652                 extrasoundtime -= extrasoundtime % snd_renderbuffer->maxframes;
653                 Con_Printf("S_Startup: extra sound time = %u\n", extrasoundtime);
654
655                 soundtime = extrasoundtime;
656         }
657         else
658                 extrasoundtime = 0;
659         snd_renderbuffer->startframe = soundtime;
660         snd_renderbuffer->endframe = soundtime;
661 #ifdef CONFIG_VIDEO_CAPTURE
662         recording_sound = false;
663 #endif
664
665         CDAudio_Startup();
666 }
667
668 void S_Shutdown(void)
669 {
670         if (snd_renderbuffer == NULL)
671                 return;
672
673         CDAudio_Shutdown();
674
675         oldpaintedtime = snd_renderbuffer->endframe;
676
677         if (simsound)
678         {
679                 Mem_Free(snd_renderbuffer->ring);
680                 Mem_Free(snd_renderbuffer);
681                 snd_renderbuffer = NULL;
682         }
683         else
684                 SndSys_Shutdown();
685
686         sound_spatialized = false;
687 }
688
689 static void S_Restart_f(cmd_state_t *cmd)
690 {
691         // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
692         // So, refuse to do this if we are connected.
693         if(cls.state == ca_connected)
694         {
695                 Con_Printf("snd_restart would wreak havoc if you do that while connected!\n");
696                 return;
697         }
698
699         S_Shutdown();
700         S_Startup();
701 }
702
703 /*
704 ================
705 S_Init
706 ================
707 */
708 void S_Init(void)
709 {
710         Cvar_RegisterVariable(&volume);
711         Cvar_RegisterVariable(&bgmvolume);
712         Cvar_RegisterVariable(&mastervolume);
713         Cvar_RegisterVariable(&snd_staticvolume);
714         Cvar_RegisterVariable(&snd_entchannel0volume);
715         Cvar_RegisterVariable(&snd_entchannel1volume);
716         Cvar_RegisterVariable(&snd_entchannel2volume);
717         Cvar_RegisterVariable(&snd_entchannel3volume);
718         Cvar_RegisterVariable(&snd_entchannel4volume);
719         Cvar_RegisterVariable(&snd_entchannel5volume);
720         Cvar_RegisterVariable(&snd_entchannel6volume);
721         Cvar_RegisterVariable(&snd_entchannel7volume);
722         Cvar_RegisterVariable(&snd_worldchannel0volume);
723         Cvar_RegisterVariable(&snd_worldchannel1volume);
724         Cvar_RegisterVariable(&snd_worldchannel2volume);
725         Cvar_RegisterVariable(&snd_worldchannel3volume);
726         Cvar_RegisterVariable(&snd_worldchannel4volume);
727         Cvar_RegisterVariable(&snd_worldchannel5volume);
728         Cvar_RegisterVariable(&snd_worldchannel6volume);
729         Cvar_RegisterVariable(&snd_worldchannel7volume);
730         Cvar_RegisterVariable(&snd_playerchannel0volume);
731         Cvar_RegisterVariable(&snd_playerchannel1volume);
732         Cvar_RegisterVariable(&snd_playerchannel2volume);
733         Cvar_RegisterVariable(&snd_playerchannel3volume);
734         Cvar_RegisterVariable(&snd_playerchannel4volume);
735         Cvar_RegisterVariable(&snd_playerchannel5volume);
736         Cvar_RegisterVariable(&snd_playerchannel6volume);
737         Cvar_RegisterVariable(&snd_playerchannel7volume);
738         Cvar_RegisterVariable(&snd_csqcchannel0volume);
739         Cvar_RegisterVariable(&snd_csqcchannel1volume);
740         Cvar_RegisterVariable(&snd_csqcchannel2volume);
741         Cvar_RegisterVariable(&snd_csqcchannel3volume);
742         Cvar_RegisterVariable(&snd_csqcchannel4volume);
743         Cvar_RegisterVariable(&snd_csqcchannel5volume);
744         Cvar_RegisterVariable(&snd_csqcchannel6volume);
745         Cvar_RegisterVariable(&snd_csqcchannel7volume);
746         Cvar_RegisterVariable(&snd_channel0volume);
747         Cvar_RegisterVariable(&snd_channel1volume);
748         Cvar_RegisterVariable(&snd_channel2volume);
749         Cvar_RegisterVariable(&snd_channel3volume);
750         Cvar_RegisterVariable(&snd_channel4volume);
751         Cvar_RegisterVariable(&snd_channel5volume);
752         Cvar_RegisterVariable(&snd_channel6volume);
753         Cvar_RegisterVariable(&snd_channel7volume);
754
755         Cvar_RegisterVariable(&snd_attenuation_exponent);
756         Cvar_RegisterVariable(&snd_attenuation_decibel);
757
758         Cvar_RegisterVariable(&snd_spatialization_min_radius);
759         Cvar_RegisterVariable(&snd_spatialization_max_radius);
760         Cvar_RegisterVariable(&snd_spatialization_min);
761         Cvar_RegisterVariable(&snd_spatialization_max);
762         Cvar_RegisterVariable(&snd_spatialization_power);
763         Cvar_RegisterVariable(&snd_spatialization_control);
764         Cvar_RegisterVariable(&snd_spatialization_occlusion);
765         Cvar_RegisterVariable(&snd_spatialization_prologic);
766         Cvar_RegisterVariable(&snd_spatialization_prologic_frontangle);
767
768         Cvar_RegisterVariable(&snd_speed);
769         Cvar_RegisterVariable(&snd_width);
770         Cvar_RegisterVariable(&snd_channels);
771         Cvar_RegisterVariable(&snd_mutewhenidle);
772         Cvar_RegisterVariable(&snd_maxchannelvolume);
773         Cvar_RegisterVariable(&snd_softclip);
774
775         Cvar_RegisterVariable(&snd_startloopingsounds);
776         Cvar_RegisterVariable(&snd_startnonloopingsounds);
777
778         Cvar_RegisterVariable(&snd_identicalsoundrandomization_time);
779         Cvar_RegisterVariable(&snd_identicalsoundrandomization_tics);
780
781 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
782         if (Sys_CheckParm("-nosound"))
783         {
784                 // dummy out Play and Play2 because mods stuffcmd that
785                 Cmd_AddCommand(CF_CLIENT, "play", Cmd_NoOperation_f, "does nothing because -nosound was specified");
786                 Cmd_AddCommand(CF_CLIENT, "play2", Cmd_NoOperation_f, "does nothing because -nosound was specified");
787                 return;
788         }
789
790         snd_mempool = Mem_AllocPool("sound", 0, NULL);
791
792 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
793         if (Sys_CheckParm("-simsound"))
794                 simsound = true;
795
796         Cmd_AddCommand(CF_CLIENT, "play", S_Play_f, "play a sound at your current location (not heard by anyone else)");
797         Cmd_AddCommand(CF_CLIENT, "play2", S_Play2_f, "play a sound globally throughout the level (not heard by anyone else)");
798         Cmd_AddCommand(CF_CLIENT, "playvol", S_PlayVol_f, "play a sound at the specified volume level at your current location (not heard by anyone else)");
799         Cmd_AddCommand(CF_CLIENT, "stopsound", S_StopAllSounds_f, "silence");
800         Cmd_AddCommand(CF_CLIENT, "pausesound", S_PauseSound_f, "temporary silence");
801         Cmd_AddCommand(CF_CLIENT, "soundlist", S_SoundList_f, "list loaded sounds");
802         Cmd_AddCommand(CF_CLIENT, "soundinfo", S_SoundInfo_f, "print sound system information (such as channels and speed)");
803         Cmd_AddCommand(CF_CLIENT, "snd_restart", S_Restart_f, "restart sound system");
804         Cmd_AddCommand(CF_CLIENT, "snd_unloadallsounds", S_UnloadAllSounds_f, "unload all sound files");
805
806         Cvar_RegisterVariable(&nosound);
807         Cvar_RegisterVariable(&snd_precache);
808         Cvar_RegisterVariable(&snd_initialized);
809         Cvar_RegisterVariable(&snd_streaming);
810         Cvar_RegisterVariable(&snd_streaming_length);
811         Cvar_RegisterVariable(&ambient_level);
812         Cvar_RegisterVariable(&ambient_fade);
813         Cvar_RegisterVariable(&snd_noextraupdate);
814         Cvar_RegisterVariable(&snd_show);
815         Cvar_RegisterVariable(&_snd_mixahead);
816         Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
817         Cvar_RegisterVariable(&snd_channellayout);
818         Cvar_RegisterVariable(&snd_soundradius);
819
820         Cvar_SetValueQuick(&snd_initialized, true);
821
822         known_sfx = NULL;
823
824         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
825         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
826
827         OGG_OpenLibrary ();
828 #ifdef USEXMP
829         XMP_OpenLibrary ();
830 #endif
831
832         CDAudio_Init();
833 }
834
835
836 /*
837 ================
838 S_Terminate
839
840 Shutdown and free all resources
841 ================
842 */
843 void S_Terminate (void)
844 {
845         S_Shutdown ();
846 #ifdef USEXMP
847         XMP_CloseLibrary ();
848 #endif
849         OGG_CloseLibrary ();
850
851         // Free all SFXs
852         while (known_sfx != NULL)
853                 S_FreeSfx (known_sfx, true);
854
855         Cvar_SetValueQuick (&snd_initialized, false);
856         Mem_FreePool (&snd_mempool);
857 }
858
859
860 /*
861 ==================
862 S_UnloadAllSounds_f
863 ==================
864 */
865 void S_UnloadAllSounds_f(cmd_state_t *cmd)
866 {
867         int i;
868
869         // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
870         // So, refuse to do this if we are connected.
871         if(cls.state == ca_connected)
872         {
873                 Con_Printf("snd_unloadallsounds would wreak havoc if you do that while connected!\n");
874                 return;
875         }
876
877         // stop any active sounds
878         S_StopAllSounds();
879
880         // because the ambient sounds will be freed, clear the pointers
881         for (i = 0;i < (int)sizeof (ambient_sfxs) / (int)sizeof (ambient_sfxs[0]);i++)
882                 ambient_sfxs[i] = NULL;
883
884         // now free all sounds
885         while (known_sfx != NULL)
886                 S_FreeSfx (known_sfx, true);
887 }
888
889
890 /*
891 ==================
892 S_FindName
893 ==================
894 */
895 sfx_t changevolume_sfx = {""};
896 sfx_t *S_FindName (const char *name)
897 {
898         sfx_t *sfx;
899
900         if (!snd_initialized.integer)
901                 return NULL;
902
903         if(!strcmp(name, changevolume_sfx.name))
904                 return &changevolume_sfx;
905
906         if (strlen (name) >= sizeof (sfx->name))
907         {
908                 Con_Printf ("S_FindName: sound name too long (%s)\n", name);
909                 return NULL;
910         }
911
912         // Look for this sound in the list of known sfx
913         // TODO: hash table search?
914         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
915                 if(!strcmp (sfx->name, name))
916                         return sfx;
917
918         // check for # in the beginning, try lookup by soundindex
919         if (name[0] == '#' && name[1])
920         {
921                 int soundindex = atoi(name + 1);
922                 if (soundindex > 0 && soundindex < MAX_SOUNDS)
923                         if (cl.sound_precache[soundindex]->name[0])
924                                 return cl.sound_precache[soundindex];
925         }
926
927         // Add a sfx_t struct for this sound
928         sfx = (sfx_t *)Mem_Alloc (snd_mempool, sizeof (*sfx));
929         memset (sfx, 0, sizeof(*sfx));
930         strlcpy (sfx->name, name, sizeof (sfx->name));
931         sfx->memsize = sizeof(*sfx);
932         sfx->next = known_sfx;
933         known_sfx = sfx;
934
935         return sfx;
936 }
937
938
939 /*
940 ==================
941 S_FreeSfx
942 ==================
943 */
944 void S_FreeSfx (sfx_t *sfx, qbool force)
945 {
946         unsigned int i;
947
948         // Do not free a precached sound during purge
949         if (!force && (sfx->flags & (SFXFLAG_LEVELSOUND | SFXFLAG_MENUSOUND)))
950                 return;
951
952         if (developer_loading.integer)
953                 Con_Printf ("unloading sound %s\n", sfx->name);
954
955         // Remove it from the list of known sfx
956         if (sfx == known_sfx)
957                 known_sfx = known_sfx->next;
958         else
959         {
960                 sfx_t *prev_sfx;
961
962                 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
963                         if (prev_sfx->next == sfx)
964                         {
965                                 prev_sfx->next = sfx->next;
966                                 break;
967                         }
968                 if (prev_sfx == NULL)
969                 {
970                         Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
971                         return;
972                 }
973         }
974
975         // Stop all channels using this sfx
976         for (i = 0; i < total_channels; i++)
977         {
978                 if (channels[i].sfx == sfx)
979                 {
980                         Con_Printf("S_FreeSfx: stopping channel %i for sfx \"%s\"\n", i, sfx->name);
981                         S_StopChannel (i, true, false);
982                 }
983         }
984
985         // Free it
986         if (sfx->fetcher != NULL && sfx->fetcher->freesfx != NULL)
987                 sfx->fetcher->freesfx(sfx);
988         Mem_Free (sfx);
989 }
990
991
992 /*
993 ==================
994 S_ClearUsed
995 ==================
996 */
997 void S_ClearUsed (void)
998 {
999         sfx_t *sfx;
1000 //      sfx_t *sfxnext;
1001         unsigned int i;
1002
1003         // Start the ambient sounds and make them loop
1004         for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
1005         {
1006                 // Precache it if it's not done (and pass false for levelsound because these are permanent)
1007                 if (ambient_sfxs[i] == NULL)
1008                         ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, false);
1009                 if (ambient_sfxs[i] != NULL)
1010                 {
1011                         channels[i].sfx = ambient_sfxs[i];
1012                         channels[i].sfx->flags |= SFXFLAG_MENUSOUND;
1013                         channels[i].flags |= CHANNELFLAG_FORCELOOP;
1014                         channels[i].basevolume = 0.0f;
1015                         channels[i].basespeed = channels[i].mixspeed = 1.0f;
1016                 }
1017         }
1018
1019         // Clear SFXFLAG_LEVELSOUND flag so that sounds not precached this level will be purged
1020         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
1021                 sfx->flags &= ~SFXFLAG_LEVELSOUND;
1022 }
1023
1024 /*
1025 ==================
1026 S_PurgeUnused
1027 ==================
1028 */
1029 void S_PurgeUnused(void)
1030 {
1031         sfx_t *sfx;
1032         sfx_t *sfxnext;
1033
1034         // Free all not-precached per-level sfx
1035         for (sfx = known_sfx;sfx;sfx = sfxnext)
1036         {
1037                 sfxnext = sfx->next;
1038                 if (!(sfx->flags & (SFXFLAG_LEVELSOUND | SFXFLAG_MENUSOUND)))
1039                         S_FreeSfx (sfx, false);
1040         }
1041 }
1042
1043
1044 /*
1045 ==================
1046 S_PrecacheSound
1047 ==================
1048 */
1049 sfx_t *S_PrecacheSound (const char *name, qbool complain, qbool levelsound)
1050 {
1051         sfx_t *sfx;
1052
1053         if (!snd_initialized.integer)
1054                 return NULL;
1055
1056         if (name == NULL || name[0] == 0)
1057                 return NULL;
1058
1059         sfx = S_FindName (name);
1060
1061         if (sfx == NULL)
1062                 return NULL;
1063
1064         // clear the FILEMISSING flag so that S_LoadSound will try again on a
1065         // previously missing file
1066         sfx->flags &= ~ SFXFLAG_FILEMISSING;
1067
1068         // set a flag to indicate this has been precached for this level or permanently
1069         if (levelsound)
1070                 sfx->flags |= SFXFLAG_LEVELSOUND;
1071         else
1072                 sfx->flags |= SFXFLAG_MENUSOUND;
1073
1074         if (!nosound.integer && snd_precache.integer)
1075                 S_LoadSound(sfx, complain);
1076
1077         return sfx;
1078 }
1079
1080 /*
1081 ==================
1082 S_SoundLength
1083 ==================
1084 */
1085
1086 float S_SoundLength(const char *name)
1087 {
1088         sfx_t *sfx;
1089
1090         if (!snd_initialized.integer)
1091                 return -1;
1092         if (name == NULL || name[0] == 0)
1093                 return -1;
1094
1095         sfx = S_FindName(name);
1096         if (sfx == NULL)
1097                 return -1;
1098         return sfx->total_length / (float) S_GetSoundRate();
1099 }
1100
1101 /*
1102 ==================
1103 S_IsSoundPrecached
1104 ==================
1105 */
1106 qbool S_IsSoundPrecached (const sfx_t *sfx)
1107 {
1108         return (sfx != NULL && sfx->fetcher != NULL) || (sfx == &changevolume_sfx);
1109 }
1110
1111 /*
1112 ==================
1113 S_BlockSound
1114 ==================
1115 */
1116 void S_BlockSound (void)
1117 {
1118         snd_blocked++;
1119 }
1120
1121
1122 /*
1123 ==================
1124 S_UnblockSound
1125 ==================
1126 */
1127 void S_UnblockSound (void)
1128 {
1129         snd_blocked--;
1130 }
1131
1132
1133 /*
1134 =================
1135 SND_PickChannel
1136
1137 Picks a channel based on priorities, empty slots, number of channels
1138 =================
1139 */
1140 static channel_t *SND_PickChannel(int entnum, int entchannel)
1141 {
1142         int ch_idx;
1143         int first_to_die;
1144         int first_life_left, life_left;
1145         channel_t* ch;
1146         sfx_t *sfx; // use this instead of ch->sfx->, because that is volatile.
1147
1148 // Check for replacement sound, or find the best one to replace
1149         first_to_die = -1;
1150         first_life_left = 0x7fffffff;
1151
1152         // entity channels try to replace the existing sound on the channel
1153         // channels <= 0 are autochannels
1154         if (IS_CHAN_SINGLE(entchannel))
1155         {
1156                 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1157                 {
1158                         ch = &channels[ch_idx];
1159                         if (ch->entnum == entnum && ch->entchannel == entchannel)
1160                         {
1161                                 // always override sound from same entity
1162                                 S_StopChannel (ch_idx, true, false);
1163                                 return &channels[ch_idx];
1164                         }
1165                 }
1166         }
1167
1168         // there was no channel to override, so look for the first empty one
1169         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1170         {
1171                 ch = &channels[ch_idx];
1172                 sfx = ch->sfx; // fetch the volatile variable
1173                 if (!sfx)
1174                 {
1175                         // no sound on this channel
1176                         first_to_die = ch_idx;
1177                         goto emptychan_found;
1178                 }
1179
1180                 // don't let monster sounds override player sounds
1181                 if ((ch->entnum == cl.viewentity || ch->entnum == CL_VM_GetViewEntity()) && !(entnum == cl.viewentity || entnum == CL_VM_GetViewEntity()))
1182                         continue;
1183
1184                 // don't override looped sounds
1185                 if ((ch->flags & CHANNELFLAG_FORCELOOP) || sfx->loopstart < sfx->total_length)
1186                         continue;
1187                 life_left = (int)((double)sfx->total_length - ch->position);
1188
1189                 if (life_left < first_life_left)
1190                 {
1191                         first_life_left = life_left;
1192                         first_to_die = ch_idx;
1193                 }
1194         }
1195
1196         if (first_to_die == -1)
1197                 return NULL;
1198         
1199         S_StopChannel (first_to_die, true, false);
1200
1201 emptychan_found:
1202         return &channels[first_to_die];
1203 }
1204
1205 /*
1206 =================
1207 SND_Spatialize
1208
1209 Spatializes a channel
1210 =================
1211 */
1212 extern cvar_t cl_gameplayfix_soundsmovewithentities;
1213 static void SND_Spatialize_WithSfx(channel_t *ch, qbool isstatic, sfx_t *sfx)
1214 {
1215         int i;
1216         double f;
1217         float angle_side, angle_front, angle_factor, mixspeed;
1218         vec_t dist, mastervol, intensity;
1219         vec3_t source_vec;
1220         char vabuf[1024];
1221
1222         // update sound origin if we know about the entity
1223         if (ch->entnum > 0 && cls.state == ca_connected && cl_gameplayfix_soundsmovewithentities.integer)
1224         {
1225                 if (ch->entnum >= MAX_EDICTS)
1226                 {
1227                         //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]);
1228
1229                         if (ch->entnum > MAX_EDICTS)
1230                                 if (!CL_VM_GetEntitySoundOrigin(ch->entnum, ch->origin))
1231                                         ch->entnum = MAX_EDICTS; // entity was removed, disown sound
1232                 }
1233                 else if (cl.entities[ch->entnum].state_current.active)
1234                 {
1235                         model_t *model;
1236                         //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]);
1237                         model = CL_GetModelByIndex(cl.entities[ch->entnum].state_current.modelindex);
1238                         if (model && model->soundfromcenter)
1239                                 VectorMAM(0.5f, cl.entities[ch->entnum].render.mins, 0.5f, cl.entities[ch->entnum].render.maxs, ch->origin);
1240                         else
1241                                 Matrix4x4_OriginFromMatrix(&cl.entities[ch->entnum].render.matrix, ch->origin);
1242                 }
1243                 else if (cl.csqc_server2csqcentitynumber[ch->entnum])
1244                 {
1245                         //Con_Printf("-- entnum %i (client %i) origin %f %f %f neworigin %f %f %f\n", ch->entnum, cl.csqc_server2csqcentitynumber[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]);
1246
1247                         if (!CL_VM_GetEntitySoundOrigin(cl.csqc_server2csqcentitynumber[ch->entnum] + MAX_EDICTS, ch->origin))
1248                                 ch->entnum = MAX_EDICTS; // entity was removed, disown sound
1249                 }
1250         }
1251
1252         mastervol = ch->basevolume;
1253         mixspeed = ch->basespeed;
1254
1255         // TODO: implement doppler based on origin change relative to viewer and time of recent origin changes
1256
1257         // Adjust volume of static sounds
1258         if (isstatic)
1259                 mastervol *= snd_staticvolume.value;
1260         else if(!(ch->flags & CHANNELFLAG_FULLVOLUME)) // same as SND_PaintChannel uses
1261         {
1262                 // old legacy separated cvars
1263                 if(ch->entnum >= MAX_EDICTS)
1264                 {
1265                         switch(ch->entchannel)
1266                         {
1267                                 case 0: mastervol *= snd_csqcchannel0volume.value; break;
1268                                 case 1: mastervol *= snd_csqcchannel1volume.value; break;
1269                                 case 2: mastervol *= snd_csqcchannel2volume.value; break;
1270                                 case 3: mastervol *= snd_csqcchannel3volume.value; break;
1271                                 case 4: mastervol *= snd_csqcchannel4volume.value; break;
1272                                 case 5: mastervol *= snd_csqcchannel5volume.value; break;
1273                                 case 6: mastervol *= snd_csqcchannel6volume.value; break;
1274                                 case 7: mastervol *= snd_csqcchannel7volume.value; break;
1275                                 default:                                           break;
1276                         }
1277                 }
1278                 else if(ch->entnum == 0)
1279                 {
1280                         switch(ch->entchannel)
1281                         {
1282                                 case 0: mastervol *= snd_worldchannel0volume.value; break;
1283                                 case 1: mastervol *= snd_worldchannel1volume.value; break;
1284                                 case 2: mastervol *= snd_worldchannel2volume.value; break;
1285                                 case 3: mastervol *= snd_worldchannel3volume.value; break;
1286                                 case 4: mastervol *= snd_worldchannel4volume.value; break;
1287                                 case 5: mastervol *= snd_worldchannel5volume.value; break;
1288                                 case 6: mastervol *= snd_worldchannel6volume.value; break;
1289                                 case 7: mastervol *= snd_worldchannel7volume.value; break;
1290                                 default:                                            break;
1291                         }
1292                 }
1293                 else if(ch->entnum > 0 && ch->entnum <= cl.maxclients)
1294                 {
1295                         switch(ch->entchannel)
1296                         {
1297                                 case 0: mastervol *= snd_playerchannel0volume.value; break;
1298                                 case 1: mastervol *= snd_playerchannel1volume.value; break;
1299                                 case 2: mastervol *= snd_playerchannel2volume.value; break;
1300                                 case 3: mastervol *= snd_playerchannel3volume.value; break;
1301                                 case 4: mastervol *= snd_playerchannel4volume.value; break;
1302                                 case 5: mastervol *= snd_playerchannel5volume.value; break;
1303                                 case 6: mastervol *= snd_playerchannel6volume.value; break;
1304                                 case 7: mastervol *= snd_playerchannel7volume.value; break;
1305                                 default:                                             break;
1306                         }
1307                 }
1308                 else
1309                 {
1310                         switch(ch->entchannel)
1311                         {
1312                                 case 0: mastervol *= snd_entchannel0volume.value; break;
1313                                 case 1: mastervol *= snd_entchannel1volume.value; break;
1314                                 case 2: mastervol *= snd_entchannel2volume.value; break;
1315                                 case 3: mastervol *= snd_entchannel3volume.value; break;
1316                                 case 4: mastervol *= snd_entchannel4volume.value; break;
1317                                 case 5: mastervol *= snd_entchannel5volume.value; break;
1318                                 case 6: mastervol *= snd_entchannel6volume.value; break;
1319                                 case 7: mastervol *= snd_entchannel7volume.value; break;
1320                                 default:                                          break;
1321                         }
1322                 }
1323
1324                 switch(ch->entchannel)
1325                 {
1326                         case 0:  mastervol *= snd_channel0volume.value; break;
1327                         case 1:  mastervol *= snd_channel1volume.value; break;
1328                         case 2:  mastervol *= snd_channel2volume.value; break;
1329                         case 3:  mastervol *= snd_channel3volume.value; break;
1330                         case 4:  mastervol *= snd_channel4volume.value; break;
1331                         case 5:  mastervol *= snd_channel5volume.value; break;
1332                         case 6:  mastervol *= snd_channel6volume.value; break;
1333                         case 7:  mastervol *= snd_channel7volume.value; break;
1334                         default: mastervol *= Cvar_VariableValueOr(&cvars_all, va(vabuf, sizeof(vabuf), "snd_channel%dvolume", CHAN_ENGINE2CVAR(ch->entchannel)), 1.0, ~0); break;
1335                 }
1336         }
1337
1338         // If this channel does not manage its own volume (like CD tracks)
1339         if (!(ch->flags & CHANNELFLAG_FULLVOLUME))
1340                 mastervol *= volume.value;
1341
1342         if(snd_maxchannelvolume.value > 0)
1343         {
1344                 // clamp HERE to allow to go at most 10dB past mastervolume (before clamping), when mastervolume < -10dB (so relative volumes don't get too messy)
1345                 mastervol = bound(0.0f, mastervol, 10.0f * snd_maxchannelvolume.value);
1346         }
1347
1348         // always apply "master"
1349         mastervol *= mastervolume.value;
1350
1351         // add in ReplayGain very late; prevent clipping when close
1352         if(sfx)
1353         if(sfx->volume_peak > 0)
1354         {
1355                 // Replaygain support
1356                 // Con_DPrintf("Setting volume on ReplayGain-enabled track... %f -> ", fvol);
1357                 mastervol *= sfx->volume_mult;
1358                 if(snd_maxchannelvolume.value > 0)
1359                 {
1360                         if(mastervol * sfx->volume_peak > snd_maxchannelvolume.value)
1361                                 mastervol = snd_maxchannelvolume.value / sfx->volume_peak;
1362                 }
1363                 // Con_DPrintf("%f\n", fvol);
1364         }
1365
1366         if(snd_maxchannelvolume.value > 0)
1367         {
1368                 // clamp HERE to keep relative volumes of the channels correct
1369                 mastervol = min(mastervol, snd_maxchannelvolume.value);
1370         }
1371
1372         mastervol = max(0.0f, mastervol);
1373
1374         ch->mixspeed = mixspeed;
1375
1376         // anything coming from the view entity will always be full volume
1377         // LadyHavoc: make sounds with ATTN_NONE have no spatialization
1378         if (ch->entnum == cl.viewentity || ch->entnum == CL_VM_GetViewEntity() || ch->distfade == 0)
1379         {
1380                 ch->prologic_invert = 1;
1381                 if (snd_spatialization_prologic.integer != 0)
1382                 {
1383                         ch->volume[0] = mastervol * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5);
1384                         ch->volume[1] = mastervol * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5);
1385                         for (i = 2;i < SND_LISTENERS;i++)
1386                                 ch->volume[i] = 0;
1387                 }
1388                 else
1389                 {
1390                         for (i = 0;i < SND_LISTENERS;i++)
1391                                 ch->volume[i] = mastervol * snd_speakerlayout.listeners[i].ambientvolume;
1392                 }
1393         }
1394         else
1395         {
1396                 // calculate stereo seperation and distance attenuation
1397                 VectorSubtract(listener_origin, ch->origin, source_vec);
1398                 dist = VectorLength(source_vec);
1399                 f = dist * ch->distfade;
1400
1401                 f =
1402                         ((snd_attenuation_exponent.value == 0) ? 1.0 : pow(1.0 - min(1.0, f), (double)snd_attenuation_exponent.value))
1403                         *
1404                         ((snd_attenuation_decibel.value == 0) ? 1.0 : pow(0.1, 0.1 * snd_attenuation_decibel.value * f));
1405
1406                 intensity = mastervol * f;
1407                 if (intensity > 0)
1408                 {
1409                         qbool occluded = false;
1410                         if (snd_spatialization_occlusion.integer)
1411                         {
1412                                 if(snd_spatialization_occlusion.integer & 1)
1413                                         if(listener_pvs && cl.worldmodel)
1414                                         {
1415                                                 int cluster = cl.worldmodel->brush.PointInLeaf(cl.worldmodel, ch->origin)->clusterindex;
1416                                                 if(cluster >= 0 && cluster < 8 * listener_pvsbytes && !CHECKPVSBIT(listener_pvs, cluster))
1417                                                         occluded = true;
1418                                         }
1419
1420                                 if(snd_spatialization_occlusion.integer & 2)
1421                                         if(!occluded)
1422                                                 if(cl.worldmodel && cl.worldmodel->brush.TraceLineOfSight && !cl.worldmodel->brush.TraceLineOfSight(cl.worldmodel, listener_origin, ch->origin, ch->origin, ch->origin))
1423                                                         occluded = true;
1424                         }
1425                         if(occluded)
1426                                 intensity *= 0.5f;
1427
1428                         ch->prologic_invert = 1;
1429                         if (snd_spatialization_prologic.integer != 0)
1430                         {
1431                                 if (dist == 0)
1432                                         angle_factor = 0.5f;
1433                                 else
1434                                 {
1435                                         Matrix4x4_Transform(&listener_basematrix, ch->origin, source_vec);
1436                                         VectorNormalize(source_vec);
1437
1438                                         switch(spatialmethod)
1439                                         {
1440                                                 case SPATIAL_LOG:
1441                                                         if(dist == 0)
1442                                                                 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1443                                                         else
1444                                                                 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1445                                                         VectorScale(source_vec, f, source_vec);
1446                                                         break;
1447                                                 case SPATIAL_POW:
1448                                                         f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1449                                                         f = spatialmin + spatialdiff * bound(0, f, 1);
1450                                                         VectorScale(source_vec, f, source_vec);
1451                                                         break;
1452                                                 case SPATIAL_THRESH:
1453                                                         f = spatialmin + spatialdiff * (dist < spatialoffset);
1454                                                         VectorScale(source_vec, f, source_vec);
1455                                                         break;
1456                                                 case SPATIAL_NONE:
1457                                                 default:
1458                                                         break;
1459                                         }
1460
1461                                         // 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
1462                                         source_vec[2] = 0;
1463                                         VectorNormalize(source_vec);
1464                                         angle_side = acos(source_vec[0]) / M_PI * 180;  // angle between 0 and 180 degrees
1465                                         angle_front = asin(source_vec[1]) / M_PI * 180; // angle between -90 and 90 degrees
1466                                         if (angle_side > snd_spatialization_prologic_frontangle.value)
1467                                         {
1468                                                 ch->prologic_invert = -1;       // this will cause the right channel to do a 180 degrees phase shift (turning the sound wave upside down),
1469                                                                                                         // but the best would be 90 degrees phase shift left and a -90 degrees phase shift right.
1470                                                 angle_factor = (angle_side - snd_spatialization_prologic_frontangle.value) / (360 - 2 * snd_spatialization_prologic_frontangle.value);
1471                                                 // angle_factor is between 0 and 1 and represents the angle range from the front left, to all the surround speakers (amount may vary,
1472                                                 // 1 in prologic I 2 in prologic II and 3 or 4 in prologic IIx) to the front right speaker.
1473                                                 if (angle_front > 0)
1474                                                         angle_factor = 1 - angle_factor;
1475                                         }
1476                                         else
1477                                                 angle_factor = angle_front / snd_spatialization_prologic_frontangle.value / 2.0 + 0.5;
1478                                                 //angle_factor is between 0 and 1 and represents the angle range from the front left to the center to the front right speaker
1479                                 }
1480
1481                                 ch->volume[0] = intensity * sqrt(angle_factor);
1482                                 ch->volume[1] = intensity * sqrt(1 - angle_factor);
1483                                 for (i = 2;i < SND_LISTENERS;i++)
1484                                         ch->volume[i] = 0;
1485                         }
1486                         else
1487                         {
1488                                 for (i = 0;i < SND_LISTENERS;i++)
1489                                 {
1490                                         Matrix4x4_Transform(&listener_matrix[i], ch->origin, source_vec);
1491                                         VectorNormalize(source_vec);
1492
1493                                         switch(spatialmethod)
1494                                         {
1495                                                 case SPATIAL_LOG:
1496                                                         if(dist == 0)
1497                                                                 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1498                                                         else
1499                                                                 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1500                                                         VectorScale(source_vec, f, source_vec);
1501                                                         break;
1502                                                 case SPATIAL_POW:
1503                                                         f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1504                                                         f = spatialmin + spatialdiff * bound(0, f, 1);
1505                                                         VectorScale(source_vec, f, source_vec);
1506                                                         break;
1507                                                 case SPATIAL_THRESH:
1508                                                         f = spatialmin + spatialdiff * (dist < spatialoffset);
1509                                                         VectorScale(source_vec, f, source_vec);
1510                                                         break;
1511                                                 case SPATIAL_NONE:
1512                                                 default:
1513                                                         break;
1514                                         }
1515
1516                                         ch->volume[i] = intensity * max(0, source_vec[0] * snd_speakerlayout.listeners[i].dotscale + snd_speakerlayout.listeners[i].dotbias);
1517                                 }
1518                         }
1519                 }
1520                 else
1521                         for (i = 0;i < SND_LISTENERS;i++)
1522                                 ch->volume[i] = 0;
1523         }
1524 }
1525 static void SND_Spatialize(channel_t *ch, qbool isstatic)
1526 {
1527         sfx_t *sfx = ch->sfx;
1528         SND_Spatialize_WithSfx(ch, isstatic, sfx);
1529 }
1530
1531
1532 // =======================================================================
1533 // Start a sound effect
1534 // =======================================================================
1535
1536 static void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qbool isstatic, int entnum, int entchannel, int startpos, float fspeed)
1537 {
1538         if (!sfx)
1539         {
1540                 Con_Printf("S_PlaySfxOnChannel called with NULL??\n");
1541                 return;
1542         }
1543
1544         if ((sfx->loopstart < sfx->total_length) || (flags & CHANNELFLAG_FORCELOOP))
1545         {
1546                 if(!snd_startloopingsounds.integer)
1547                         return;
1548         }
1549         else
1550         {
1551                 if(!snd_startnonloopingsounds.integer)
1552                         return;
1553         }
1554
1555         // Initialize the channel
1556         // a crash was reported on an in-use channel, so check here...
1557         if (target_chan->sfx)
1558         {
1559                 int channelindex = (int)(target_chan - channels);
1560                 Con_Printf("S_PlaySfxOnChannel(%s): channel %i already in use??  Clearing.\n", sfx->name, channelindex);
1561                 S_StopChannel (channelindex, true, false);
1562         }
1563         // We MUST set sfx LAST because otherwise we could crash a threaded mixer
1564         // (otherwise we'd have to call SndSys_LockRenderBuffer here)
1565         memset (target_chan, 0, sizeof (*target_chan));
1566         VectorCopy (origin, target_chan->origin);
1567         target_chan->flags = flags;
1568         target_chan->position = startpos; // start of the sound
1569         target_chan->entnum = entnum;
1570         target_chan->entchannel = entchannel;
1571
1572         // If it's a static sound
1573         if (isstatic)
1574         {
1575                 if (sfx->loopstart >= sfx->total_length && (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEWORLD))
1576                         Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
1577                 target_chan->distfade = attenuation / (64.0f * snd_soundradius.value);
1578         }
1579         else
1580                 target_chan->distfade = attenuation / snd_soundradius.value;
1581
1582         // set the listener volumes
1583         S_SetChannelVolume(target_chan - channels, fvol);
1584         S_SetChannelSpeed(target_chan - channels, fspeed);
1585         SND_Spatialize_WithSfx (target_chan, isstatic, sfx);
1586
1587         // finally, set the sfx pointer, so the channel becomes valid for playback
1588         // and will be noticed by the mixer
1589         target_chan->sfx = sfx;
1590 }
1591
1592
1593 int S_StartSound_StartPosition_Flags (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation, float startposition, int flags, float fspeed)
1594 {
1595         channel_t *target_chan, *check, *ch;
1596         int             ch_idx, startpos, i;
1597
1598         if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1599                 return -1;
1600
1601         if(sfx == &changevolume_sfx)
1602         {
1603                 if (!IS_CHAN_SINGLE(entchannel))
1604                         return -1;
1605                 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1606                 {
1607                         ch = &channels[ch_idx];
1608                         if (ch->entnum == entnum && ch->entchannel == entchannel)
1609                         {
1610                                 S_SetChannelVolume(ch_idx, fvol);
1611                                 S_SetChannelSpeed(ch_idx, fspeed);
1612                                 for(i = 1; i > 0 && (i <= flags || i <= (int) channels[ch_idx].flags); i <<= 1)
1613                                         if((flags ^ channels[ch_idx].flags) & i)
1614                                                 S_SetChannelFlag(ch_idx, i, (flags & i) != 0);
1615                                 ch->distfade = attenuation / snd_soundradius.value;
1616                                 SND_Spatialize(ch, false);
1617                                 return ch_idx;
1618                         }
1619                 }
1620                 return -1;
1621         }
1622
1623         if (sfx->fetcher == NULL)
1624                 return -1;
1625
1626         // Pick a channel to play on
1627         target_chan = SND_PickChannel(entnum, entchannel);
1628         if (!target_chan)
1629                 return -1;
1630
1631         // if an identical sound has also been started this frame, offset the pos
1632         // a bit to keep it from just making the first one louder
1633         check = &channels[NUM_AMBIENTS];
1634         startpos = (int)(startposition * sfx->format.speed);
1635         if (startpos == 0)
1636         {
1637                 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
1638                 {
1639                         if (check == target_chan)
1640                                 continue;
1641                         if (check->sfx == sfx && check->position == 0 && check->basespeed == fspeed)
1642                         {
1643                                 // calculate max offset
1644                                 float maxtime = snd_identicalsoundrandomization_time.value;
1645                                 float maxtics = snd_identicalsoundrandomization_tics.value;
1646                                 float maxticsdelta = ((cls.state == ca_connected) ? (maxtics * (cl.mtime[0] - cl.mtime[1])) : 0);
1647                                 float maxdelta = 0;
1648                                 if(maxticsdelta == 0 || fabs(maxticsdelta) > fabs(maxtime))
1649                                         maxdelta = maxtime;
1650                                 else
1651                                         maxdelta = fabs(maxticsdelta) * ((maxtime > 0) ? 1 : -1);
1652
1653                                 // use negative pos offset to delay this sound effect
1654                                 startpos = lhrandom(0, maxdelta * sfx->format.speed);
1655                                 break;
1656                         }
1657                 }
1658         }
1659
1660         S_PlaySfxOnChannel (sfx, target_chan, flags, origin, fvol, attenuation, false, entnum, entchannel, startpos, fspeed);
1661
1662         return (target_chan - channels);
1663 }
1664
1665 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1666 {
1667         return S_StartSound_StartPosition_Flags(entnum, entchannel, sfx, origin, fvol, attenuation, 0, CHANNELFLAG_NONE, 1.0f);
1668 }
1669
1670 void S_StopChannel (unsigned int channel_ind, qbool lockmutex, qbool freesfx)
1671 {
1672         channel_t *ch;
1673         sfx_t *sfx;
1674
1675         if (channel_ind >= total_channels)
1676                 return;
1677
1678         // we have to lock an audio mutex to prevent crashes if an audio mixer
1679         // thread is currently mixing this channel
1680         // the SndSys_LockRenderBuffer function uses such a mutex in
1681         // threaded sound backends
1682         if (lockmutex && !simsound)
1683                 SndSys_LockRenderBuffer();
1684         
1685         ch = &channels[channel_ind];
1686         sfx = ch->sfx;
1687         if (sfx != NULL)
1688         {
1689                 if (sfx->fetcher != NULL && sfx->fetcher->stopchannel != NULL)
1690                         sfx->fetcher->stopchannel(ch);
1691                 ch->fetcher_data = NULL;
1692                 ch->sfx = NULL;
1693                 if (freesfx)
1694                         S_FreeSfx(sfx, true);
1695         }
1696         if (lockmutex && !simsound)
1697                 SndSys_UnlockRenderBuffer();
1698 }
1699
1700
1701 qbool S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qbool value)
1702 {
1703         if (ch_ind >= total_channels)
1704                 return false;
1705
1706         if (flag != CHANNELFLAG_FORCELOOP &&
1707                 flag != CHANNELFLAG_PAUSED &&
1708                 flag != CHANNELFLAG_FULLVOLUME &&
1709                 flag != CHANNELFLAG_LOCALSOUND)
1710                 return false;
1711
1712         if (value)
1713                 channels[ch_ind].flags |= flag;
1714         else
1715                 channels[ch_ind].flags &= ~flag;
1716
1717         return true;
1718 }
1719
1720 void S_StopSound(int entnum, int entchannel)
1721 {
1722         unsigned int i;
1723
1724         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
1725                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
1726                 {
1727                         S_StopChannel (i, true, false);
1728                         return;
1729                 }
1730 }
1731
1732 void S_StopAllSounds(void)
1733 {
1734         unsigned int i;
1735
1736         // TOCHECK: is this test necessary?
1737         if (snd_renderbuffer == NULL)
1738                 return;
1739
1740         // stop CD audio because it may be using a faketrack
1741         CDAudio_Stop();
1742
1743         if (simsound || SndSys_LockRenderBuffer ())
1744         {
1745                 int clear;
1746                 size_t memsize;
1747
1748                 for (i = 0; i < total_channels; i++)
1749                         if (channels[i].sfx)
1750                                 S_StopChannel (i, false, false);
1751
1752                 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
1753                 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
1754
1755                 // Mute the contents of the submittion buffer
1756                 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1757                 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1758                 memset(snd_renderbuffer->ring, clear, memsize);
1759
1760                 if (!simsound)
1761                         SndSys_UnlockRenderBuffer ();
1762         }
1763 }
1764
1765 void S_StopAllSounds_f(cmd_state_t *cmd)
1766 {
1767         S_StopAllSounds();
1768 }
1769
1770
1771 void S_PauseGameSounds (qbool toggle)
1772 {
1773         unsigned int i;
1774
1775         for (i = 0; i < total_channels; i++)
1776         {
1777                 channel_t *ch;
1778
1779                 ch = &channels[i];
1780                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
1781                         S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
1782         }
1783 }
1784
1785 void S_SetChannelVolume(unsigned int ch_ind, float fvol)
1786 {
1787         channels[ch_ind].basevolume = fvol;
1788 }
1789
1790 void S_SetChannelSpeed(unsigned int ch_ind, float fspeed)
1791 {
1792         channels[ch_ind].basespeed = fspeed;
1793 }
1794
1795 float S_GetChannelPosition (unsigned int ch_ind)
1796 {
1797         // note: this is NOT accurate yet
1798         double s;
1799         channel_t *ch = &channels[ch_ind];
1800         sfx_t *sfx = ch->sfx;
1801         if (!sfx)
1802                 return -1;
1803
1804         s = ch->position / sfx->format.speed;
1805         /*
1806         if(!snd_usethreadedmixing)
1807                 s += _snd_mixahead.value;
1808         */
1809         return (float)s;
1810 }
1811
1812 float S_GetEntChannelPosition(int entnum, int entchannel)
1813 {
1814         channel_t *ch;
1815         unsigned int i;
1816
1817         for (i = 0; i < total_channels; i++)
1818         {
1819                 ch = &channels[i];
1820                 if (ch->entnum == entnum && ch->entchannel == entchannel)
1821                         return S_GetChannelPosition(i);
1822         }
1823         return -1; // no playing sound in this channel
1824 }
1825
1826 /*
1827 =================
1828 S_StaticSound
1829 =================
1830 */
1831 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1832 {
1833         channel_t       *target_chan;
1834
1835         if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1836                 return;
1837         if (!sfx->fetcher)
1838         {
1839                 Con_Printf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
1840                 return;
1841         }
1842
1843         if (total_channels == MAX_CHANNELS)
1844         {
1845                 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
1846                 return;
1847         }
1848
1849         target_chan = &channels[total_channels++];
1850         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true, 0, 0, 0, 1.0f);
1851 }
1852
1853
1854 /*
1855 ===================
1856 S_UpdateAmbientSounds
1857 ===================
1858 */
1859 static void S_UpdateAmbientSounds (void)
1860 {
1861         int                     i;
1862         float           vol;
1863         float           fade = (float)max(0.0, cl.time - cl.oldtime) * ambient_fade.value / 256.0f;
1864         int                     ambient_channel;
1865         channel_t       *chan;
1866         unsigned char           ambientlevels[NUM_AMBIENTS];
1867         sfx_t           *sfx;
1868
1869         memset(ambientlevels, 0, sizeof(ambientlevels));
1870         if (cl.worldmodel && cl.worldmodel->brush.AmbientSoundLevelsForPoint)
1871                 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
1872
1873         // Calc ambient sound levels
1874         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
1875         {
1876                 chan = &channels[ambient_channel];
1877                 sfx = chan->sfx; // fetch the volatile variable
1878                 if (sfx == NULL || sfx->fetcher == NULL)
1879                         continue;
1880
1881                 i = ambientlevels[ambient_channel];
1882                 if (i < 8)
1883                         i = 0;
1884                 vol = i * (1.0f / 256.0f);
1885
1886                 // Don't adjust volume too fast
1887                 if (chan->basevolume < vol)
1888                 {
1889                         chan->basevolume += fade;
1890                         if (chan->basevolume > vol)
1891                                 chan->basevolume = vol;
1892                 }
1893                 else if (chan->basevolume > vol)
1894                 {
1895                         chan->basevolume -= fade;
1896                         if (chan->basevolume < vol)
1897                                 chan->basevolume = vol;
1898                 }
1899
1900                 if (snd_spatialization_prologic.integer != 0)
1901                 {
1902                         chan->volume[0] = chan->basevolume * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5);
1903                         chan->volume[1] = chan->basevolume * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5);
1904                         for (i = 2;i < SND_LISTENERS;i++)
1905                                 chan->volume[i] = 0.0f;
1906                 }
1907                 else
1908                 {
1909                         for (i = 0;i < SND_LISTENERS;i++)
1910                                 chan->volume[i] = chan->basevolume * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[i].ambientvolume;
1911                 }
1912         }
1913 }
1914
1915 static void S_PaintAndSubmit (void)
1916 {
1917         unsigned int newsoundtime, paintedtime, endtime, maxtime, usedframes;
1918         int usesoundtimehack;
1919         static int soundtimehack = -1;
1920         static int oldsoundtime = 0;
1921
1922         if (snd_renderbuffer == NULL || nosound.integer)
1923                 return;
1924
1925         // Update sound time
1926         snd_usethreadedmixing = false;
1927         usesoundtimehack = true;
1928         if (cls.timedemo) // SUPER NASTY HACK to mix non-realtime sound for more reliable benchmarking
1929         {
1930                 usesoundtimehack = 1;
1931                 newsoundtime = (unsigned int)((double)cl.mtime[0] * (double)snd_renderbuffer->format.speed);
1932         }
1933 #ifdef CONFIG_VIDEO_CAPTURE
1934         else if (cls.capturevideo.soundrate && !cls.capturevideo.realtime) // SUPER NASTY HACK to record non-realtime sound
1935         {
1936                 usesoundtimehack = 2;
1937                 newsoundtime = (unsigned int)((double)cls.capturevideo.frame * (double)snd_renderbuffer->format.speed / (double)cls.capturevideo.framerate);
1938         }
1939 #endif
1940         else if (simsound)
1941         {
1942                 usesoundtimehack = 3;
1943                 newsoundtime = (unsigned int)((host.realtime - snd_starttime) * (double)snd_renderbuffer->format.speed);
1944         }
1945         else
1946         {
1947 #ifdef CONFIG_VIDEO_CAPTURE
1948                 snd_usethreadedmixing = snd_threaded && !cls.capturevideo.soundrate;
1949 #else
1950                 snd_usethreadedmixing = snd_threaded;
1951 #endif
1952                 usesoundtimehack = 0;
1953                 newsoundtime = SndSys_GetSoundTime();
1954         }
1955         // if the soundtimehack state changes we need to reset the soundtime
1956         if (soundtimehack != usesoundtimehack)
1957         {
1958                 snd_renderbuffer->startframe = snd_renderbuffer->endframe = soundtime = newsoundtime;
1959
1960                 // Mute the contents of the submission buffer
1961                 if (simsound || SndSys_LockRenderBuffer ())
1962                 {
1963                         int clear;
1964                         size_t memsize;
1965
1966                         clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1967                         memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1968                         memset(snd_renderbuffer->ring, clear, memsize);
1969
1970                         if (!simsound)
1971                                 SndSys_UnlockRenderBuffer ();
1972                 }
1973         }
1974         soundtimehack = usesoundtimehack;
1975
1976         if (!soundtimehack && snd_blocked > 0)
1977                 return;
1978
1979         if (snd_usethreadedmixing)
1980                 return; // the audio thread will mix its own data
1981
1982         newsoundtime += extrasoundtime;
1983         if (newsoundtime < soundtime)
1984         {
1985 #ifdef CONFIG_VIDEO_CAPTURE
1986                 if ((cls.capturevideo.soundrate != 0) != recording_sound)
1987                 {
1988                         unsigned int additionaltime;
1989
1990                         // add some time to extrasoundtime make newsoundtime higher
1991
1992                         // The extra time must be a multiple of the render buffer size
1993                         // to avoid modifying the current position in the buffer,
1994                         // some modules write directly to a shared (DMA) buffer
1995                         additionaltime = (soundtime - newsoundtime) + snd_renderbuffer->maxframes - 1;
1996                         additionaltime -= additionaltime % snd_renderbuffer->maxframes;
1997
1998                         extrasoundtime += additionaltime;
1999                         newsoundtime += additionaltime;
2000                         Con_DPrintf("S_PaintAndSubmit: new extra sound time = %u\n",
2001                                                 extrasoundtime);
2002                 }
2003                 else if (!soundtimehack)
2004 #else
2005                 if (!soundtimehack)
2006 #endif
2007                         Con_Printf("S_PaintAndSubmit: WARNING: newsoundtime < soundtime (%u < %u)\n",
2008                                            newsoundtime, soundtime);
2009         }
2010         soundtime = newsoundtime;
2011 #ifdef CONFIG_VIDEO_CAPTURE
2012         recording_sound = (cls.capturevideo.soundrate != 0);
2013 #endif
2014
2015         // Lock submitbuffer
2016         if (!simsound && !SndSys_LockRenderBuffer())
2017         {
2018                 // If the lock failed, stop here
2019                 Con_DPrint(">> S_PaintAndSubmit: SndSys_LockRenderBuffer() failed\n");
2020                 return;
2021         }
2022
2023         // Check to make sure that we haven't overshot
2024         paintedtime = snd_renderbuffer->endframe;
2025         if (paintedtime < soundtime)
2026                 paintedtime = soundtime;
2027
2028         // mix ahead of current position
2029         if (soundtimehack)
2030                 endtime = soundtime + (unsigned int)(_snd_mixahead.value * (float)snd_renderbuffer->format.speed);
2031         else
2032                 endtime = soundtime + (unsigned int)(max(_snd_mixahead.value * (float)snd_renderbuffer->format.speed, min(3 * (soundtime - oldsoundtime), 0.3 * (float)snd_renderbuffer->format.speed)));
2033         usedframes = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
2034         maxtime = paintedtime + snd_renderbuffer->maxframes - usedframes;
2035         endtime = min(endtime, maxtime);
2036
2037         while (paintedtime < endtime)
2038         {
2039                 unsigned int startoffset;
2040                 unsigned int nbframes;
2041
2042                 // see how much we can fit in the paint buffer
2043                 nbframes = endtime - paintedtime;
2044                 // limit to the end of the ring buffer (in case of wrapping)
2045                 startoffset = paintedtime % snd_renderbuffer->maxframes;
2046                 nbframes = min(nbframes, snd_renderbuffer->maxframes - startoffset);
2047
2048                 // mix into the buffer
2049                 S_MixToBuffer(&snd_renderbuffer->ring[startoffset * snd_renderbuffer->format.width * snd_renderbuffer->format.channels], nbframes);
2050
2051                 paintedtime += nbframes;
2052                 snd_renderbuffer->endframe = paintedtime;
2053         }
2054         if (!simsound)
2055                 SndSys_UnlockRenderBuffer();
2056
2057         // Remove outdated samples from the ring buffer, if any
2058         if (snd_renderbuffer->startframe < soundtime)
2059                 snd_renderbuffer->startframe = soundtime;
2060
2061         if (simsound)
2062                 snd_renderbuffer->startframe = snd_renderbuffer->endframe;
2063         else
2064                 SndSys_Submit();
2065
2066         oldsoundtime = soundtime;
2067
2068         cls.soundstats.latency_milliseconds = (snd_renderbuffer->endframe - snd_renderbuffer->startframe) * 1000 / snd_renderbuffer->format.speed;
2069         R_TimeReport("audiomix");
2070 }
2071
2072 /*
2073 ============
2074 S_Update
2075
2076 Called once each time through the main loop
2077 ============
2078 */
2079 void S_Update(const matrix4x4_t *listenermatrix)
2080 {
2081         unsigned int i, j, k;
2082         channel_t *ch, *combine;
2083         matrix4x4_t rotatematrix;
2084
2085         if (snd_renderbuffer == NULL || nosound.integer)
2086                 return;
2087
2088         {
2089                 double mindist_trans, maxdist_trans;
2090
2091                 spatialmin = snd_spatialization_min.value;
2092                 spatialdiff = snd_spatialization_max.value - spatialmin;
2093
2094                 if(snd_spatialization_control.value)
2095                 {
2096                         spatialpower = snd_spatialization_power.value;
2097
2098                         if(spatialpower == 0)
2099                         {
2100                                 spatialmethod = SPATIAL_LOG;
2101                                 mindist_trans = log(max(1, snd_spatialization_min_radius.value));
2102                                 maxdist_trans = log(max(1, snd_spatialization_max_radius.value));
2103                         }
2104                         else
2105                         {
2106                                 spatialmethod = SPATIAL_POW;
2107                                 mindist_trans = pow(snd_spatialization_min_radius.value, spatialpower);
2108                                 maxdist_trans = pow(snd_spatialization_max_radius.value, spatialpower);
2109                         }
2110
2111                         if(mindist_trans - maxdist_trans == 0)
2112                         {
2113                                 spatialmethod = SPATIAL_THRESH;
2114                                 mindist_trans = snd_spatialization_min_radius.value;
2115                         }
2116                         else
2117                         {
2118                                 spatialoffset = mindist_trans;
2119                                 spatialfactor = 1 / (maxdist_trans - mindist_trans);
2120                         }
2121                 }
2122                 else
2123                         spatialmethod = SPATIAL_NONE;
2124
2125         }
2126
2127         // If snd_swapstereo or snd_channellayout has changed, recompute the channel layout
2128         if (current_swapstereo != boolxor(snd_swapstereo.integer, v_flipped.integer) ||
2129                 current_channellayout != snd_channellayout.integer)
2130                 S_SetChannelLayout();
2131
2132         Matrix4x4_Invert_Simple(&listener_basematrix, listenermatrix);
2133         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
2134         if (cl.worldmodel && cl.worldmodel->brush.FatPVS && cl.worldmodel->brush.num_pvsclusterbytes && cl.worldmodel->brush.PointInLeaf)
2135         {
2136                 if(cl.worldmodel->brush.num_pvsclusterbytes != listener_pvsbytes)
2137                 {
2138                         if(listener_pvs)
2139                                 Mem_Free(listener_pvs);
2140                         listener_pvsbytes = cl.worldmodel->brush.num_pvsclusterbytes;
2141                         listener_pvs = (unsigned char *) Mem_Alloc(snd_mempool, listener_pvsbytes);
2142                 }
2143                 cl.worldmodel->brush.FatPVS(cl.worldmodel, listener_origin, 2, listener_pvs, listener_pvsbytes, 0);
2144         }
2145         else
2146         {
2147                 if(listener_pvs)
2148                 {
2149                         Mem_Free(listener_pvs);
2150                         listener_pvs = NULL;
2151                 }
2152                 listener_pvsbytes = 0;
2153         }
2154
2155         // calculate the current matrices
2156         for (j = 0;j < SND_LISTENERS;j++)
2157         {
2158                 Matrix4x4_CreateFromQuakeEntity(&rotatematrix, 0, 0, 0, 0, -snd_speakerlayout.listeners[j].yawangle, 0, 1);
2159                 Matrix4x4_Concat(&listener_matrix[j], &rotatematrix, &listener_basematrix);
2160                 // I think this should now do this:
2161                 //   1. create a rotation matrix for rotating by e.g. -90 degrees CCW
2162                 //      (note: the matrix will rotate the OBJECT, not the VIEWER, so its
2163                 //       angle has to be taken negative)
2164                 //   2. create a transform which first rotates and moves its argument
2165                 //      into the player's view coordinates (using basematrix which is
2166                 //      an inverted "absolute" listener matrix), then applies the
2167                 //      rotation matrix for the ear
2168                 // Isn't Matrix4x4_CreateFromQuakeEntity a bit misleading because this
2169                 // does not actually refer to an entity?
2170         }
2171
2172         // update general area ambient sound sources
2173         S_UpdateAmbientSounds ();
2174
2175         combine = NULL;
2176         R_TimeReport("audioprep");
2177
2178         // update spatialization for static and dynamic sounds
2179         cls.soundstats.totalsounds = 0;
2180         cls.soundstats.mixedsounds = 0;
2181         ch = channels+NUM_AMBIENTS;
2182         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
2183         {
2184                 if (!ch->sfx)
2185                         continue;
2186                 cls.soundstats.totalsounds++;
2187
2188                 // respatialize channel
2189                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);
2190
2191                 // try to combine static sounds with a previous channel of the same
2192                 // sound effect so we don't mix five torches every frame
2193                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
2194                 {
2195                         // no need to merge silent channels
2196                         for (j = 0;j < SND_LISTENERS;j++)
2197                                 if (ch->volume[j])
2198                                         break;
2199                         if (j == SND_LISTENERS)
2200                                 continue;
2201                         // if the last combine chosen isn't suitable, find a new one
2202                         if (!(combine && combine != ch && combine->sfx == ch->sfx))
2203                         {
2204                                 // search for one
2205                                 combine = NULL;
2206                                 for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;j < i;j++)
2207                                 {
2208                                         if (channels[j].sfx == ch->sfx)
2209                                         {
2210                                                 combine = channels + j;
2211                                                 break;
2212                                         }
2213                                 }
2214                         }
2215                         if (combine && combine != ch && combine->sfx == ch->sfx)
2216                         {
2217                                 for (j = 0;j < SND_LISTENERS;j++)
2218                                 {
2219                                         combine->volume[j] += ch->volume[j];
2220                                         ch->volume[j] = 0;
2221                                 }
2222                         }
2223                 }
2224                 for (k = 0;k < SND_LISTENERS;k++)
2225                         if (ch->volume[k])
2226                                 break;
2227                 if (k < SND_LISTENERS)
2228                         cls.soundstats.mixedsounds++;
2229         }
2230         R_TimeReport("audiospatialize");
2231
2232         sound_spatialized = true;
2233
2234         // debugging output
2235         if (snd_show.integer)
2236                 Con_Printf("----(%u)----\n", cls.soundstats.mixedsounds);
2237
2238         S_PaintAndSubmit();
2239 }
2240
2241 void S_ExtraUpdate (void)
2242 {
2243         if (snd_noextraupdate.integer || !sound_spatialized)
2244                 return;
2245
2246         S_PaintAndSubmit();
2247 }
2248
2249 qbool S_LocalSoundEx (const char *sound, int chan, float fvol)
2250 {
2251         sfx_t   *sfx;
2252         int             ch_ind;
2253
2254         if (!snd_initialized.integer || nosound.integer)
2255                 return true;
2256
2257         sfx = S_PrecacheSound (sound, true, false);
2258         if (!sfx)
2259         {
2260                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
2261                 return false;
2262         }
2263
2264         // menu sounds must not be freed on level change
2265         sfx->flags |= SFXFLAG_MENUSOUND;
2266
2267         // fun fact: in Quake 1, this used -1 "replace any entity channel",
2268         // which we no longer support anyway
2269         // changed by Black in r4297 "Changed S_LocalSound to play multiple sounds at a time."
2270         ch_ind = S_StartSound (cl.viewentity, chan, sfx, vec3_origin, fvol, 0);
2271         if (ch_ind < 0)
2272                 return false;
2273
2274         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
2275         return true;
2276 }
2277
2278 qbool S_LocalSound (const char *sound)
2279 {
2280         return S_LocalSoundEx(sound, 0, 1);
2281 }