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