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