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