2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // snd_main.c -- main control for any streaming sound output device
26 #include "snd_modplug.h"
28 #include "cl_collision.h"
31 #define SND_MIN_SPEED 8000
32 #define SND_MAX_SPEED 96000
33 #define SND_MIN_WIDTH 1
34 #define SND_MAX_WIDTH 2
35 #define SND_MIN_CHANNELS 1
36 #define SND_MAX_CHANNELS 8
37 #if SND_LISTENERS != 8
38 # error this data only supports up to 8 channel, update it!
41 speakerlayout_t snd_speakerlayout;
43 // Our speaker layouts are based on ALSA. They differ from those
44 // Win32 and Mac OS X APIs use when there's more than 4 channels.
45 // (rear left + rear right, and front center + LFE are swapped).
46 #define SND_SPEAKERLAYOUTS (sizeof(snd_speakerlayouts) / sizeof(snd_speakerlayouts[0]))
47 static const speakerlayout_t snd_speakerlayouts[] =
52 {0, 45, 0.2, 0.2, 0.5}, // front left
53 {1, 315, 0.2, 0.2, 0.5}, // front right
54 {2, 135, 0.2, 0.2, 0.5}, // rear left
55 {3, 225, 0.2, 0.2, 0.5}, // rear right
56 {4, 0, 0.2, 0.2, 0.5}, // front center
57 {5, 0, 0, 0, 0}, // lfe (we don't have any good lfe sound sources and it would take some filtering work to generate them (and they'd probably still be wrong), so... no lfe)
58 {6, 90, 0.2, 0.2, 0.5}, // side left
59 {7, 180, 0.2, 0.2, 0.5}, // side right
65 {0, 45, 0.2, 0.2, 0.5}, // front left
66 {1, 315, 0.2, 0.2, 0.5}, // front right
67 {2, 135, 0.2, 0.2, 0.5}, // rear left
68 {3, 225, 0.2, 0.2, 0.5}, // rear right
69 {4, 0, 0.2, 0.2, 0.5}, // front center
70 {5, 0, 0, 0, 0}, // lfe (we don't have any good lfe sound sources and it would take some filtering work to generate them (and they'd probably still be wrong), so... no lfe)
76 // these systems sometimes have a subwoofer as well, but it has no
80 {0, 45, 0.3, 0.3, 0.8}, // front left
81 {1, 315, 0.3, 0.3, 0.8}, // front right
82 {2, 135, 0.3, 0.3, 0.8}, // rear left
83 {3, 225, 0.3, 0.3, 0.8}, // rear right
91 // these systems sometimes have a subwoofer as well, but it has no
95 {0, 90, 0.5, 0.5, 1}, // side left
96 {1, 270, 0.5, 0.5, 1}, // side right
108 {0, 0, 0, 1, 1}, // center
121 // =======================================================================
122 // Internal sound data & structures
123 // =======================================================================
125 channel_t channels[MAX_CHANNELS];
126 unsigned int total_channels;
128 snd_ringbuffer_t *snd_renderbuffer = NULL;
129 static unsigned int soundtime = 0;
130 static unsigned int oldpaintedtime = 0;
131 static unsigned int extrasoundtime = 0;
132 static double snd_starttime = 0.0;
133 qboolean snd_threaded = false;
134 qboolean snd_usethreadedmixing = false;
136 vec3_t listener_origin;
137 matrix4x4_t listener_basematrix;
138 static unsigned char *listener_pvs = NULL;
139 static int listener_pvsbytes = 0;
140 matrix4x4_t listener_matrix[SND_LISTENERS];
141 mempool_t *snd_mempool;
143 // Linked list of known sfx
144 static sfx_t *known_sfx = NULL;
146 static qboolean sound_spatialized = false;
148 qboolean simsound = false;
150 static qboolean recording_sound = false;
153 static int current_swapstereo = false;
154 static int current_channellayout = SND_CHANNELLAYOUT_AUTO;
155 static int current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
157 static float spatialpower, spatialmin, spatialdiff, spatialoffset, spatialfactor;
158 typedef enum { SPATIAL_NONE, SPATIAL_LOG, SPATIAL_POW, SPATIAL_THRESH } spatialmethod_t;
159 spatialmethod_t spatialmethod;
161 // Cvars declared in sound.h (part of the sound API)
162 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1", "volume of background music (such as CD music or replacement files such as sound/cdtracks/track002.ogg)"};
163 cvar_t mastervolume = {CVAR_SAVE, "mastervolume", "0.7", "master volume"};
164 cvar_t volume = {CVAR_SAVE, "volume", "0.7", "volume of sound effects"};
165 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0", "indicates the sound subsystem is active"};
166 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1", "volume of ambient sound effects (such as swampy sounds at the start of e1m2)"};
167 cvar_t snd_soundradius = {CVAR_SAVE, "snd_soundradius", "1200", "radius of weapon sounds and other standard sound effects (monster idle noises are half this radius and flickering light noises are one third of this radius)"};
168 cvar_t snd_spatialization_min_radius = {CVAR_SAVE, "snd_spatialization_min_radius", "10000", "use minimum spatialization above to this radius"};
169 cvar_t snd_spatialization_max_radius = {CVAR_SAVE, "snd_spatialization_max_radius", "100", "use maximum spatialization below this radius"};
170 cvar_t snd_spatialization_min = {CVAR_SAVE, "snd_spatialization_min", "0.70", "minimum spatializazion of sounds"};
171 cvar_t snd_spatialization_max = {CVAR_SAVE, "snd_spatialization_max", "0.95", "maximum spatialization of sounds"};
172 cvar_t snd_spatialization_power = {CVAR_SAVE, "snd_spatialization_power", "0", "exponent of the spatialization falloff curve (0: logarithmic)"};
173 cvar_t snd_spatialization_control = {CVAR_SAVE, "snd_spatialization_control", "0", "enable spatialization control (headphone friendly mode)"};
174 cvar_t snd_spatialization_prologic = {CVAR_SAVE, "snd_spatialization_prologic", "0", "use dolby prologic (I, II or IIx) encoding (snd_channels must be 2)"};
175 cvar_t snd_spatialization_prologic_frontangle = {CVAR_SAVE, "snd_spatialization_prologic_frontangle", "30", "the angle between the front speakers and the center speaker"};
176 cvar_t snd_spatialization_occlusion = {CVAR_SAVE, "snd_spatialization_occlusion", "1", "enable occlusion testing on spatialized sounds, which simply quiets sounds that are blocked by the world; 1 enables PVS method, 2 enables LineOfSight method, 3 enables both"};
178 // Cvars declared in snd_main.h (shared with other snd_*.c files)
179 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.15", "how much sound to mix ahead of time"};
180 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)"};
181 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0", "swaps left/right speakers for old ISA soundblaster cards"};
182 extern cvar_t v_flipped;
183 cvar_t snd_channellayout = {0, "snd_channellayout", "0", "channel layout. Can be 0 (auto - snd_restart needed), 1 (standard layout), or 2 (ALSA layout)"};
184 cvar_t snd_mutewhenidle = {CVAR_SAVE, "snd_mutewhenidle", "1", "whether to disable sound output when game window is inactive"};
185 cvar_t snd_entchannel0volume = {CVAR_SAVE, "snd_entchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of regular entities"};
186 cvar_t snd_entchannel1volume = {CVAR_SAVE, "snd_entchannel1volume", "1", "volume multiplier of the 1st entity channel of regular entities"};
187 cvar_t snd_entchannel2volume = {CVAR_SAVE, "snd_entchannel2volume", "1", "volume multiplier of the 2nd entity channel of regular entities"};
188 cvar_t snd_entchannel3volume = {CVAR_SAVE, "snd_entchannel3volume", "1", "volume multiplier of the 3rd entity channel of regular entities"};
189 cvar_t snd_entchannel4volume = {CVAR_SAVE, "snd_entchannel4volume", "1", "volume multiplier of the 4th entity channel of regular entities"};
190 cvar_t snd_entchannel5volume = {CVAR_SAVE, "snd_entchannel5volume", "1", "volume multiplier of the 5th entity channel of regular entities"};
191 cvar_t snd_entchannel6volume = {CVAR_SAVE, "snd_entchannel6volume", "1", "volume multiplier of the 6th entity channel of regular entities"};
192 cvar_t snd_entchannel7volume = {CVAR_SAVE, "snd_entchannel7volume", "1", "volume multiplier of the 7th entity channel of regular entities"};
193 cvar_t snd_playerchannel0volume = {CVAR_SAVE, "snd_playerchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of player entities"};
194 cvar_t snd_playerchannel1volume = {CVAR_SAVE, "snd_playerchannel1volume", "1", "volume multiplier of the 1st entity channel of player entities"};
195 cvar_t snd_playerchannel2volume = {CVAR_SAVE, "snd_playerchannel2volume", "1", "volume multiplier of the 2nd entity channel of player entities"};
196 cvar_t snd_playerchannel3volume = {CVAR_SAVE, "snd_playerchannel3volume", "1", "volume multiplier of the 3rd entity channel of player entities"};
197 cvar_t snd_playerchannel4volume = {CVAR_SAVE, "snd_playerchannel4volume", "1", "volume multiplier of the 4th entity channel of player entities"};
198 cvar_t snd_playerchannel5volume = {CVAR_SAVE, "snd_playerchannel5volume", "1", "volume multiplier of the 5th entity channel of player entities"};
199 cvar_t snd_playerchannel6volume = {CVAR_SAVE, "snd_playerchannel6volume", "1", "volume multiplier of the 6th entity channel of player entities"};
200 cvar_t snd_playerchannel7volume = {CVAR_SAVE, "snd_playerchannel7volume", "1", "volume multiplier of the 7th entity channel of player entities"};
201 cvar_t snd_worldchannel0volume = {CVAR_SAVE, "snd_worldchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of the world entity"};
202 cvar_t snd_worldchannel1volume = {CVAR_SAVE, "snd_worldchannel1volume", "1", "volume multiplier of the 1st entity channel of the world entity"};
203 cvar_t snd_worldchannel2volume = {CVAR_SAVE, "snd_worldchannel2volume", "1", "volume multiplier of the 2nd entity channel of the world entity"};
204 cvar_t snd_worldchannel3volume = {CVAR_SAVE, "snd_worldchannel3volume", "1", "volume multiplier of the 3rd entity channel of the world entity"};
205 cvar_t snd_worldchannel4volume = {CVAR_SAVE, "snd_worldchannel4volume", "1", "volume multiplier of the 4th entity channel of the world entity"};
206 cvar_t snd_worldchannel5volume = {CVAR_SAVE, "snd_worldchannel5volume", "1", "volume multiplier of the 5th entity channel of the world entity"};
207 cvar_t snd_worldchannel6volume = {CVAR_SAVE, "snd_worldchannel6volume", "1", "volume multiplier of the 6th entity channel of the world entity"};
208 cvar_t snd_worldchannel7volume = {CVAR_SAVE, "snd_worldchannel7volume", "1", "volume multiplier of the 7th entity channel of the world entity"};
209 cvar_t snd_csqcchannel0volume = {CVAR_SAVE, "snd_csqcchannel0volume", "1", "volume multiplier of the auto-allocate entity channel of the world entity"};
210 cvar_t snd_csqcchannel1volume = {CVAR_SAVE, "snd_csqcchannel1volume", "1", "volume multiplier of the 1st entity channel of the world entity"};
211 cvar_t snd_csqcchannel2volume = {CVAR_SAVE, "snd_csqcchannel2volume", "1", "volume multiplier of the 2nd entity channel of the world entity"};
212 cvar_t snd_csqcchannel3volume = {CVAR_SAVE, "snd_csqcchannel3volume", "1", "volume multiplier of the 3rd entity channel of the world entity"};
213 cvar_t snd_csqcchannel4volume = {CVAR_SAVE, "snd_csqcchannel4volume", "1", "volume multiplier of the 4th entity channel of the world entity"};
214 cvar_t snd_csqcchannel5volume = {CVAR_SAVE, "snd_csqcchannel5volume", "1", "volume multiplier of the 5th entity channel of the world entity"};
215 cvar_t snd_csqcchannel6volume = {CVAR_SAVE, "snd_csqcchannel6volume", "1", "volume multiplier of the 6th entity channel of the world entity"};
216 cvar_t snd_csqcchannel7volume = {CVAR_SAVE, "snd_csqcchannel7volume", "1", "volume multiplier of the 7th entity channel of the world entity"};
219 static cvar_t nosound = {0, "nosound", "0", "disables sound"};
220 static cvar_t snd_precache = {0, "snd_precache", "1", "loads sounds before they are used"};
221 static cvar_t ambient_level = {0, "ambient_level", "0.3", "volume of environment noises (water and wind)"};
222 static cvar_t ambient_fade = {0, "ambient_fade", "100", "rate of volume fading when moving from one environment to another"};
223 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"};
224 static cvar_t snd_show = {0, "snd_show", "0", "shows some statistics about sound mixing"};
226 // Default sound format is 48KHz, 16-bit, stereo
227 // (48KHz because a lot of onboard sound cards sucks at any other speed)
228 static cvar_t snd_speed = {CVAR_SAVE, "snd_speed", "48000", "sound output frequency, in hertz"};
229 static cvar_t snd_width = {CVAR_SAVE, "snd_width", "2", "sound output precision, in bytes (1 and 2 supported)"};
230 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)"};
233 static sfx_t* ambient_sfxs [2] = { NULL, NULL };
234 static const char* ambient_names [2] = { "sound/ambience/water1.wav", "sound/ambience/wind2.wav" };
237 // ====================================================================
239 // ====================================================================
241 void S_FreeSfx (sfx_t *sfx, qboolean force);
243 static void S_Play_Common (float fvol, float attenuation)
246 char name [MAX_QPATH];
250 while (i < Cmd_Argc ())
252 // Get the name, and appends ".wav" as an extension if there's none
253 strlcpy (name, Cmd_Argv (i), sizeof (name));
254 if (!strrchr (name, '.'))
255 strlcat (name, ".wav", sizeof (name));
258 // If we need to get the volume from the command line
261 fvol = atof (Cmd_Argv (i));
265 sfx = S_PrecacheSound (name, true, true);
268 ch_ind = S_StartSound (-1, 0, sfx, listener_origin, fvol, attenuation);
270 // Free the sfx if the file didn't exist
272 S_FreeSfx (sfx, false);
274 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
279 static void S_Play_f(void)
281 S_Play_Common (1.0f, 1.0f);
284 static void S_Play2_f(void)
286 S_Play_Common (1.0f, 0.0f);
289 static void S_PlayVol_f(void)
291 S_Play_Common (-1.0f, 0.0f);
294 static void S_SoundList_f (void)
301 for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
303 if (sfx->fetcher != NULL)
306 const snd_format_t* format;
309 format = sfx->fetcher->getfmt(sfx);
310 Con_Printf ("%c%c%c%c(%2db, %6s) %8i : %s\n",
311 (sfx->loopstart < sfx->total_length) ? 'L' : ' ',
312 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
313 (sfx->locks > 0) ? 'K' : ' ',
314 (sfx->flags & SFXFLAG_PERMANENTLOCK) ? 'P' : ' ',
316 (format->channels == 1) ? "mono" : "stereo",
322 Con_Printf (" ( unknown ) unloaded : %s\n", sfx->name);
324 Con_Printf("Total resident: %i\n", total);
328 void S_SoundInfo_f(void)
330 if (snd_renderbuffer == NULL)
332 Con_Print("sound system not started\n");
336 Con_Printf("%5d speakers\n", snd_renderbuffer->format.channels);
337 Con_Printf("%5d frames\n", snd_renderbuffer->maxframes);
338 Con_Printf("%5d samplebits\n", snd_renderbuffer->format.width * 8);
339 Con_Printf("%5d speed\n", snd_renderbuffer->format.speed);
340 Con_Printf("%5u total_channels\n", total_channels);
344 int S_GetSoundRate(void)
346 return snd_renderbuffer ? snd_renderbuffer->format.speed : 0;
349 int S_GetSoundChannels(void)
351 return snd_renderbuffer ? snd_renderbuffer->format.channels : 0;
355 static qboolean S_ChooseCheaperFormat (snd_format_t* format, qboolean fixed_speed, qboolean fixed_width, qboolean fixed_channels)
357 static const snd_format_t thresholds [] =
359 // speed width channels
360 { SND_MIN_SPEED, SND_MIN_WIDTH, SND_MIN_CHANNELS },
366 { SND_MAX_SPEED, SND_MAX_WIDTH, SND_MAX_CHANNELS },
368 const unsigned int nb_thresholds = sizeof(thresholds) / sizeof(thresholds[0]);
369 unsigned int speed_level, width_level, channels_level;
371 // If we have reached the minimum values, there's nothing more we can do
372 if ((format->speed == thresholds[0].speed || fixed_speed) &&
373 (format->width == thresholds[0].width || fixed_width) &&
374 (format->channels == thresholds[0].channels || fixed_channels))
377 // Check the min and max values
378 #define CHECK_BOUNDARIES(param) \
379 if (format->param < thresholds[0].param) \
381 format->param = thresholds[0].param; \
384 if (format->param > thresholds[nb_thresholds - 1].param) \
386 format->param = thresholds[nb_thresholds - 1].param; \
389 CHECK_BOUNDARIES(speed);
390 CHECK_BOUNDARIES(width);
391 CHECK_BOUNDARIES(channels);
392 #undef CHECK_BOUNDARIES
394 // Find the level of each parameter
395 #define FIND_LEVEL(param) \
397 while (param##_level < nb_thresholds - 1) \
399 if (format->param <= thresholds[param##_level].param) \
406 FIND_LEVEL(channels);
409 // Decrease the parameter with the highest level to the previous level
410 if (channels_level >= speed_level && channels_level >= width_level && !fixed_channels)
412 format->channels = thresholds[channels_level - 1].channels;
415 if (speed_level >= width_level && !fixed_speed)
417 format->speed = thresholds[speed_level - 1].speed;
421 format->width = thresholds[width_level - 1].width;
426 #define SWAP_LISTENERS(l1, l2, tmpl) { tmpl = (l1); (l1) = (l2); (l2) = tmpl; }
428 static void S_SetChannelLayout (void)
431 listener_t swaplistener;
432 listener_t *listeners;
435 for (i = 0; i < SND_SPEAKERLAYOUTS; i++)
436 if (snd_speakerlayouts[i].channels == snd_renderbuffer->format.channels)
438 if (i >= SND_SPEAKERLAYOUTS)
440 Con_Printf("S_SetChannelLayout: can't find the speaker layout for %hu channels. Defaulting to mono output\n",
441 snd_renderbuffer->format.channels);
442 i = SND_SPEAKERLAYOUTS - 1;
445 snd_speakerlayout = snd_speakerlayouts[i];
446 listeners = snd_speakerlayout.listeners;
448 // Swap the left and right channels if snd_swapstereo is set
449 if (boolxor(snd_swapstereo.integer, v_flipped.integer))
451 switch (snd_speakerlayout.channels)
454 SWAP_LISTENERS(listeners[6], listeners[7], swaplistener);
458 SWAP_LISTENERS(listeners[2], listeners[3], swaplistener);
461 SWAP_LISTENERS(listeners[0], listeners[1], swaplistener);
472 if (snd_channellayout.integer < SND_CHANNELLAYOUT_AUTO ||
473 snd_channellayout.integer > SND_CHANNELLAYOUT_ALSA)
474 Cvar_SetValueQuick (&snd_channellayout, SND_CHANNELLAYOUT_STANDARD);
476 if (snd_channellayout.integer == SND_CHANNELLAYOUT_AUTO)
478 // If we're in the sound engine initialization
479 if (current_channellayout_used == SND_CHANNELLAYOUT_AUTO)
481 layout = SND_CHANNELLAYOUT_STANDARD;
482 Cvar_SetValueQuick (&snd_channellayout, layout);
485 layout = current_channellayout_used;
488 layout = snd_channellayout.integer;
490 // Convert our layout (= ALSA) to the standard layout if necessary
491 if (snd_speakerlayout.channels == 6 || snd_speakerlayout.channels == 8)
493 if (layout == SND_CHANNELLAYOUT_STANDARD)
495 SWAP_LISTENERS(listeners[2], listeners[4], swaplistener);
496 SWAP_LISTENERS(listeners[3], listeners[5], swaplistener);
499 Con_Printf("S_SetChannelLayout: using %s speaker layout for 3D sound\n",
500 (layout == SND_CHANNELLAYOUT_ALSA) ? "ALSA" : "standard");
503 current_swapstereo = boolxor(snd_swapstereo.integer, v_flipped.integer);
504 current_channellayout = snd_channellayout.integer;
505 current_channellayout_used = layout;
509 void S_Startup (void)
511 qboolean fixed_speed, fixed_width, fixed_channels;
512 snd_format_t chosen_fmt;
513 static snd_format_t prev_render_format = {0, 0, 0};
520 if (!snd_initialized.integer)
525 fixed_channels = false;
527 // Get the starting sound format from the cvars
528 chosen_fmt.speed = snd_speed.integer;
529 chosen_fmt.width = snd_width.integer;
530 chosen_fmt.channels = snd_channels.integer;
532 // Check the environment variables to see if the player wants a particular sound format
534 _dupenv_s(&env, &envlen, "QUAKE_SOUND_CHANNELS");
536 env = getenv("QUAKE_SOUND_CHANNELS");
540 chosen_fmt.channels = atoi (env);
544 fixed_channels = true;
547 _dupenv_s(&env, &envlen, "QUAKE_SOUND_SPEED");
549 env = getenv("QUAKE_SOUND_SPEED");
553 chosen_fmt.speed = atoi (env);
560 _dupenv_s(&env, &envlen, "QUAKE_SOUND_SAMPLEBITS");
562 env = getenv("QUAKE_SOUND_SAMPLEBITS");
566 chosen_fmt.width = atoi (env) / 8;
573 // Parse the command line to see if the player wants a particular sound format
574 // COMMANDLINEOPTION: Sound: -sndquad sets sound output to 4 channel surround
575 if (COM_CheckParm ("-sndquad") != 0)
577 chosen_fmt.channels = 4;
578 fixed_channels = true;
580 // COMMANDLINEOPTION: Sound: -sndstereo sets sound output to stereo
581 else if (COM_CheckParm ("-sndstereo") != 0)
583 chosen_fmt.channels = 2;
584 fixed_channels = true;
586 // COMMANDLINEOPTION: Sound: -sndmono sets sound output to mono
587 else if (COM_CheckParm ("-sndmono") != 0)
589 chosen_fmt.channels = 1;
590 fixed_channels = true;
592 // COMMANDLINEOPTION: Sound: -sndspeed <hz> chooses sound output rate (supported values are 48000, 44100, 32000, 24000, 22050, 16000, 11025 (quake), 8000)
593 i = COM_CheckParm ("-sndspeed");
594 if (0 < i && i < com_argc - 1)
596 chosen_fmt.speed = atoi (com_argv[i + 1]);
599 // COMMANDLINEOPTION: Sound: -sndbits <bits> chooses 8 bit or 16 bit sound output
600 i = COM_CheckParm ("-sndbits");
601 if (0 < i && i < com_argc - 1)
603 chosen_fmt.width = atoi (com_argv[i + 1]) / 8;
607 // You can't change sound speed after start time (not yet supported)
608 if (prev_render_format.speed != 0)
611 if (chosen_fmt.speed != prev_render_format.speed)
613 Con_Printf("S_Startup: sound speed has changed! This is NOT supported yet. Falling back to previous speed (%u Hz)\n",
614 prev_render_format.speed);
615 chosen_fmt.speed = prev_render_format.speed;
620 if (chosen_fmt.speed < SND_MIN_SPEED)
622 chosen_fmt.speed = SND_MIN_SPEED;
625 else if (chosen_fmt.speed > SND_MAX_SPEED)
627 chosen_fmt.speed = SND_MAX_SPEED;
631 if (chosen_fmt.width < SND_MIN_WIDTH)
633 chosen_fmt.width = SND_MIN_WIDTH;
636 else if (chosen_fmt.width > SND_MAX_WIDTH)
638 chosen_fmt.width = SND_MAX_WIDTH;
642 if (chosen_fmt.channels < SND_MIN_CHANNELS)
644 chosen_fmt.channels = SND_MIN_CHANNELS;
645 fixed_channels = false;
647 else if (chosen_fmt.channels > SND_MAX_CHANNELS)
649 chosen_fmt.channels = SND_MAX_CHANNELS;
650 fixed_channels = false;
653 // create the sound buffer used for sumitting the samples to the plaform-dependent module
656 snd_format_t suggest_fmt;
662 Con_Printf("S_Startup: initializing sound output format: %dHz, %d bit, %d channels...\n",
663 chosen_fmt.speed, chosen_fmt.width * 8,
664 chosen_fmt.channels);
666 memset(&suggest_fmt, 0, sizeof(suggest_fmt));
667 accepted = SndSys_Init(&chosen_fmt, &suggest_fmt);
671 Con_Printf("S_Startup: sound output initialization FAILED\n");
673 // If the module is suggesting another one
674 if (suggest_fmt.speed != 0)
676 memcpy(&chosen_fmt, &suggest_fmt, sizeof(chosen_fmt));
677 Con_Printf (" Driver has suggested %dHz, %d bit, %d channels. Retrying...\n",
678 suggest_fmt.speed, suggest_fmt.width * 8,
679 suggest_fmt.channels);
681 // Else, try to find a less resource-demanding format
682 else if (!S_ChooseCheaperFormat (&chosen_fmt, fixed_speed, fixed_width, fixed_channels))
687 // If we haven't found a suitable format
690 Con_Print("S_Startup: SndSys_Init failed.\n");
691 sound_spatialized = false;
697 snd_renderbuffer = Snd_CreateRingBuffer(&chosen_fmt, 0, NULL);
698 Con_Print ("S_Startup: simulating sound output\n");
701 memcpy(&prev_render_format, &snd_renderbuffer->format, sizeof(prev_render_format));
702 Con_Printf("Sound format: %dHz, %d channels, %d bits per sample\n",
703 chosen_fmt.speed, chosen_fmt.channels, chosen_fmt.width * 8);
706 if (snd_speed.integer != (int)chosen_fmt.speed)
707 Cvar_SetValueQuick(&snd_speed, chosen_fmt.speed);
708 if (snd_width.integer != chosen_fmt.width)
709 Cvar_SetValueQuick(&snd_width, chosen_fmt.width);
710 if (snd_channels.integer != chosen_fmt.channels)
711 Cvar_SetValueQuick(&snd_channels, chosen_fmt.channels);
713 current_channellayout_used = SND_CHANNELLAYOUT_AUTO;
714 S_SetChannelLayout();
716 snd_starttime = realtime;
718 // If the sound module has already run, add an extra time to make sure
719 // the sound time doesn't decrease, to not confuse playing SFXs
720 if (oldpaintedtime != 0)
722 // The extra time must be a multiple of the render buffer size
723 // to avoid modifying the current position in the buffer,
724 // some modules write directly to a shared (DMA) buffer
725 extrasoundtime = oldpaintedtime + snd_renderbuffer->maxframes - 1;
726 extrasoundtime -= extrasoundtime % snd_renderbuffer->maxframes;
727 Con_Printf("S_Startup: extra sound time = %u\n", extrasoundtime);
729 soundtime = extrasoundtime;
733 snd_renderbuffer->startframe = soundtime;
734 snd_renderbuffer->endframe = soundtime;
735 recording_sound = false;
738 void S_Shutdown(void)
740 if (snd_renderbuffer == NULL)
743 oldpaintedtime = snd_renderbuffer->endframe;
747 Mem_Free(snd_renderbuffer->ring);
748 Mem_Free(snd_renderbuffer);
749 snd_renderbuffer = NULL;
754 sound_spatialized = false;
757 void S_Restart_f(void)
759 // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
760 // So, refuse to do this if we are connected.
761 if(cls.state == ca_connected)
763 Con_Printf("snd_restart would wreak havoc if you do that while connected!\n");
778 Cvar_RegisterVariable(&volume);
779 Cvar_RegisterVariable(&bgmvolume);
780 Cvar_RegisterVariable(&mastervolume);
781 Cvar_RegisterVariable(&snd_staticvolume);
782 Cvar_RegisterVariable(&snd_entchannel0volume);
783 Cvar_RegisterVariable(&snd_entchannel1volume);
784 Cvar_RegisterVariable(&snd_entchannel2volume);
785 Cvar_RegisterVariable(&snd_entchannel3volume);
786 Cvar_RegisterVariable(&snd_entchannel4volume);
787 Cvar_RegisterVariable(&snd_entchannel5volume);
788 Cvar_RegisterVariable(&snd_entchannel6volume);
789 Cvar_RegisterVariable(&snd_entchannel7volume);
790 Cvar_RegisterVariable(&snd_worldchannel0volume);
791 Cvar_RegisterVariable(&snd_worldchannel1volume);
792 Cvar_RegisterVariable(&snd_worldchannel2volume);
793 Cvar_RegisterVariable(&snd_worldchannel3volume);
794 Cvar_RegisterVariable(&snd_worldchannel4volume);
795 Cvar_RegisterVariable(&snd_worldchannel5volume);
796 Cvar_RegisterVariable(&snd_worldchannel6volume);
797 Cvar_RegisterVariable(&snd_worldchannel7volume);
798 Cvar_RegisterVariable(&snd_playerchannel0volume);
799 Cvar_RegisterVariable(&snd_playerchannel1volume);
800 Cvar_RegisterVariable(&snd_playerchannel2volume);
801 Cvar_RegisterVariable(&snd_playerchannel3volume);
802 Cvar_RegisterVariable(&snd_playerchannel4volume);
803 Cvar_RegisterVariable(&snd_playerchannel5volume);
804 Cvar_RegisterVariable(&snd_playerchannel6volume);
805 Cvar_RegisterVariable(&snd_playerchannel7volume);
806 Cvar_RegisterVariable(&snd_csqcchannel0volume);
807 Cvar_RegisterVariable(&snd_csqcchannel1volume);
808 Cvar_RegisterVariable(&snd_csqcchannel2volume);
809 Cvar_RegisterVariable(&snd_csqcchannel3volume);
810 Cvar_RegisterVariable(&snd_csqcchannel4volume);
811 Cvar_RegisterVariable(&snd_csqcchannel5volume);
812 Cvar_RegisterVariable(&snd_csqcchannel6volume);
813 Cvar_RegisterVariable(&snd_csqcchannel7volume);
815 Cvar_RegisterVariable(&snd_spatialization_min_radius);
816 Cvar_RegisterVariable(&snd_spatialization_max_radius);
817 Cvar_RegisterVariable(&snd_spatialization_min);
818 Cvar_RegisterVariable(&snd_spatialization_max);
819 Cvar_RegisterVariable(&snd_spatialization_power);
820 Cvar_RegisterVariable(&snd_spatialization_control);
821 Cvar_RegisterVariable(&snd_spatialization_occlusion);
822 Cvar_RegisterVariable(&snd_spatialization_prologic);
823 Cvar_RegisterVariable(&snd_spatialization_prologic_frontangle);
825 Cvar_RegisterVariable(&snd_speed);
826 Cvar_RegisterVariable(&snd_width);
827 Cvar_RegisterVariable(&snd_channels);
828 Cvar_RegisterVariable(&snd_mutewhenidle);
830 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
831 if (COM_CheckParm("-nosound"))
833 // dummy out Play and Play2 because mods stuffcmd that
834 Cmd_AddCommand("play", Host_NoOperation_f, "does nothing because -nosound was specified");
835 Cmd_AddCommand("play2", Host_NoOperation_f, "does nothing because -nosound was specified");
839 snd_mempool = Mem_AllocPool("sound", 0, NULL);
841 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
842 if (COM_CheckParm("-simsound"))
845 Cmd_AddCommand("play", S_Play_f, "play a sound at your current location (not heard by anyone else)");
846 Cmd_AddCommand("play2", S_Play2_f, "play a sound globally throughout the level (not heard by anyone else)");
847 Cmd_AddCommand("playvol", S_PlayVol_f, "play a sound at the specified volume level at your current location (not heard by anyone else)");
848 Cmd_AddCommand("stopsound", S_StopAllSounds, "silence");
849 Cmd_AddCommand("soundlist", S_SoundList_f, "list loaded sounds");
850 Cmd_AddCommand("soundinfo", S_SoundInfo_f, "print sound system information (such as channels and speed)");
851 Cmd_AddCommand("snd_restart", S_Restart_f, "restart sound system");
852 Cmd_AddCommand("snd_unloadallsounds", S_UnloadAllSounds_f, "unload all sound files");
854 Cvar_RegisterVariable(&nosound);
855 Cvar_RegisterVariable(&snd_precache);
856 Cvar_RegisterVariable(&snd_initialized);
857 Cvar_RegisterVariable(&snd_streaming);
858 Cvar_RegisterVariable(&ambient_level);
859 Cvar_RegisterVariable(&ambient_fade);
860 Cvar_RegisterVariable(&snd_noextraupdate);
861 Cvar_RegisterVariable(&snd_show);
862 Cvar_RegisterVariable(&_snd_mixahead);
863 Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
864 Cvar_RegisterVariable(&snd_channellayout);
865 Cvar_RegisterVariable(&snd_soundradius);
867 Cvar_SetValueQuick(&snd_initialized, true);
871 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
872 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
875 ModPlug_OpenLibrary ();
883 Shutdown and free all resources
886 void S_Terminate (void)
889 ModPlug_CloseLibrary ();
893 while (known_sfx != NULL)
894 S_FreeSfx (known_sfx, true);
896 Cvar_SetValueQuick (&snd_initialized, false);
897 Mem_FreePool (&snd_mempool);
906 void S_UnloadAllSounds_f (void)
910 // NOTE: we can't free all sounds if we are running a map (this frees sfx_t that are still referenced by precaches)
911 // So, refuse to do this if we are connected.
912 if(cls.state == ca_connected)
914 Con_Printf("snd_unloadallsounds would wreak havoc if you do that while connected!\n");
918 // stop any active sounds
921 // because the ambient sounds will be freed, clear the pointers
922 for (i = 0;i < (int)sizeof (ambient_sfxs) / (int)sizeof (ambient_sfxs[0]);i++)
923 ambient_sfxs[i] = NULL;
925 // now free all sounds
926 while (known_sfx != NULL)
927 S_FreeSfx (known_sfx, true);
936 sfx_t changevolume_sfx = {""};
937 sfx_t *S_FindName (const char *name)
941 if (!snd_initialized.integer)
944 if(!strcmp(name, changevolume_sfx.name))
945 return &changevolume_sfx;
947 if (strlen (name) >= sizeof (sfx->name))
949 Con_Printf ("S_FindName: sound name too long (%s)\n", name);
953 // Look for this sound in the list of known sfx
954 // TODO: hash table search?
955 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
956 if(!strcmp (sfx->name, name))
959 // Add a sfx_t struct for this sound
960 sfx = (sfx_t *)Mem_Alloc (snd_mempool, sizeof (*sfx));
961 memset (sfx, 0, sizeof(*sfx));
962 strlcpy (sfx->name, name, sizeof (sfx->name));
963 sfx->memsize = sizeof(*sfx);
964 sfx->next = known_sfx;
976 void S_FreeSfx (sfx_t *sfx, qboolean force)
980 // Never free a locked sfx unless forced
981 if (!force && (sfx->locks > 0 || (sfx->flags & SFXFLAG_PERMANENTLOCK)))
984 if (developer_loading.integer)
985 Con_Printf ("unloading sound %s\n", sfx->name);
987 // Remove it from the list of known sfx
988 if (sfx == known_sfx)
989 known_sfx = known_sfx->next;
994 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
995 if (prev_sfx->next == sfx)
997 prev_sfx->next = sfx->next;
1000 if (prev_sfx == NULL)
1002 Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
1007 // Stop all channels using this sfx
1008 for (i = 0; i < total_channels; i++)
1009 if (channels[i].sfx == sfx)
1010 S_StopChannel (i, true);
1013 if (sfx->fetcher != NULL && sfx->fetcher->free != NULL)
1014 sfx->fetcher->free (sfx->fetcher_data);
1024 void S_ClearUsed (void)
1030 // Start the ambient sounds and make them loop
1031 for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
1033 // Precache it if it's not done (request a lock to make sure it will never be freed)
1034 if (ambient_sfxs[i] == NULL)
1035 ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, true);
1036 if (ambient_sfxs[i] != NULL)
1038 // Add a lock to the SFX while playing. It will be
1039 // removed by S_StopAllSounds at the end of the level
1040 S_LockSfx (ambient_sfxs[i]);
1042 channels[i].sfx = ambient_sfxs[i];
1043 channels[i].flags |= CHANNELFLAG_FORCELOOP;
1044 channels[i].master_vol = 0;
1048 // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
1049 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
1050 if (sfx->flags & SFXFLAG_SERVERSOUND)
1053 sfx->flags &= ~SFXFLAG_SERVERSOUND;
1062 void S_PurgeUnused(void)
1067 // Free all unlocked sfx
1068 for (sfx = known_sfx;sfx;sfx = sfxnext)
1070 sfxnext = sfx->next;
1071 S_FreeSfx (sfx, false);
1081 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean serversound)
1085 if (!snd_initialized.integer)
1088 if (name == NULL || name[0] == 0)
1091 sfx = S_FindName (name);
1096 // clear the FILEMISSING flag so that S_LoadSound will try again on a
1097 // previously missing file
1098 sfx->flags &= ~ SFXFLAG_FILEMISSING;
1100 if (serversound && !(sfx->flags & SFXFLAG_SERVERSOUND))
1103 sfx->flags |= SFXFLAG_SERVERSOUND;
1106 if (!nosound.integer && snd_precache.integer)
1107 S_LoadSound(sfx, complain);
1118 float S_SoundLength(const char *name)
1122 if (!snd_initialized.integer)
1124 if (name == NULL || name[0] == 0)
1127 sfx = S_FindName(name);
1130 return sfx->total_length / (float) S_GetSoundRate();
1138 qboolean S_IsSoundPrecached (const sfx_t *sfx)
1140 return (sfx != NULL && sfx->fetcher != NULL) || (sfx == &changevolume_sfx);
1150 void S_LockSfx (sfx_t *sfx)
1159 Remove a lock from a SFX
1162 void S_UnlockSfx (sfx_t *sfx)
1173 void S_BlockSound (void)
1184 void S_UnblockSound (void)
1194 Picks a channel based on priorities, empty slots, number of channels
1197 channel_t *SND_PickChannel(int entnum, int entchannel)
1201 int first_life_left, life_left;
1204 // Check for replacement sound, or find the best one to replace
1206 first_life_left = 0x7fffffff;
1208 // entity channels try to replace the existing sound on the channel
1209 if (entchannel != 0)
1211 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1213 ch = &channels[ch_idx];
1214 if (ch->entnum == entnum && (ch->entchannel == entchannel || entchannel == -1) )
1216 // always override sound from same entity
1217 S_StopChannel (ch_idx, true);
1218 return &channels[ch_idx];
1223 // there was no channel to override, so look for the first empty one
1224 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1226 ch = &channels[ch_idx];
1229 // no sound on this channel
1230 first_to_die = ch_idx;
1231 goto emptychan_found;
1234 // don't let monster sounds override player sounds
1235 if (ch->entnum == cl.viewentity && entnum != cl.viewentity)
1238 // don't override looped sounds
1239 if ((ch->flags & CHANNELFLAG_FORCELOOP) || ch->sfx->loopstart < ch->sfx->total_length)
1241 life_left = ch->sfx->total_length - ch->pos;
1243 if (life_left < first_life_left)
1245 first_life_left = life_left;
1246 first_to_die = ch_idx;
1250 if (first_to_die == -1)
1253 S_StopChannel (first_to_die, true);
1256 return &channels[first_to_die];
1263 Spatializes a channel
1266 extern cvar_t cl_gameplayfix_soundsmovewithentities;
1267 void SND_Spatialize_WithSfx(channel_t *ch, qboolean isstatic, sfx_t *sfx)
1271 float angle_side, angle_front, angle_factor;
1272 vec_t dist, mastervol, intensity, vol;
1275 // update sound origin if we know about the entity
1276 if (ch->entnum > 0 && cls.state == ca_connected && cl_gameplayfix_soundsmovewithentities.integer)
1278 if (ch->entnum >= MAX_EDICTS)
1280 //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]);
1282 if (ch->entnum > MAX_EDICTS)
1283 if (!CL_VM_GetEntitySoundOrigin(ch->entnum, ch->origin))
1284 ch->entnum = MAX_EDICTS; // entity was removed, disown sound
1286 else if (cl.entities[ch->entnum].state_current.active)
1289 //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]);
1290 model = CL_GetModelByIndex(cl.entities[ch->entnum].state_current.modelindex);
1291 if (model && model->soundfromcenter)
1292 VectorMAM(0.5f, cl.entities[ch->entnum].render.mins, 0.5f, cl.entities[ch->entnum].render.maxs, ch->origin);
1294 Matrix4x4_OriginFromMatrix(&cl.entities[ch->entnum].render.matrix, ch->origin);
1298 mastervol = ch->master_vol;
1300 // Adjust volume of static sounds
1302 mastervol *= snd_staticvolume.value;
1303 else if(!(ch->flags & CHANNELFLAG_FULLVOLUME)) // same as SND_PaintChannel uses
1305 if(ch->entnum >= MAX_EDICTS)
1307 switch(ch->entchannel)
1309 case 0: mastervol *= snd_csqcchannel0volume.value; break;
1310 case 1: mastervol *= snd_csqcchannel1volume.value; break;
1311 case 2: mastervol *= snd_csqcchannel2volume.value; break;
1312 case 3: mastervol *= snd_csqcchannel3volume.value; break;
1313 case 4: mastervol *= snd_csqcchannel4volume.value; break;
1314 case 5: mastervol *= snd_csqcchannel5volume.value; break;
1315 case 6: mastervol *= snd_csqcchannel6volume.value; break;
1316 case 7: mastervol *= snd_csqcchannel7volume.value; break;
1320 else if(ch->entnum == 0)
1322 switch(ch->entchannel)
1324 case 0: mastervol *= snd_worldchannel0volume.value; break;
1325 case 1: mastervol *= snd_worldchannel1volume.value; break;
1326 case 2: mastervol *= snd_worldchannel2volume.value; break;
1327 case 3: mastervol *= snd_worldchannel3volume.value; break;
1328 case 4: mastervol *= snd_worldchannel4volume.value; break;
1329 case 5: mastervol *= snd_worldchannel5volume.value; break;
1330 case 6: mastervol *= snd_worldchannel6volume.value; break;
1331 case 7: mastervol *= snd_worldchannel7volume.value; break;
1335 else if(ch->entnum > 0 && ch->entnum <= cl.maxclients)
1337 switch(ch->entchannel)
1339 case 0: mastervol *= snd_playerchannel0volume.value; break;
1340 case 1: mastervol *= snd_playerchannel1volume.value; break;
1341 case 2: mastervol *= snd_playerchannel2volume.value; break;
1342 case 3: mastervol *= snd_playerchannel3volume.value; break;
1343 case 4: mastervol *= snd_playerchannel4volume.value; break;
1344 case 5: mastervol *= snd_playerchannel5volume.value; break;
1345 case 6: mastervol *= snd_playerchannel6volume.value; break;
1346 case 7: mastervol *= snd_playerchannel7volume.value; break;
1352 switch(ch->entchannel)
1354 case 0: mastervol *= snd_entchannel0volume.value; break;
1355 case 1: mastervol *= snd_entchannel1volume.value; break;
1356 case 2: mastervol *= snd_entchannel2volume.value; break;
1357 case 3: mastervol *= snd_entchannel3volume.value; break;
1358 case 4: mastervol *= snd_entchannel4volume.value; break;
1359 case 5: mastervol *= snd_entchannel5volume.value; break;
1360 case 6: mastervol *= snd_entchannel6volume.value; break;
1361 case 7: mastervol *= snd_entchannel7volume.value; break;
1367 // If this channel does not manage its own volume (like CD tracks)
1368 if (!(ch->flags & CHANNELFLAG_FULLVOLUME))
1369 mastervol *= volume.value;
1371 // clamp HERE to allow to go at most 10dB past mastervolume (before clamping), when mastervolume < -10dB (so relative volumes don't get too messy)
1372 mastervol = bound(0, mastervol, 655360);
1374 // always apply "master"
1375 mastervol *= mastervolume.value;
1377 // add in ReplayGain very late; prevent clipping when close
1379 if(sfx->volume_peak > 0)
1381 // Replaygain support
1382 // Con_DPrintf("Setting volume on ReplayGain-enabled track... %f -> ", fvol);
1383 mastervol *= sfx->volume_mult;
1384 if(mastervol * sfx->volume_peak > 65536)
1385 mastervol = 65536 / sfx->volume_peak;
1386 // Con_DPrintf("%f\n", fvol);
1389 // clamp HERE to keep relative volumes of the channels correct
1390 mastervol = bound(0, mastervol, 65536);
1392 // anything coming from the view entity will always be full volume
1393 // LordHavoc: make sounds with ATTN_NONE have no spatialization
1394 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
1396 ch->prologic_invert = 1;
1397 if (snd_spatialization_prologic.integer != 0)
1399 vol = mastervol * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5);
1400 ch->listener_volume[0] = (int)bound(0, vol, 65536);
1401 vol = mastervol * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5);
1402 ch->listener_volume[1] = (int)bound(0, vol, 65536);
1403 for (i = 2;i < SND_LISTENERS;i++)
1404 ch->listener_volume[i] = 0;
1408 for (i = 0;i < SND_LISTENERS;i++)
1410 vol = mastervol * snd_speakerlayout.listeners[i].ambientvolume;
1411 ch->listener_volume[i] = (int)bound(0, vol, 65536);
1417 // calculate stereo seperation and distance attenuation
1418 VectorSubtract(listener_origin, ch->origin, source_vec);
1419 dist = VectorLength(source_vec);
1420 intensity = mastervol * (1.0 - dist * ch->dist_mult);
1423 qboolean occluded = false;
1424 if (snd_spatialization_occlusion.integer)
1426 if(snd_spatialization_occlusion.integer & 1)
1429 int cluster = cl.worldmodel->brush.PointInLeaf(cl.worldmodel, ch->origin)->clusterindex;
1430 if(cluster >= 0 && cluster < 8 * listener_pvsbytes && !CHECKPVSBIT(listener_pvs, cluster))
1434 if(snd_spatialization_occlusion.integer & 2)
1436 if(cl.worldmodel && cl.worldmodel->brush.TraceLineOfSight && !cl.worldmodel->brush.TraceLineOfSight(cl.worldmodel, listener_origin, ch->origin))
1442 ch->prologic_invert = 1;
1443 if (snd_spatialization_prologic.integer != 0)
1449 Matrix4x4_Transform(&listener_basematrix, ch->origin, source_vec);
1450 VectorNormalize(source_vec);
1452 switch(spatialmethod)
1456 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1458 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1459 VectorScale(source_vec, f, source_vec);
1462 f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1463 f = spatialmin + spatialdiff * bound(0, f, 1);
1464 VectorScale(source_vec, f, source_vec);
1466 case SPATIAL_THRESH:
1467 f = spatialmin + spatialdiff * (dist < spatialoffset);
1468 VectorScale(source_vec, f, source_vec);
1475 // the z axis needs to be removed and normalized because otherwise the volume would get lower as the sound source goes higher or lower then normal
1477 VectorNormalize(source_vec);
1478 angle_side = acos(source_vec[0]) / M_PI * 180; // angle between 0 and 180 degrees
1479 angle_front = asin(source_vec[1]) / M_PI * 180; // angle between -90 and 90 degrees
1480 if (angle_side > snd_spatialization_prologic_frontangle.value)
1482 ch->prologic_invert = -1; // this will cause the right channel to do a 180 degrees phase shift (turning the sound wave upside down),
1483 // but the best would be 90 degrees phase shift left and a -90 degrees phase shift right.
1484 angle_factor = (angle_side - snd_spatialization_prologic_frontangle.value) / (360 - 2 * snd_spatialization_prologic_frontangle.value);
1485 // angle_factor is between 0 and 1 and represents the angle range from the front left, to all the surround speakers (amount may vary,
1486 // 1 in prologic I 2 in prologic II and 3 or 4 in prologic IIx) to the front right speaker.
1487 if (angle_front > 0)
1488 angle_factor = 1 - angle_factor;
1491 angle_factor = angle_front / snd_spatialization_prologic_frontangle.value / 2.0 + 0.5;
1492 //angle_factor is between 0 and 1 and represents the angle range from the front left to the center to the front right speaker
1495 vol = intensity * sqrt(angle_factor);
1496 ch->listener_volume[0] = (int)bound(0, vol, 65536);
1497 vol = intensity * sqrt(1 - angle_factor);
1498 ch->listener_volume[1] = (int)bound(0, vol, 65536);
1499 for (i = 2;i < SND_LISTENERS;i++)
1500 ch->listener_volume[i] = 0;
1504 for (i = 0;i < SND_LISTENERS;i++)
1506 Matrix4x4_Transform(&listener_matrix[i], ch->origin, source_vec);
1507 VectorNormalize(source_vec);
1509 switch(spatialmethod)
1513 f = spatialmin + spatialdiff * (spatialfactor < 0); // avoid log(0), but do the right thing
1515 f = spatialmin + spatialdiff * bound(0, (log(dist) - spatialoffset) * spatialfactor, 1);
1516 VectorScale(source_vec, f, source_vec);
1519 f = (pow(dist, spatialpower) - spatialoffset) * spatialfactor;
1520 f = spatialmin + spatialdiff * bound(0, f, 1);
1521 VectorScale(source_vec, f, source_vec);
1523 case SPATIAL_THRESH:
1524 f = spatialmin + spatialdiff * (dist < spatialoffset);
1525 VectorScale(source_vec, f, source_vec);
1532 vol = intensity * max(0, source_vec[0] * snd_speakerlayout.listeners[i].dotscale + snd_speakerlayout.listeners[i].dotbias);
1534 ch->listener_volume[i] = (int)bound(0, vol, 65536);
1539 for (i = 0;i < SND_LISTENERS;i++)
1540 ch->listener_volume[i] = 0;
1543 void SND_Spatialize(channel_t *ch, qboolean isstatic)
1545 sfx_t *sfx = ch->sfx;
1546 SND_Spatialize_WithSfx(ch, isstatic, sfx);
1550 // =======================================================================
1551 // Start a sound effect
1552 // =======================================================================
1554 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic, int entnum, int entchannel, int startpos)
1558 Con_Printf("S_PlaySfxOnChannel called with NULL??\n");
1561 // Initialize the channel
1562 // a crash was reported on an in-use channel, so check here...
1563 if (target_chan->sfx)
1565 int channelindex = (int)(target_chan - channels);
1566 Con_Printf("S_PlaySfxOnChannel(%s): channel %i already in use?? Clearing.\n", sfx->name, channelindex);
1567 S_StopChannel (channelindex, true);
1569 // We MUST set sfx LAST because otherwise we could crash a threaded mixer
1570 // (otherwise we'd have to call SndSys_LockRenderBuffer here)
1571 memset (target_chan, 0, sizeof (*target_chan));
1572 VectorCopy (origin, target_chan->origin);
1573 target_chan->flags = flags;
1574 target_chan->pos = startpos; // start of the sound
1575 target_chan->entnum = entnum;
1576 target_chan->entchannel = entchannel;
1578 // If it's a static sound
1581 if (sfx->loopstart >= sfx->total_length && (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEWORLD))
1582 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
1583 target_chan->dist_mult = attenuation / (64.0f * snd_soundradius.value);
1586 target_chan->dist_mult = attenuation / snd_soundradius.value;
1588 // set the listener volumes
1589 S_SetChannelVolume(target_chan - channels, fvol);
1590 SND_Spatialize_WithSfx (target_chan, isstatic, sfx);
1592 // Lock the SFX during play
1595 // finally, set the sfx pointer, so the channel becomes valid for playback
1596 // and will be noticed by the mixer
1597 target_chan->sfx = sfx;
1601 int S_StartSound_StartPosition (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation, float startposition)
1603 channel_t *target_chan, *check, *ch;
1604 int ch_idx, startpos;
1606 if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1609 if(sfx == &changevolume_sfx)
1613 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
1615 ch = &channels[ch_idx];
1616 if (ch->entnum == entnum && (ch->entchannel == entchannel || entchannel == -1) )
1618 S_SetChannelVolume(ch_idx, fvol);
1619 ch->dist_mult = attenuation / snd_soundradius.value;
1620 SND_Spatialize(ch, false);
1627 if (sfx->fetcher == NULL)
1630 // Pick a channel to play on
1631 target_chan = SND_PickChannel(entnum, entchannel);
1635 // if an identical sound has also been started this frame, offset the pos
1636 // a bit to keep it from just making the first one louder
1637 check = &channels[NUM_AMBIENTS];
1638 startpos = (int)(startposition * S_GetSoundRate());
1641 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
1643 if (check == target_chan)
1645 if (check->sfx == sfx && check->pos == 0)
1647 // use negative pos offset to delay this sound effect
1648 startpos = (int)lhrandom(0, -0.1 * snd_renderbuffer->format.speed);
1654 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false, entnum, entchannel, startpos);
1656 return (target_chan - channels);
1659 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1661 return S_StartSound_StartPosition(entnum, entchannel, sfx, origin, fvol, attenuation, 0);
1664 void S_StopChannel (unsigned int channel_ind, qboolean lockmutex)
1668 if (channel_ind >= total_channels)
1671 // we have to lock an audio mutex to prevent crashes if an audio mixer
1672 // thread is currently mixing this channel
1673 // the SndSys_LockRenderBuffer function uses such a mutex in
1674 // threaded sound backends
1675 if (lockmutex && !simsound)
1676 SndSys_LockRenderBuffer();
1678 ch = &channels[channel_ind];
1679 if (ch->sfx != NULL)
1681 sfx_t *sfx = ch->sfx;
1683 if (sfx->fetcher != NULL)
1685 snd_fetcher_endsb_t fetcher_endsb = sfx->fetcher->endsb;
1686 if (fetcher_endsb != NULL)
1687 fetcher_endsb (ch->fetcher_data);
1690 // Remove the lock it holds
1693 ch->fetcher_data = NULL;
1696 if (lockmutex && !simsound)
1697 SndSys_UnlockRenderBuffer();
1701 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
1703 if (ch_ind >= total_channels)
1706 if (flag != CHANNELFLAG_FORCELOOP &&
1707 flag != CHANNELFLAG_PAUSED &&
1708 flag != CHANNELFLAG_FULLVOLUME &&
1709 flag != CHANNELFLAG_LOCALSOUND)
1713 channels[ch_ind].flags |= flag;
1715 channels[ch_ind].flags &= ~flag;
1720 void S_StopSound(int entnum, int entchannel)
1724 for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
1725 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
1727 S_StopChannel (i, true);
1732 extern void CDAudio_Stop(void);
1733 void S_StopAllSounds (void)
1737 // TOCHECK: is this test necessary?
1738 if (snd_renderbuffer == NULL)
1741 // stop CD audio because it may be using a faketrack
1744 if (simsound || SndSys_LockRenderBuffer ())
1749 for (i = 0; i < total_channels; i++)
1750 S_StopChannel (i, false);
1752 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
1753 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
1755 // Mute the contents of the submittion buffer
1756 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1757 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1758 memset(snd_renderbuffer->ring, clear, memsize);
1761 SndSys_UnlockRenderBuffer ();
1765 void S_PauseGameSounds (qboolean toggle)
1769 for (i = 0; i < total_channels; i++)
1774 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
1775 S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
1779 void S_SetChannelVolume(unsigned int ch_ind, float fvol)
1781 channels[ch_ind].master_vol = (int)(fvol * 65536.0f);
1784 float S_GetChannelPosition (unsigned int ch_ind)
1786 // note: this is NOT accurate yet
1788 channel_t *ch = &channels[ch_ind];
1789 sfx_t *sfx = ch->sfx;
1795 if(!snd_usethreadedmixing)
1796 s += _snd_mixahead.value * S_GetSoundRate();
1798 return (s % sfx->total_length) / (float) S_GetSoundRate();
1801 float S_GetEntChannelPosition(int entnum, int entchannel)
1806 for (i = 0; i < total_channels; i++)
1809 if (ch->entnum == entnum && ch->entchannel == entchannel)
1810 return S_GetChannelPosition(i);
1812 return -1; // no playing sound in this channel
1820 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
1822 channel_t *target_chan;
1824 if (snd_renderbuffer == NULL || sfx == NULL || nosound.integer)
1828 Con_Printf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
1832 if (total_channels == MAX_CHANNELS)
1834 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
1838 target_chan = &channels[total_channels++];
1839 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true, 0, 0, 0);
1845 S_UpdateAmbientSounds
1848 void S_UpdateAmbientSounds (void)
1852 int ambient_channel;
1854 unsigned char ambientlevels[NUM_AMBIENTS];
1856 memset(ambientlevels, 0, sizeof(ambientlevels));
1857 if (cl.worldmodel && cl.worldmodel->brush.AmbientSoundLevelsForPoint)
1858 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
1860 // Calc ambient sound levels
1861 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
1863 chan = &channels[ambient_channel];
1864 if (chan->sfx == NULL || chan->sfx->fetcher == NULL)
1867 vol = (int)ambientlevels[ambient_channel];
1872 // Don't adjust volume too fast
1873 // FIXME: this rounds off to an int each frame, meaning there is little to no fade at extremely high framerates!
1874 if (cl.time > cl.oldtime)
1876 if (chan->master_vol < vol)
1878 chan->master_vol += (int)((cl.time - cl.oldtime) * 256.0 * ambient_fade.value);
1879 if (chan->master_vol > vol)
1880 chan->master_vol = vol;
1882 else if (chan->master_vol > vol)
1884 chan->master_vol -= (int)((cl.time - cl.oldtime) * 256.0 * ambient_fade.value);
1885 if (chan->master_vol < vol)
1886 chan->master_vol = vol;
1890 if (snd_spatialization_prologic.integer != 0)
1892 chan->listener_volume[0] = (int)bound(0, chan->master_vol * ambient_level.value * mastervolume.value * snd_speakerlayout.listeners[0].ambientvolume * sqrt(0.5), 65536);
1893 chan->listener_volume[1] = (int)bound(0, chan->master_vol * ambient_level.value * mastervolume.value * snd_speakerlayout.listeners[1].ambientvolume * sqrt(0.5), 65536);
1894 for (i = 2;i < SND_LISTENERS;i++)
1895 chan->listener_volume[i] = 0;
1899 for (i = 0;i < SND_LISTENERS;i++)
1900 chan->listener_volume[i] = (int)bound(0, chan->master_vol * ambient_level.value * mastervolume.value * snd_speakerlayout.listeners[i].ambientvolume, 65536);
1905 static void S_PaintAndSubmit (void)
1907 unsigned int newsoundtime, paintedtime, endtime, maxtime, usedframes;
1908 int usesoundtimehack;
1909 static int soundtimehack = -1;
1910 static int oldsoundtime = 0;
1912 if (snd_renderbuffer == NULL || nosound.integer)
1915 // Update sound time
1916 snd_usethreadedmixing = false;
1917 usesoundtimehack = true;
1918 if (cls.timedemo) // SUPER NASTY HACK to mix non-realtime sound for more reliable benchmarking
1920 usesoundtimehack = 1;
1921 newsoundtime = (unsigned int)((double)cl.mtime[0] * (double)snd_renderbuffer->format.speed);
1923 else if (cls.capturevideo.soundrate && !cls.capturevideo.realtime) // SUPER NASTY HACK to record non-realtime sound
1925 usesoundtimehack = 2;
1926 newsoundtime = (unsigned int)((double)cls.capturevideo.frame * (double)snd_renderbuffer->format.speed / (double)cls.capturevideo.framerate);
1930 usesoundtimehack = 3;
1931 newsoundtime = (unsigned int)((realtime - snd_starttime) * (double)snd_renderbuffer->format.speed);
1935 snd_usethreadedmixing = snd_threaded && !cls.capturevideo.soundrate;
1936 usesoundtimehack = 0;
1937 newsoundtime = SndSys_GetSoundTime();
1939 // if the soundtimehack state changes we need to reset the soundtime
1940 if (soundtimehack != usesoundtimehack)
1942 snd_renderbuffer->startframe = snd_renderbuffer->endframe = soundtime = newsoundtime;
1944 // Mute the contents of the submission buffer
1945 if (simsound || SndSys_LockRenderBuffer ())
1950 clear = (snd_renderbuffer->format.width == 1) ? 0x80 : 0;
1951 memsize = snd_renderbuffer->maxframes * snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
1952 memset(snd_renderbuffer->ring, clear, memsize);
1955 SndSys_UnlockRenderBuffer ();
1958 soundtimehack = usesoundtimehack;
1960 if (!soundtimehack && snd_blocked > 0)
1963 if (snd_usethreadedmixing)
1964 return; // the audio thread will mix its own data
1966 newsoundtime += extrasoundtime;
1967 if (newsoundtime < soundtime)
1969 if ((cls.capturevideo.soundrate != 0) != recording_sound)
1971 unsigned int additionaltime;
1973 // add some time to extrasoundtime make newsoundtime higher
1975 // The extra time must be a multiple of the render buffer size
1976 // to avoid modifying the current position in the buffer,
1977 // some modules write directly to a shared (DMA) buffer
1978 additionaltime = (soundtime - newsoundtime) + snd_renderbuffer->maxframes - 1;
1979 additionaltime -= additionaltime % snd_renderbuffer->maxframes;
1981 extrasoundtime += additionaltime;
1982 newsoundtime += additionaltime;
1983 Con_DPrintf("S_PaintAndSubmit: new extra sound time = %u\n",
1986 else if (!soundtimehack)
1987 Con_Printf("S_PaintAndSubmit: WARNING: newsoundtime < soundtime (%u < %u)\n",
1988 newsoundtime, soundtime);
1990 soundtime = newsoundtime;
1991 recording_sound = (cls.capturevideo.soundrate != 0);
1993 // Lock submitbuffer
1994 if (!simsound && !SndSys_LockRenderBuffer())
1996 // If the lock failed, stop here
1997 Con_DPrint(">> S_PaintAndSubmit: SndSys_LockRenderBuffer() failed\n");
2001 // Check to make sure that we haven't overshot
2002 paintedtime = snd_renderbuffer->endframe;
2003 if (paintedtime < soundtime)
2004 paintedtime = soundtime;
2006 // mix ahead of current position
2008 endtime = soundtime + (unsigned int)(_snd_mixahead.value * (float)snd_renderbuffer->format.speed);
2010 endtime = soundtime + (unsigned int)(max(_snd_mixahead.value * (float)snd_renderbuffer->format.speed, min(3 * (soundtime - oldsoundtime), 0.3 * (float)snd_renderbuffer->format.speed)));
2011 usedframes = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
2012 maxtime = paintedtime + snd_renderbuffer->maxframes - usedframes;
2013 endtime = min(endtime, maxtime);
2015 while (paintedtime < endtime)
2017 unsigned int startoffset;
2018 unsigned int nbframes;
2020 // see how much we can fit in the paint buffer
2021 nbframes = endtime - paintedtime;
2022 // limit to the end of the ring buffer (in case of wrapping)
2023 startoffset = paintedtime % snd_renderbuffer->maxframes;
2024 nbframes = min(nbframes, snd_renderbuffer->maxframes - startoffset);
2026 // mix into the buffer
2027 S_MixToBuffer(&snd_renderbuffer->ring[startoffset * snd_renderbuffer->format.width * snd_renderbuffer->format.channels], nbframes);
2029 paintedtime += nbframes;
2030 snd_renderbuffer->endframe = paintedtime;
2033 SndSys_UnlockRenderBuffer();
2035 // Remove outdated samples from the ring buffer, if any
2036 if (snd_renderbuffer->startframe < soundtime)
2037 snd_renderbuffer->startframe = soundtime;
2040 snd_renderbuffer->startframe = snd_renderbuffer->endframe;
2044 oldsoundtime = soundtime;
2046 cls.soundstats.latency_milliseconds = (snd_renderbuffer->endframe - snd_renderbuffer->startframe) * 1000 / snd_renderbuffer->format.speed;
2047 R_TimeReport("audiomix");
2054 Called once each time through the main loop
2057 void S_Update(const matrix4x4_t *listenermatrix)
2059 unsigned int i, j, k;
2060 channel_t *ch, *combine;
2061 matrix4x4_t rotatematrix;
2063 if (snd_renderbuffer == NULL || nosound.integer)
2067 double mindist_trans, maxdist_trans;
2069 spatialmin = snd_spatialization_min.value;
2070 spatialdiff = snd_spatialization_max.value - spatialmin;
2072 if(snd_spatialization_control.value)
2074 spatialpower = snd_spatialization_power.value;
2076 if(spatialpower == 0)
2078 spatialmethod = SPATIAL_LOG;
2079 mindist_trans = log(max(1, snd_spatialization_min_radius.value));
2080 maxdist_trans = log(max(1, snd_spatialization_max_radius.value));
2084 spatialmethod = SPATIAL_POW;
2085 mindist_trans = pow(snd_spatialization_min_radius.value, spatialpower);
2086 maxdist_trans = pow(snd_spatialization_max_radius.value, spatialpower);
2089 if(mindist_trans - maxdist_trans == 0)
2091 spatialmethod = SPATIAL_THRESH;
2092 mindist_trans = snd_spatialization_min_radius.value;
2096 spatialoffset = mindist_trans;
2097 spatialfactor = 1 / (maxdist_trans - mindist_trans);
2101 spatialmethod = SPATIAL_NONE;
2105 // If snd_swapstereo or snd_channellayout has changed, recompute the channel layout
2106 if (current_swapstereo != boolxor(snd_swapstereo.integer, v_flipped.integer) ||
2107 current_channellayout != snd_channellayout.integer)
2108 S_SetChannelLayout();
2110 Matrix4x4_Invert_Simple(&listener_basematrix, listenermatrix);
2111 Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
2112 if (cl.worldmodel && cl.worldmodel->brush.FatPVS && cl.worldmodel->brush.num_pvsclusterbytes && cl.worldmodel->brush.PointInLeaf)
2114 if(cl.worldmodel->brush.num_pvsclusterbytes != listener_pvsbytes)
2117 Mem_Free(listener_pvs);
2118 listener_pvsbytes = cl.worldmodel->brush.num_pvsclusterbytes;
2119 listener_pvs = (unsigned char *) Mem_Alloc(snd_mempool, listener_pvsbytes);
2121 cl.worldmodel->brush.FatPVS(cl.worldmodel, listener_origin, 2, listener_pvs, listener_pvsbytes, 0);
2127 Mem_Free(listener_pvs);
2128 listener_pvs = NULL;
2130 listener_pvsbytes = 0;
2133 // calculate the current matrices
2134 for (j = 0;j < SND_LISTENERS;j++)
2136 Matrix4x4_CreateFromQuakeEntity(&rotatematrix, 0, 0, 0, 0, -snd_speakerlayout.listeners[j].yawangle, 0, 1);
2137 Matrix4x4_Concat(&listener_matrix[j], &rotatematrix, &listener_basematrix);
2138 // I think this should now do this:
2139 // 1. create a rotation matrix for rotating by e.g. -90 degrees CCW
2140 // (note: the matrix will rotate the OBJECT, not the VIEWER, so its
2141 // angle has to be taken negative)
2142 // 2. create a transform which first rotates and moves its argument
2143 // into the player's view coordinates (using basematrix which is
2144 // an inverted "absolute" listener matrix), then applies the
2145 // rotation matrix for the ear
2146 // Isn't Matrix4x4_CreateFromQuakeEntity a bit misleading because this
2147 // does not actually refer to an entity?
2150 // update general area ambient sound sources
2151 S_UpdateAmbientSounds ();
2154 R_TimeReport("audioprep");
2156 // update spatialization for static and dynamic sounds
2157 cls.soundstats.totalsounds = 0;
2158 cls.soundstats.mixedsounds = 0;
2159 ch = channels+NUM_AMBIENTS;
2160 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
2164 cls.soundstats.totalsounds++;
2166 // respatialize channel
2167 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);
2169 // try to combine static sounds with a previous channel of the same
2170 // sound effect so we don't mix five torches every frame
2171 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
2173 // no need to merge silent channels
2174 for (j = 0;j < SND_LISTENERS;j++)
2175 if (ch->listener_volume[j])
2177 if (j == SND_LISTENERS)
2179 // if the last combine chosen isn't suitable, find a new one
2180 if (!(combine && combine != ch && combine->sfx == ch->sfx))
2184 for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;j < i;j++)
2186 if (channels[j].sfx == ch->sfx)
2188 combine = channels + j;
2193 if (combine && combine != ch && combine->sfx == ch->sfx)
2195 for (j = 0;j < SND_LISTENERS;j++)
2197 combine->listener_volume[j] = bound(0, combine->listener_volume[j] + ch->listener_volume[j], 65536);
2198 ch->listener_volume[j] = 0;
2202 for (k = 0;k < SND_LISTENERS;k++)
2203 if (ch->listener_volume[k])
2205 if (k < SND_LISTENERS)
2206 cls.soundstats.mixedsounds++;
2208 R_TimeReport("audiospatialize");
2210 sound_spatialized = true;
2213 if (snd_show.integer)
2214 Con_Printf("----(%u)----\n", cls.soundstats.mixedsounds);
2219 void S_ExtraUpdate (void)
2221 if (snd_noextraupdate.integer || !sound_spatialized)
2227 qboolean S_LocalSound (const char *sound)
2232 if (!snd_initialized.integer || nosound.integer)
2235 sfx = S_PrecacheSound (sound, true, false);
2238 Con_Printf("S_LocalSound: can't precache %s\n", sound);
2242 // Local sounds must not be freed
2243 sfx->flags |= SFXFLAG_PERMANENTLOCK;
2245 ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 0);
2249 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;