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