]> git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_main.c
new cvar: snd_streaming_length ("don't stream sound files below this length")
[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(&ambient_level);
881         Cvar_RegisterVariable(&ambient_fade);
882         Cvar_RegisterVariable(&snd_noextraupdate);
883         Cvar_RegisterVariable(&snd_show);
884         Cvar_RegisterVariable(&_snd_mixahead);
885         Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
886         Cvar_RegisterVariable(&snd_channellayout);
887         Cvar_RegisterVariable(&snd_soundradius);
888
889         Cvar_SetValueQuick(&snd_initialized, true);
890
891         known_sfx = NULL;
892
893         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
894         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
895
896         OGG_OpenLibrary ();
897         ModPlug_OpenLibrary ();
898 }
899
900
901 /*
902 ================
903 S_Terminate
904
905 Shutdown and free all resources
906 ================
907 */
908 void S_Terminate (void)
909 {
910         S_Shutdown ();
911         ModPlug_CloseLibrary ();
912         OGG_CloseLibrary ();
913
914         // Free all SFXs
915         while (known_sfx != NULL)
916                 S_FreeSfx (known_sfx, true);
917
918         Cvar_SetValueQuick (&snd_initialized, false);
919         Mem_FreePool (&snd_mempool);
920 }
921
922
923 /*
924 ==================
925 S_UnloadAllSounds_f
926 ==================
927 */
928 void S_UnloadAllSounds_f (void)
929 {
930         int i;
931
932         // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
933         // So, refuse to do this if we are connected.
934         if(cls.state == ca_connected)
935         {
936                 Con_Printf("snd_unloadallsounds would wreak havoc if you do that while connected!\n");
937                 return;
938         }
939
940         // stop any active sounds
941         S_StopAllSounds();
942
943         // because the ambient sounds will be freed, clear the pointers
944         for (i = 0;i < (int)sizeof (ambient_sfxs) / (int)sizeof (ambient_sfxs[0]);i++)
945                 ambient_sfxs[i] = NULL;
946
947         // now free all sounds
948         while (known_sfx != NULL)
949                 S_FreeSfx (known_sfx, true);
950 }
951
952
953 /*
954 ==================
955 S_FindName
956 ==================
957 */
958 sfx_t changevolume_sfx = {""};
959 sfx_t *S_FindName (const char *name)
960 {
961         sfx_t *sfx;
962
963         if (!snd_initialized.integer)
964                 return NULL;
965
966         if(!strcmp(name, changevolume_sfx.name))
967                 return &changevolume_sfx;
968
969         if (strlen (name) >= sizeof (sfx->name))
970         {
971                 Con_Printf ("S_FindName: sound name too long (%s)\n", name);
972                 return NULL;
973         }
974
975         // Look for this sound in the list of known sfx
976         // TODO: hash table search?
977         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
978                 if(!strcmp (sfx->name, name))
979                         return sfx;
980
981         // check for # in the beginning, try lookup by soundindex
982         if (name[0] == '#' && name[1])
983         {
984                 int soundindex = atoi(name + 1);
985                 if (soundindex > 0 && soundindex < MAX_SOUNDS)
986                         if (cl.sound_precache[soundindex]->name[0])
987                                 return cl.sound_precache[soundindex];
988         }
989
990         // Add a sfx_t struct for this sound
991         sfx = (sfx_t *)Mem_Alloc (snd_mempool, sizeof (*sfx));
992         memset (sfx, 0, sizeof(*sfx));
993         strlcpy (sfx->name, name, sizeof (sfx->name));
994         sfx->memsize = sizeof(*sfx);
995         sfx->next = known_sfx;
996         known_sfx = sfx;
997
998         return sfx;
999 }
1000
1001
1002 /*
1003 ==================
1004 S_FreeSfx
1005 ==================
1006 */
1007 void S_FreeSfx (sfx_t *sfx, qboolean force)
1008 {
1009         unsigned int i;
1010
1011         // Do not free a precached sound during purge
1012         if (!force && (sfx->flags & (SFXFLAG_LEVELSOUND | SFXFLAG_MENUSOUND)))
1013                 return;
1014
1015         if (developer_loading.integer)
1016                 Con_Printf ("unloading sound %s\n", sfx->name);
1017
1018         // Remove it from the list of known sfx
1019         if (sfx == known_sfx)
1020                 known_sfx = known_sfx->next;
1021         else
1022         {
1023                 sfx_t *prev_sfx;
1024
1025                 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
1026                         if (prev_sfx->next == sfx)
1027                         {
1028                                 prev_sfx->next = sfx->next;
1029                                 break;
1030                         }
1031                 if (prev_sfx == NULL)
1032                 {
1033                         Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
1034                         return;
1035                 }
1036         }
1037
1038         // Stop all channels using this sfx
1039         for (i = 0; i < total_channels; i++)
1040         {
1041                 if (channels[i].sfx == sfx)
1042                 {
1043                         Con_Printf("S_FreeSfx: stopping channel %i for sfx \"%s\"\n", i, sfx->name);
1044                         S_StopChannel (i, true, false);
1045                 }
1046         }
1047
1048         // Free it
1049         if (sfx->fetcher != NULL && sfx->fetcher->free != NULL)
1050                 sfx->fetcher->free (sfx->fetcher_data);
1051         Mem_Free (sfx);
1052 }
1053
1054
1055 /*
1056 ==================
1057 S_ClearUsed
1058 ==================
1059 */
1060 void S_ClearUsed (void)
1061 {
1062         sfx_t *sfx;
1063 //      sfx_t *sfxnext;
1064         unsigned int i;
1065
1066         // Start the ambient sounds and make them loop
1067         for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
1068         {
1069                 // Precache it if it's not done (and pass false for levelsound because these are permanent)
1070                 if (ambient_sfxs[i] == NULL)
1071                         ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, false);
1072                 if (ambient_sfxs[i] != NULL)
1073                 {
1074                         channels[i].sfx = ambient_sfxs[i];
1075                         channels[i].sfx->flags |= SFXFLAG_MENUSOUND;
1076                         channels[i].flags |= CHANNELFLAG_FORCELOOP;
1077                         channels[i].master_vol = 0;
1078                 }
1079         }
1080
1081         // Clear SFXFLAG_LEVELSOUND flag so that sounds not precached this level will be purged
1082         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
1083                 sfx->flags &= ~SFXFLAG_LEVELSOUND;
1084 }
1085
1086 /*
1087 ==================
1088 S_PurgeUnused
1089 ==================
1090 */
1091 void S_PurgeUnused(void)
1092 {
1093         sfx_t *sfx;
1094         sfx_t *sfxnext;
1095
1096         // Free all not-precached per-level sfx
1097         for (sfx = known_sfx;sfx;sfx = sfxnext)
1098         {
1099                 sfxnext = sfx->next;
1100                 if (!(sfx->flags & (SFXFLAG_LEVELSOUND | SFXFLAG_MENUSOUND)))
1101                         S_FreeSfx (sfx, false);
1102         }
1103 }
1104
1105
1106 /*
1107 ==================
1108 S_PrecacheSound
1109 ==================
1110 */
1111 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean levelsound)
1112 {
1113         sfx_t *sfx;
1114
1115         if (!snd_initialized.integer)
1116                 return NULL;
1117
1118         if (name == NULL || name[0] == 0)
1119                 return NULL;
1120
1121         sfx = S_FindName (name);
1122
1123         if (sfx == NULL)
1124                 return NULL;
1125
1126         // clear the FILEMISSING flag so that S_LoadSound will try again on a
1127         // previously missing file
1128         sfx->flags &= ~ SFXFLAG_FILEMISSING;
1129
1130         // set a flag to indicate this has been precached for this level or permanently
1131         if (levelsound)
1132                 sfx->flags |= SFXFLAG_LEVELSOUND;
1133         else
1134                 sfx->flags |= SFXFLAG_MENUSOUND;
1135
1136         if (!nosound.integer && snd_precache.integer)
1137                 S_LoadSound(sfx, complain);
1138
1139         return sfx;
1140 }
1141
1142 /*
1143 ==================
1144 S_SoundLength
1145 ==================
1146 */
1147
1148 float S_SoundLength(const char *name)
1149 {
1150         sfx_t *sfx;
1151
1152         if (!snd_initialized.integer)
1153                 return -1;
1154         if (name == NULL || name[0] == 0)
1155                 return -1;
1156
1157         sfx = S_FindName(name);
1158         if (sfx == NULL)
1159                 return -1;
1160         return sfx->total_length / (float) S_GetSoundRate();
1161 }
1162
1163 /*
1164 ==================
1165 S_IsSoundPrecached
1166 ==================
1167 */
1168 qboolean S_IsSoundPrecached (const sfx_t *sfx)
1169 {
1170         return (sfx != NULL && sfx->fetcher != NULL) || (sfx == &changevolume_sfx);
1171 }
1172
1173 /*
1174 ==================
1175 S_BlockSound
1176 ==================
1177 */
1178 void S_BlockSound (void)
1179 {
1180         snd_blocked++;
1181 }
1182
1183
1184 /*
1185 ==================
1186 S_UnblockSound
1187 ==================
1188 */
1189 void S_UnblockSound (void)
1190 {
1191         snd_blocked--;
1192 }
1193
1194
1195 /*
1196 =================
1197 SND_PickChannel
1198
1199 Picks a channel based on priorities, empty slots, number of channels
1200 =================
1201 */
1202 channel_t *SND_PickChannel(int entnum, int entchannel)
1203 {
1204         int ch_idx;
1205         int first_to_die;
1206         int first_life_left, life_left;
1207         channel_t* ch;
1208         sfx_t *sfx; // use this instead of ch->sfx->, because that is volatile.
1209
1210 // Check for replacement sound, or find the best one to replace
1211         first_to_die = -1;
1212         first_life_left = 0x7fffffff;
1213
1214         // entity channels try to replace the existing sound on the channel
1215         // channels <= 0 are autochannels
1216         if (IS_CHAN_SINGLE(entchannel))
1217         {
1218                 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1219                 {
1220                         ch = &channels[ch_idx];
1221                         if (ch->entnum == entnum && ch->entchannel == entchannel)
1222                         {
1223                                 // always override sound from same entity
1224                                 S_StopChannel (ch_idx, true, false);
1225                                 return &channels[ch_idx];
1226                         }
1227                 }
1228         }
1229
1230         // there was no channel to override, so look for the first empty one
1231         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1232         {
1233                 ch = &channels[ch_idx];
1234                 sfx = ch->sfx; // fetch the volatile variable
1235                 if (!sfx)
1236                 {
1237                         // no sound on this channel
1238                         first_to_die = ch_idx;
1239                         goto emptychan_found;
1240                 }
1241
1242                 // don't let monster sounds override player sounds
1243                 if (ch->entnum == cl.viewentity && entnum != cl.viewentity)
1244                         continue;
1245
1246                 // don't override looped sounds
1247                 if ((ch->flags & CHANNELFLAG_FORCELOOP) || sfx->loopstart < sfx->total_length)
1248                         continue;
1249                 life_left = sfx->total_length - ch->pos;
1250
1251                 if (life_left < first_life_left)
1252                 {
1253                         first_life_left = life_left;
1254                         first_to_die = ch_idx;
1255                 }
1256         }
1257
1258         if (first_to_die == -1)
1259                 return NULL;
1260         
1261         S_StopChannel (first_to_die, true, false);
1262
1263 emptychan_found:
1264         return &channels[first_to_die];
1265 }
1266
1267 /*
1268 =================
1269 SND_Spatialize
1270
1271 Spatializes a channel
1272 =================
1273 */
1274 extern cvar_t cl_gameplayfix_soundsmovewithentities;
1275 void SND_Spatialize_WithSfx(channel_t *ch, qboolean isstatic, sfx_t *sfx)
1276 {
1277         int i;
1278         double f;
1279         float angle_side, angle_front, angle_factor;
1280         vec_t dist, mastervol, intensity, vol;
1281         vec3_t source_vec;
1282
1283         // update sound origin if we know about the entity
1284         if (ch->entnum > 0 && cls.state == ca_connected && cl_gameplayfix_soundsmovewithentities.integer)
1285         {
1286                 if (ch->entnum >= MAX_EDICTS)
1287                 {
1288                         //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]);
1289
1290                         if (ch->entnum > MAX_EDICTS)
1291                                 if (!CL_VM_GetEntitySoundOrigin(ch->entnum, ch->origin))
1292                                         ch->entnum = MAX_EDICTS; // entity was removed, disown sound
1293                 }
1294                 else if (cl.entities[ch->entnum].state_current.active)
1295                 {
1296                         dp_model_t *model;
1297                         //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]);
1298                         model = CL_GetModelByIndex(cl.entities[ch->entnum].state_current.modelindex);
1299                         if (model && model->soundfromcenter)
1300                                 VectorMAM(0.5f, cl.entities[ch->entnum].render.mins, 0.5f, cl.entities[ch->entnum].render.maxs, ch->origin);
1301                         else
1302                                 Matrix4x4_OriginFromMatrix(&cl.entities[ch->entnum].render.matrix, ch->origin);
1303                 }
1304         }
1305
1306         mastervol = ch->master_vol;
1307
1308         // Adjust volume of static sounds
1309         if (isstatic)
1310                 mastervol *= snd_staticvolume.value;
1311         else if(!(ch->flags & CHANNELFLAG_FULLVOLUME)) // same as SND_PaintChannel uses
1312         {
1313                 // old legacy separated cvars
1314                 if(ch->entnum >= MAX_EDICTS)
1315                 {
1316                         switch(ch->entchannel)
1317                         {
1318                                 case 0: mastervol *= snd_csqcchannel0volume.value; break;
1319                                 case 1: mastervol *= snd_csqcchannel1volume.value; break;
1320                                 case 2: mastervol *= snd_csqcchannel2volume.value; break;
1321                                 case 3: mastervol *= snd_csqcchannel3volume.value; break;
1322                                 case 4: mastervol *= snd_csqcchannel4volume.value; break;
1323                                 case 5: mastervol *= snd_csqcchannel5volume.value; break;
1324                                 case 6: mastervol *= snd_csqcchannel6volume.value; break;
1325                                 case 7: mastervol *= snd_csqcchannel7volume.value; break;
1326                                 default:                                           break;
1327                         }
1328                 }
1329                 else if(ch->entnum == 0)
1330                 {
1331                         switch(ch->entchannel)
1332                         {
1333                                 case 0: mastervol *= snd_worldchannel0volume.value; break;
1334                                 case 1: mastervol *= snd_worldchannel1volume.value; break;
1335                                 case 2: mastervol *= snd_worldchannel2volume.value; break;
1336                                 case 3: mastervol *= snd_worldchannel3volume.value; break;
1337                                 case 4: mastervol *= snd_worldchannel4volume.value; break;
1338                                 case 5: mastervol *= snd_worldchannel5volume.value; break;
1339                                 case 6: mastervol *= snd_worldchannel6volume.value; break;
1340                                 case 7: mastervol *= snd_worldchannel7volume.value; break;
1341                                 default:                                            break;
1342                         }
1343                 }
1344                 else if(ch->entnum > 0 && ch->entnum <= cl.maxclients)
1345                 {
1346                         switch(ch->entchannel)
1347                         {
1348                                 case 0: mastervol *= snd_playerchannel0volume.value; break;
1349                                 case 1: mastervol *= snd_playerchannel1volume.value; break;
1350                                 case 2: mastervol *= snd_playerchannel2volume.value; break;
1351                                 case 3: mastervol *= snd_playerchannel3volume.value; break;
1352                                 case 4: mastervol *= snd_playerchannel4volume.value; break;
1353                                 case 5: mastervol *= snd_playerchannel5volume.value; break;
1354                                 case 6: mastervol *= snd_playerchannel6volume.value; break;
1355                                 case 7: mastervol *= snd_playerchannel7volume.value; break;
1356                                 default:                                             break;
1357                         }
1358                 }
1359                 else
1360                 {
1361                         switch(ch->entchannel)
1362                         {
1363                                 case 0: mastervol *= snd_entchannel0volume.value; break;
1364                                 case 1: mastervol *= snd_entchannel1volume.value; break;
1365                                 case 2: mastervol *= snd_entchannel2volume.value; break;
1366                                 case 3: mastervol *= snd_entchannel3volume.value; break;
1367                                 case 4: mastervol *= snd_entchannel4volume.value; break;
1368                                 case 5: mastervol *= snd_entchannel5volume.value; break;
1369                                 case 6: mastervol *= snd_entchannel6volume.value; break;
1370                                 case 7: mastervol *= snd_entchannel7volume.value; break;
1371                                 default:                                          break;
1372                         }
1373                 }
1374
1375                 switch(ch->entchannel)
1376                 {
1377                         case 0:  mastervol *= snd_channel0volume.value; break;
1378                         case 1:  mastervol *= snd_channel1volume.value; break;
1379                         case 2:  mastervol *= snd_channel2volume.value; break;
1380                         case 3:  mastervol *= snd_channel3volume.value; break;
1381                         case 4:  mastervol *= snd_channel4volume.value; break;
1382                         case 5:  mastervol *= snd_channel5volume.value; break;
1383                         case 6:  mastervol *= snd_channel6volume.value; break;
1384                         case 7:  mastervol *= snd_channel7volume.value; break;
1385                         default: mastervol *= Cvar_VariableValueOr(va("snd_channel%dvolume", CHAN_ENGINE2CVAR(ch->entchannel)), 1.0); break;
1386                 }
1387         }
1388
1389         // If this channel does not manage its own volume (like CD tracks)
1390         if (!(ch->flags & CHANNELFLAG_FULLVOLUME))
1391                 mastervol *= volume.value;
1392
1393         // clamp HERE to allow to go at most 10dB past mastervolume (before clamping), when mastervolume < -10dB (so relative volumes don't get too messy)
1394         mastervol = bound(0, mastervol, 655360);
1395
1396         // always apply "master"
1397         mastervol *= mastervolume.value;
1398
1399         // add in ReplayGain very late; prevent clipping when close
1400         if(sfx)
1401         if(sfx->volume_peak > 0)
1402         {
1403                 // Replaygain support
1404                 // Con_DPrintf("Setting volume on ReplayGain-enabled track... %f -> ", fvol);
1405                 mastervol *= sfx->volume_mult;
1406                 if(mastervol * sfx->volume_peak > 65536)
1407                         mastervol = 65536 / sfx->volume_peak;
1408                 // Con_DPrintf("%f\n", fvol);
1409         }
1410
1411         // clamp HERE to keep relative volumes of the channels correct
1412         mastervol = bound(0, mastervol, 65536);
1413
1414         // anything coming from the view entity will always be full volume
1415         // LordHavoc: make sounds with ATTN_NONE have no spatialization
1416         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
1417         {
1418                 ch->prologic_invert = 1;
1419                 if (snd_spatialization_prologic.integer != 0)
1420                 {
1421                         vol = mastervol * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5);
1422                         ch->listener_volume[0] = (int)bound(0, vol, 65536);
1423                         vol = mastervol * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5);
1424                         ch->listener_volume[1] = (int)bound(0, vol, 65536);
1425                         for (i = 2;i < SND_LISTENERS;i++)
1426                                 ch->listener_volume[i] = 0;
1427                 }
1428                 else
1429                 {
1430                         for (i = 0;i < SND_LISTENERS;i++)
1431                         {
1432                                 vol = mastervol * snd_speakerlayout.listeners[i].ambientvolume;
1433                                 ch->listener_volume[i] = (int)bound(0, vol, 65536);
1434                         }
1435                 }
1436         }
1437         else
1438         {
1439                 // calculate stereo seperation and distance attenuation
1440                 VectorSubtract(listener_origin, ch->origin, source_vec);
1441                 dist = VectorLength(source_vec);
1442                 intensity = mastervol * (1.0 - dist * ch->dist_mult);
1443                 if (intensity > 0)
1444                 {
1445                         qboolean occluded = false;
1446                         if (snd_spatialization_occlusion.integer)
1447                         {
1448                                 if(snd_spatialization_occlusion.integer & 1)
1449                                         if(listener_pvs)
1450                                         {
1451                                                 int cluster = cl.worldmodel->brush.PointInLeaf(cl.worldmodel, ch->origin)->clusterindex;
1452                                                 if(cluster >= 0 && cluster < 8 * listener_pvsbytes && !CHECKPVSBIT(listener_pvs, cluster))
1453                                                         occluded = true;
1454                                         }
1455
1456                                 if(snd_spatialization_occlusion.integer & 2)
1457                                         if(!occluded)
1458                                                 if(cl.worldmodel && cl.worldmodel->brush.TraceLineOfSight && !cl.worldmodel->brush.TraceLineOfSight(cl.worldmodel, listener_origin, ch->origin))
1459                                                         occluded = true;
1460                         }
1461                         if(occluded)
1462                                 intensity *= 0.5;
1463
1464                         ch->prologic_invert = 1;
1465                         if (snd_spatialization_prologic.integer != 0)
1466                         {
1467                                 if (dist == 0)
1468                                         angle_factor = 0.5;
1469                                 else
1470                                 {
1471                                         Matrix4x4_Transform(&listener_basematrix, ch->origin, source_vec);
1472                                         VectorNormalize(source_vec);
1473
1474                                         switch(spatialmethod)
1475                                         {
1476                                                 case SPATIAL_LOG:
1477                                                         if(dist == 0)
1478                                                                 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1479                                                         else
1480                                                                 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1481                                                         VectorScale(source_vec, f, source_vec);
1482                                                         break;
1483                                                 case SPATIAL_POW:
1484                                                         f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1485                                                         f = spatialmin + spatialdiff * bound(0, f, 1);
1486                                                         VectorScale(source_vec, f, source_vec);
1487                                                         break;
1488                                                 case SPATIAL_THRESH:
1489                                                         f = spatialmin + spatialdiff * (dist < spatialoffset);
1490                                                         VectorScale(source_vec, f, source_vec);
1491                                                         break;
1492                                                 case SPATIAL_NONE:
1493                                                 default:
1494                                                         break;
1495                                         }
1496
1497                                         // 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
1498                                         source_vec[2] = 0;
1499                                         VectorNormalize(source_vec);
1500                                         angle_side = acos(source_vec[0]) / M_PI * 180;  // angle between 0 and 180 degrees
1501                                         angle_front = asin(source_vec[1]) / M_PI * 180; // angle between -90 and 90 degrees
1502                                         if (angle_side > snd_spatialization_prologic_frontangle.value)
1503                                         {
1504                                                 ch->prologic_invert = -1;       // this will cause the right channel to do a 180 degrees phase shift (turning the sound wave upside down),
1505                                                                                                         // but the best would be 90 degrees phase shift left and a -90 degrees phase shift right.
1506                                                 angle_factor = (angle_side - snd_spatialization_prologic_frontangle.value) / (360 - 2 * snd_spatialization_prologic_frontangle.value);
1507                                                 // angle_factor is between 0 and 1 and represents the angle range from the front left, to all the surround speakers (amount may vary,
1508                                                 // 1 in prologic I 2 in prologic II and 3 or 4 in prologic IIx) to the front right speaker.
1509                                                 if (angle_front > 0)
1510                                                         angle_factor = 1 - angle_factor;
1511                                         }
1512                                         else
1513                                                 angle_factor = angle_front / snd_spatialization_prologic_frontangle.value / 2.0 + 0.5;
1514                                                 //angle_factor is between 0 and 1 and represents the angle range from the front left to the center to the front right speaker
1515                                 }
1516
1517                                 vol = intensity * sqrt(angle_factor);
1518                                 ch->listener_volume[0] = (int)bound(0, vol, 65536);
1519                                 vol = intensity * sqrt(1 - angle_factor);
1520                                 ch->listener_volume[1] = (int)bound(0, vol, 65536);
1521                                 for (i = 2;i < SND_LISTENERS;i++)
1522                                         ch->listener_volume[i] = 0;
1523                         }
1524                         else
1525                         {
1526                                 for (i = 0;i < SND_LISTENERS;i++)
1527                                 {
1528                                         Matrix4x4_Transform(&listener_matrix[i], ch->origin, source_vec);
1529                                         VectorNormalize(source_vec);
1530
1531                                         switch(spatialmethod)
1532                                         {
1533                                                 case SPATIAL_LOG:
1534                                                         if(dist == 0)
1535                                                                 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1536                                                         else
1537                                                                 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1538                                                         VectorScale(source_vec, f, source_vec);
1539                                                         break;
1540                                                 case SPATIAL_POW:
1541                                                         f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1542                                                         f = spatialmin + spatialdiff * bound(0, f, 1);
1543                                                         VectorScale(source_vec, f, source_vec);
1544                                                         break;
1545                                                 case SPATIAL_THRESH:
1546                                                         f = spatialmin + spatialdiff * (dist < spatialoffset);
1547                                                         VectorScale(source_vec, f, source_vec);
1548                                                         break;
1549                                                 case SPATIAL_NONE:
1550                                                 default:
1551                                                         break;
1552                                         }
1553
1554                                         vol = intensity * max(0, source_vec[0] * snd_speakerlayout.listeners[i].dotscale + snd_speakerlayout.listeners[i].dotbias);
1555
1556                                         ch->listener_volume[i] = (int)bound(0, vol, 65536);
1557                                 }
1558                         }
1559                 }
1560                 else
1561                         for (i = 0;i < SND_LISTENERS;i++)
1562                                 ch->listener_volume[i] = 0;
1563         }
1564 }
1565 void SND_Spatialize(channel_t *ch, qboolean isstatic)
1566 {
1567         sfx_t *sfx = ch->sfx;
1568         SND_Spatialize_WithSfx(ch, isstatic, sfx);
1569 }
1570
1571
1572 // =======================================================================
1573 // Start a sound effect
1574 // =======================================================================
1575
1576 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)
1577 {
1578         if (!sfx)
1579         {
1580                 Con_Printf("S_PlaySfxOnChannel called with NULL??\n");
1581                 return;
1582         }
1583
1584         if ((sfx->loopstart < sfx->total_length) || (flags & CHANNELFLAG_FORCELOOP))
1585         {
1586                 if(!snd_startloopingsounds.integer)
1587                         return;
1588         }
1589         else
1590         {
1591                 if(!snd_startnonloopingsounds.integer)
1592                         return;
1593         }
1594
1595         // Initialize the channel
1596         // a crash was reported on an in-use channel, so check here...
1597         if (target_chan->sfx)
1598         {
1599                 int channelindex = (int)(target_chan - channels);
1600                 Con_Printf("S_PlaySfxOnChannel(%s): channel %i already in use??  Clearing.\n", sfx->name, channelindex);
1601                 S_StopChannel (channelindex, true, false);
1602         }
1603         // We MUST set sfx LAST because otherwise we could crash a threaded mixer
1604         // (otherwise we'd have to call SndSys_LockRenderBuffer here)
1605         memset (target_chan, 0, sizeof (*target_chan));
1606         VectorCopy (origin, target_chan->origin);
1607         target_chan->flags = flags;
1608         target_chan->pos = startpos; // start of the sound
1609         target_chan->entnum = entnum;
1610         target_chan->entchannel = entchannel;
1611
1612         // If it's a static sound
1613         if (isstatic)
1614         {
1615                 if (sfx->loopstart >= sfx->total_length && (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEWORLD))
1616                         Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
1617                 target_chan->dist_mult = attenuation / (64.0f * snd_soundradius.value);
1618         }
1619         else
1620                 target_chan->dist_mult = attenuation / snd_soundradius.value;
1621
1622         // set the listener volumes
1623         S_SetChannelVolume(target_chan - channels, fvol);
1624         SND_Spatialize_WithSfx (target_chan, isstatic, sfx);
1625
1626         // finally, set the sfx pointer, so the channel becomes valid for playback
1627         // and will be noticed by the mixer
1628         target_chan->sfx = sfx;
1629 }
1630
1631
1632 int S_StartSound_StartPosition_Flags (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation, float startposition, int flags)
1633 {
1634         channel_t *target_chan, *check, *ch;
1635         int             ch_idx, startpos;
1636
1637         if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1638                 return -1;
1639
1640         if(sfx == &changevolume_sfx)
1641         {
1642                 if (!IS_CHAN_SINGLE(entchannel))
1643                         return -1;
1644                 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1645                 {
1646                         ch = &channels[ch_idx];
1647                         if (ch->entnum == entnum && ch->entchannel == entchannel)
1648                         {
1649                                 S_SetChannelVolume(ch_idx, fvol);
1650                                 ch->dist_mult = attenuation / snd_soundradius.value;
1651                                 SND_Spatialize(ch, false);
1652                                 return ch_idx;
1653                         }
1654                 }
1655                 return -1;
1656         }
1657
1658         if (sfx->fetcher == NULL)
1659                 return -1;
1660
1661         // Pick a channel to play on
1662         target_chan = SND_PickChannel(entnum, entchannel);
1663         if (!target_chan)
1664                 return -1;
1665
1666         // if an identical sound has also been started this frame, offset the pos
1667         // a bit to keep it from just making the first one louder
1668         check = &channels[NUM_AMBIENTS];
1669         startpos = (int)(startposition * S_GetSoundRate());
1670         if (startpos == 0)
1671         {
1672                 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
1673                 {
1674                         if (check == target_chan)
1675                                 continue;
1676                         if (check->sfx == sfx && check->pos == 0)
1677                         {
1678                                 // use negative pos offset to delay this sound effect
1679                                 startpos = (int)lhrandom(0, -0.1 * snd_renderbuffer->format.speed);
1680                                 break;
1681                         }
1682                 }
1683         }
1684
1685         S_PlaySfxOnChannel (sfx, target_chan, flags, origin, fvol, attenuation, false, entnum, entchannel, startpos);
1686
1687         return (target_chan - channels);
1688 }
1689
1690 int S_StartSound_StartPosition (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation, float startposition)
1691 {
1692         return S_StartSound_StartPosition_Flags(entnum, entchannel, sfx, origin, fvol, attenuation, startposition, CHANNELFLAG_NONE);
1693 }
1694
1695 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1696 {
1697         return S_StartSound_StartPosition(entnum, entchannel, sfx, origin, fvol, attenuation, 0);
1698 }
1699
1700 void S_StopChannel (unsigned int channel_ind, qboolean lockmutex, qboolean freesfx)
1701 {
1702         channel_t *ch;
1703         sfx_t *sfx;
1704
1705         if (channel_ind >= total_channels)
1706                 return;
1707
1708         // we have to lock an audio mutex to prevent crashes if an audio mixer
1709         // thread is currently mixing this channel
1710         // the SndSys_LockRenderBuffer function uses such a mutex in
1711         // threaded sound backends
1712         if (lockmutex && !simsound)
1713                 SndSys_LockRenderBuffer();
1714         
1715         ch = &channels[channel_ind];
1716         sfx = ch->sfx;
1717         if (ch->sfx != NULL)
1718         {
1719                 if (sfx->fetcher != NULL)
1720                 {
1721                         snd_fetcher_endsb_t fetcher_endsb = sfx->fetcher->endsb;
1722                         if (fetcher_endsb != NULL)
1723                                 fetcher_endsb (ch->fetcher_data);
1724                 }
1725
1726                 ch->fetcher_data = NULL;
1727                 ch->sfx = NULL;
1728         }
1729         if (lockmutex && !simsound)
1730                 SndSys_UnlockRenderBuffer();
1731         if (freesfx)
1732                 S_FreeSfx(sfx, true);
1733 }
1734
1735
1736 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
1737 {
1738         if (ch_ind >= total_channels)
1739                 return false;
1740
1741         if (flag != CHANNELFLAG_FORCELOOP &&
1742                 flag != CHANNELFLAG_PAUSED &&
1743                 flag != CHANNELFLAG_FULLVOLUME &&
1744                 flag != CHANNELFLAG_LOCALSOUND)
1745                 return false;
1746
1747         if (value)
1748                 channels[ch_ind].flags |= flag;
1749         else
1750                 channels[ch_ind].flags &= ~flag;
1751
1752         return true;
1753 }
1754
1755 void S_StopSound(int entnum, int entchannel)
1756 {
1757         unsigned int i;
1758
1759         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
1760                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
1761                 {
1762                         S_StopChannel (i, true, false);
1763                         return;
1764                 }
1765 }
1766
1767 extern void CDAudio_Stop(void);
1768 void S_StopAllSounds (void)
1769 {
1770         unsigned int i;
1771
1772         // TOCHECK: is this test necessary?
1773         if (snd_renderbuffer == NULL)
1774                 return;
1775
1776         // stop CD audio because it may be using a faketrack
1777         CDAudio_Stop();
1778
1779         if (simsound || SndSys_LockRenderBuffer ())
1780         {
1781                 int clear;
1782                 size_t memsize;
1783
1784                 for (i = 0; i < total_channels; i++)
1785                         if (channels[i].sfx)
1786                                 S_StopChannel (i, false, false);
1787
1788                 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
1789                 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
1790
1791                 // Mute the contents of the submittion buffer
1792                 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1793                 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1794                 memset(snd_renderbuffer->ring, clear, memsize);
1795
1796                 if (!simsound)
1797                         SndSys_UnlockRenderBuffer ();
1798         }
1799 }
1800
1801 void S_PauseGameSounds (qboolean toggle)
1802 {
1803         unsigned int i;
1804
1805         for (i = 0; i < total_channels; i++)
1806         {
1807                 channel_t *ch;
1808
1809                 ch = &channels[i];
1810                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
1811                         S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
1812         }
1813 }
1814
1815 void S_SetChannelVolume(unsigned int ch_ind, float fvol)
1816 {
1817         channels[ch_ind].master_vol = (int)(fvol * 65536.0f);
1818 }
1819
1820 float S_GetChannelPosition (unsigned int ch_ind)
1821 {
1822         // note: this is NOT accurate yet
1823         int s;
1824         channel_t *ch = &channels[ch_ind];
1825         sfx_t *sfx = ch->sfx;
1826         if (!sfx)
1827                 return -1;
1828
1829         s = ch->pos;
1830         /*
1831         if(!snd_usethreadedmixing)
1832                 s += _snd_mixahead.value * S_GetSoundRate();
1833         */
1834         return (s % sfx->total_length) / (float) S_GetSoundRate();
1835 }
1836
1837 float S_GetEntChannelPosition(int entnum, int entchannel)
1838 {
1839         channel_t *ch;
1840         unsigned int i;
1841
1842         for (i = 0; i < total_channels; i++)
1843         {
1844                 ch = &channels[i];
1845                 if (ch->entnum == entnum && ch->entchannel == entchannel)
1846                         return S_GetChannelPosition(i);
1847         }
1848         return -1; // no playing sound in this channel
1849 }
1850
1851 /*
1852 =================
1853 S_StaticSound
1854 =================
1855 */
1856 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1857 {
1858         channel_t       *target_chan;
1859
1860         if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1861                 return;
1862         if (!sfx->fetcher)
1863         {
1864                 Con_Printf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
1865                 return;
1866         }
1867
1868         if (total_channels == MAX_CHANNELS)
1869         {
1870                 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
1871                 return;
1872         }
1873
1874         target_chan = &channels[total_channels++];
1875         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true, 0, 0, 0);
1876 }
1877
1878
1879 /*
1880 ===================
1881 S_UpdateAmbientSounds
1882 ===================
1883 */
1884 void S_UpdateAmbientSounds (void)
1885 {
1886         int                     i;
1887         int                     vol;
1888         int                     ambient_channel;
1889         channel_t       *chan;
1890         unsigned char           ambientlevels[NUM_AMBIENTS];
1891         sfx_t           *sfx;
1892
1893         memset(ambientlevels, 0, sizeof(ambientlevels));
1894         if (cl.worldmodel && cl.worldmodel->brush.AmbientSoundLevelsForPoint)
1895                 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
1896
1897         // Calc ambient sound levels
1898         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
1899         {
1900                 chan = &channels[ambient_channel];
1901                 sfx = chan->sfx; // fetch the volatile variable
1902                 if (sfx == NULL || sfx->fetcher == NULL)
1903                         continue;
1904
1905                 vol = (int)ambientlevels[ambient_channel];
1906                 if (vol < 8)
1907                         vol = 0;
1908                 vol *= 256;
1909
1910                 // Don't adjust volume too fast
1911                 // FIXME: this rounds off to an int each frame, meaning there is little to no fade at extremely high framerates!
1912                 if (cl.time > cl.oldtime)
1913                 {
1914                         if (chan->master_vol < vol)
1915                         {
1916                                 chan->master_vol += (int)((cl.time - cl.oldtime) * 256.0 * ambient_fade.value);
1917                                 if (chan->master_vol > vol)
1918                                         chan->master_vol = vol;
1919                         }
1920                         else if (chan->master_vol > vol)
1921                         {
1922                                 chan->master_vol -= (int)((cl.time - cl.oldtime) * 256.0 * ambient_fade.value);
1923                                 if (chan->master_vol < vol)
1924                                         chan->master_vol = vol;
1925                         }
1926                 }
1927
1928                 if (snd_spatialization_prologic.integer != 0)
1929                 {
1930                         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);
1931                         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);
1932                         for (i = 2;i < SND_LISTENERS;i++)
1933                                 chan->listener_volume[i] = 0;
1934                 }
1935                 else
1936                 {
1937                         for (i = 0;i < SND_LISTENERS;i++)
1938                                 chan->listener_volume[i] = (int)bound(0, chan->master_vol * ambient_level.value * volume.value * mastervolume.value * snd_speakerlayout.listeners[i].ambientvolume, 65536);
1939                 }
1940         }
1941 }
1942
1943 static void S_PaintAndSubmit (void)
1944 {
1945         unsigned int newsoundtime, paintedtime, endtime, maxtime, usedframes;
1946         int usesoundtimehack;
1947         static int soundtimehack = -1;
1948         static int oldsoundtime = 0;
1949
1950         if (snd_renderbuffer == NULL || nosound.integer)
1951                 return;
1952
1953         // Update sound time
1954         snd_usethreadedmixing = false;
1955         usesoundtimehack = true;
1956         if (cls.timedemo) // SUPER NASTY HACK to mix non-realtime sound for more reliable benchmarking
1957         {
1958                 usesoundtimehack = 1;
1959                 newsoundtime = (unsigned int)((double)cl.mtime[0] * (double)snd_renderbuffer->format.speed);
1960         }
1961         else if (cls.capturevideo.soundrate && !cls.capturevideo.realtime) // SUPER NASTY HACK to record non-realtime sound
1962         {
1963                 usesoundtimehack = 2;
1964                 newsoundtime = (unsigned int)((double)cls.capturevideo.frame * (double)snd_renderbuffer->format.speed / (double)cls.capturevideo.framerate);
1965         }
1966         else if (simsound)
1967         {
1968                 usesoundtimehack = 3;
1969                 newsoundtime = (unsigned int)((realtime - snd_starttime) * (double)snd_renderbuffer->format.speed);
1970         }
1971         else
1972         {
1973                 snd_usethreadedmixing = snd_threaded && !cls.capturevideo.soundrate;
1974                 usesoundtimehack = 0;
1975                 newsoundtime = SndSys_GetSoundTime();
1976         }
1977         // if the soundtimehack state changes we need to reset the soundtime
1978         if (soundtimehack != usesoundtimehack)
1979         {
1980                 snd_renderbuffer->startframe = snd_renderbuffer->endframe = soundtime = newsoundtime;
1981
1982                 // Mute the contents of the submission buffer
1983                 if (simsound || SndSys_LockRenderBuffer ())
1984                 {
1985                         int clear;
1986                         size_t memsize;
1987
1988                         clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1989                         memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1990                         memset(snd_renderbuffer->ring, clear, memsize);
1991
1992                         if (!simsound)
1993                                 SndSys_UnlockRenderBuffer ();
1994                 }
1995         }
1996         soundtimehack = usesoundtimehack;
1997
1998         if (!soundtimehack && snd_blocked > 0)
1999                 return;
2000
2001         if (snd_usethreadedmixing)
2002                 return; // the audio thread will mix its own data
2003
2004         newsoundtime += extrasoundtime;
2005         if (newsoundtime < soundtime)
2006         {
2007                 if ((cls.capturevideo.soundrate != 0) != recording_sound)
2008                 {
2009                         unsigned int additionaltime;
2010
2011                         // add some time to extrasoundtime make newsoundtime higher
2012
2013                         // The extra time must be a multiple of the render buffer size
2014                         // to avoid modifying the current position in the buffer,
2015                         // some modules write directly to a shared (DMA) buffer
2016                         additionaltime = (soundtime - newsoundtime) + snd_renderbuffer->maxframes - 1;
2017                         additionaltime -= additionaltime % snd_renderbuffer->maxframes;
2018
2019                         extrasoundtime += additionaltime;
2020                         newsoundtime += additionaltime;
2021                         Con_DPrintf("S_PaintAndSubmit: new extra sound time = %u\n",
2022                                                 extrasoundtime);
2023                 }
2024                 else if (!soundtimehack)
2025                         Con_Printf("S_PaintAndSubmit: WARNING: newsoundtime < soundtime (%u < %u)\n",
2026                                            newsoundtime, soundtime);
2027         }
2028         soundtime = newsoundtime;
2029         recording_sound = (cls.capturevideo.soundrate != 0);
2030
2031         // Lock submitbuffer
2032         if (!simsound && !SndSys_LockRenderBuffer())
2033         {
2034                 // If the lock failed, stop here
2035                 Con_DPrint(">> S_PaintAndSubmit: SndSys_LockRenderBuffer() failed\n");
2036                 return;
2037         }
2038
2039         // Check to make sure that we haven't overshot
2040         paintedtime = snd_renderbuffer->endframe;
2041         if (paintedtime < soundtime)
2042                 paintedtime = soundtime;
2043
2044         // mix ahead of current position
2045         if (soundtimehack)
2046                 endtime = soundtime + (unsigned int)(_snd_mixahead.value * (float)snd_renderbuffer->format.speed);
2047         else
2048                 endtime = soundtime + (unsigned int)(max(_snd_mixahead.value * (float)snd_renderbuffer->format.speed, min(3 * (soundtime - oldsoundtime), 0.3 * (float)snd_renderbuffer->format.speed)));
2049         usedframes = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
2050         maxtime = paintedtime + snd_renderbuffer->maxframes - usedframes;
2051         endtime = min(endtime, maxtime);
2052
2053         while (paintedtime < endtime)
2054         {
2055                 unsigned int startoffset;
2056                 unsigned int nbframes;
2057
2058                 // see how much we can fit in the paint buffer
2059                 nbframes = endtime - paintedtime;
2060                 // limit to the end of the ring buffer (in case of wrapping)
2061                 startoffset = paintedtime % snd_renderbuffer->maxframes;
2062                 nbframes = min(nbframes, snd_renderbuffer->maxframes - startoffset);
2063
2064                 // mix into the buffer
2065                 S_MixToBuffer(&snd_renderbuffer->ring[startoffset * snd_renderbuffer->format.width * snd_renderbuffer->format.channels], nbframes);
2066
2067                 paintedtime += nbframes;
2068                 snd_renderbuffer->endframe = paintedtime;
2069         }
2070         if (!simsound)
2071                 SndSys_UnlockRenderBuffer();
2072
2073         // Remove outdated samples from the ring buffer, if any
2074         if (snd_renderbuffer->startframe < soundtime)
2075                 snd_renderbuffer->startframe = soundtime;
2076
2077         if (simsound)
2078                 snd_renderbuffer->startframe = snd_renderbuffer->endframe;
2079         else
2080                 SndSys_Submit();
2081
2082         oldsoundtime = soundtime;
2083
2084         cls.soundstats.latency_milliseconds = (snd_renderbuffer->endframe - snd_renderbuffer->startframe) * 1000 / snd_renderbuffer->format.speed;
2085         R_TimeReport("audiomix");
2086 }
2087
2088 /*
2089 ============
2090 S_Update
2091
2092 Called once each time through the main loop
2093 ============
2094 */
2095 void S_Update(const matrix4x4_t *listenermatrix)
2096 {
2097         unsigned int i, j, k;
2098         channel_t *ch, *combine;
2099         matrix4x4_t rotatematrix;
2100
2101         if (snd_renderbuffer == NULL || nosound.integer)
2102                 return;
2103
2104         {
2105                 double mindist_trans, maxdist_trans;
2106
2107                 spatialmin = snd_spatialization_min.value;
2108                 spatialdiff = snd_spatialization_max.value - spatialmin;
2109
2110                 if(snd_spatialization_control.value)
2111                 {
2112                         spatialpower = snd_spatialization_power.value;
2113
2114                         if(spatialpower == 0)
2115                         {
2116                                 spatialmethod = SPATIAL_LOG;
2117                                 mindist_trans = log(max(1, snd_spatialization_min_radius.value));
2118                                 maxdist_trans = log(max(1, snd_spatialization_max_radius.value));
2119                         }
2120                         else
2121                         {
2122                                 spatialmethod = SPATIAL_POW;
2123                                 mindist_trans = pow(snd_spatialization_min_radius.value, spatialpower);
2124                                 maxdist_trans = pow(snd_spatialization_max_radius.value, spatialpower);
2125                         }
2126
2127                         if(mindist_trans - maxdist_trans == 0)
2128                         {
2129                                 spatialmethod = SPATIAL_THRESH;
2130                                 mindist_trans = snd_spatialization_min_radius.value;
2131                         }
2132                         else
2133                         {
2134                                 spatialoffset = mindist_trans;
2135                                 spatialfactor = 1 / (maxdist_trans - mindist_trans);
2136                         }
2137                 }
2138                 else
2139                         spatialmethod = SPATIAL_NONE;
2140
2141         }
2142
2143         // If snd_swapstereo or snd_channellayout has changed, recompute the channel layout
2144         if (current_swapstereo != boolxor(snd_swapstereo.integer, v_flipped.integer) ||
2145                 current_channellayout != snd_channellayout.integer)
2146                 S_SetChannelLayout();
2147
2148         Matrix4x4_Invert_Simple(&listener_basematrix, listenermatrix);
2149         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
2150         if (cl.worldmodel && cl.worldmodel->brush.FatPVS && cl.worldmodel->brush.num_pvsclusterbytes && cl.worldmodel->brush.PointInLeaf)
2151         {
2152                 if(cl.worldmodel->brush.num_pvsclusterbytes != listener_pvsbytes)
2153                 {
2154                         if(listener_pvs)
2155                                 Mem_Free(listener_pvs);
2156                         listener_pvsbytes = cl.worldmodel->brush.num_pvsclusterbytes;
2157                         listener_pvs = (unsigned char *) Mem_Alloc(snd_mempool, listener_pvsbytes);
2158                 }
2159                 cl.worldmodel->brush.FatPVS(cl.worldmodel, listener_origin, 2, listener_pvs, listener_pvsbytes, 0);
2160         }
2161         else
2162         {
2163                 if(listener_pvs)
2164                 {
2165                         Mem_Free(listener_pvs);
2166                         listener_pvs = NULL;
2167                 }
2168                 listener_pvsbytes = 0;
2169         }
2170
2171         // calculate the current matrices
2172         for (j = 0;j < SND_LISTENERS;j++)
2173         {
2174                 Matrix4x4_CreateFromQuakeEntity(&rotatematrix, 0, 0, 0, 0, -snd_speakerlayout.listeners[j].yawangle, 0, 1);
2175                 Matrix4x4_Concat(&listener_matrix[j], &rotatematrix, &listener_basematrix);
2176                 // I think this should now do this:
2177                 //   1. create a rotation matrix for rotating by e.g. -90 degrees CCW
2178                 //      (note: the matrix will rotate the OBJECT, not the VIEWER, so its
2179                 //       angle has to be taken negative)
2180                 //   2. create a transform which first rotates and moves its argument
2181                 //      into the player's view coordinates (using basematrix which is
2182                 //      an inverted "absolute" listener matrix), then applies the
2183                 //      rotation matrix for the ear
2184                 // Isn't Matrix4x4_CreateFromQuakeEntity a bit misleading because this
2185                 // does not actually refer to an entity?
2186         }
2187
2188         // update general area ambient sound sources
2189         S_UpdateAmbientSounds ();
2190
2191         combine = NULL;
2192         R_TimeReport("audioprep");
2193
2194         // update spatialization for static and dynamic sounds
2195         cls.soundstats.totalsounds = 0;
2196         cls.soundstats.mixedsounds = 0;
2197         ch = channels+NUM_AMBIENTS;
2198         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
2199         {
2200                 if (!ch->sfx)
2201                         continue;
2202                 cls.soundstats.totalsounds++;
2203
2204                 // respatialize channel
2205                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);
2206
2207                 // try to combine static sounds with a previous channel of the same
2208                 // sound effect so we don't mix five torches every frame
2209                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
2210                 {
2211                         // no need to merge silent channels
2212                         for (j = 0;j < SND_LISTENERS;j++)
2213                                 if (ch->listener_volume[j])
2214                                         break;
2215                         if (j == SND_LISTENERS)
2216                                 continue;
2217                         // if the last combine chosen isn't suitable, find a new one
2218                         if (!(combine && combine != ch && combine->sfx == ch->sfx))
2219                         {
2220                                 // search for one
2221                                 combine = NULL;
2222                                 for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;j < i;j++)
2223                                 {
2224                                         if (channels[j].sfx == ch->sfx)
2225                                         {
2226                                                 combine = channels + j;
2227                                                 break;
2228                                         }
2229                                 }
2230                         }
2231                         if (combine && combine != ch && combine->sfx == ch->sfx)
2232                         {
2233                                 for (j = 0;j < SND_LISTENERS;j++)
2234                                 {
2235                                         combine->listener_volume[j] = bound(0, combine->listener_volume[j] + ch->listener_volume[j], 65536);
2236                                         ch->listener_volume[j] = 0;
2237                                 }
2238                         }
2239                 }
2240                 for (k = 0;k < SND_LISTENERS;k++)
2241                         if (ch->listener_volume[k])
2242                                 break;
2243                 if (k < SND_LISTENERS)
2244                         cls.soundstats.mixedsounds++;
2245         }
2246         R_TimeReport("audiospatialize");
2247
2248         sound_spatialized = true;
2249
2250         // debugging output
2251         if (snd_show.integer)
2252                 Con_Printf("----(%u)----\n", cls.soundstats.mixedsounds);
2253
2254         S_PaintAndSubmit();
2255 }
2256
2257 void S_ExtraUpdate (void)
2258 {
2259         if (snd_noextraupdate.integer || !sound_spatialized)
2260                 return;
2261
2262         S_PaintAndSubmit();
2263 }
2264
2265 qboolean S_LocalSound (const char *sound)
2266 {
2267         sfx_t   *sfx;
2268         int             ch_ind;
2269
2270         if (!snd_initialized.integer || nosound.integer)
2271                 return true;
2272
2273         sfx = S_PrecacheSound (sound, true, false);
2274         if (!sfx)
2275         {
2276                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
2277                 return false;
2278         }
2279
2280         // menu sounds must not be freed on level change
2281         sfx->flags |= SFXFLAG_MENUSOUND;
2282
2283         // fun fact: in Quake 1, this used -1 "replace any entity channel",
2284         // which we no longer support anyway
2285         // changed by Black in r4297 "Changed S_LocalSound to play multiple sounds at a time."
2286         ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 0);
2287         if (ch_ind < 0)
2288                 return false;
2289
2290         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
2291         return true;
2292 }