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