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