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