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