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