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