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