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