]> icculus.org git repositories - divverent/darkplaces.git/blob - snd_main.c
improved how showfps 1 measures framerate, it's now a bit more accurate, still reads...
[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
27
28 void S_Play(void);
29 void S_PlayVol(void);
30 void S_Play2(void);
31 void S_SoundList(void);
32 void S_Update_();
33
34 void S_ClearBuffer (void);
35
36
37 // =======================================================================
38 // Internal sound data & structures
39 // =======================================================================
40
41 channel_t channels[MAX_CHANNELS];
42 unsigned int total_channels;
43
44 int snd_blocked = 0;
45 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0"};
46 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1"};
47
48 volatile dma_t *shm = 0;
49 volatile dma_t sn;
50
51 vec3_t listener_origin;
52 matrix4x4_t listener_matrix;
53 vec_t sound_nominal_clip_dist=1000.0;
54 mempool_t *snd_mempool;
55
56 // sample PAIRS
57 int soundtime;
58 int paintedtime;
59
60
61 // Linked list of known sfx
62 sfx_t *known_sfx = NULL;
63
64 qboolean sound_started = false;
65 qboolean sound_spatialized = false;
66
67 // Fake dma is a synchronous faking of the DMA progress used for
68 // isolating performance in the renderer.
69 qboolean fakedma = false;
70
71 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
72 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
73 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1"};
74
75 cvar_t nosound = {0, "nosound", "0"};
76 cvar_t snd_precache = {0, "snd_precache", "1"};
77 cvar_t bgmbuffer = {0, "bgmbuffer", "4096"};
78 cvar_t ambient_level = {0, "ambient_level", "0.3"};
79 cvar_t ambient_fade = {0, "ambient_fade", "100"};
80 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0"};
81 cvar_t snd_show = {0, "snd_show", "0"};
82 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1"};
83 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0"};
84
85
86 // ====================================================================
87 // User-setable variables
88 // ====================================================================
89
90 void S_SoundInfo_f(void)
91 {
92         if (!sound_started || !shm)
93         {
94                 Con_Print("sound system not started\n");
95                 return;
96         }
97
98         Con_Printf("%5d stereo\n", shm->format.channels - 1);
99         Con_Printf("%5d samples\n", shm->samples);
100         Con_Printf("%5d samplepos\n", shm->samplepos);
101         Con_Printf("%5d samplebits\n", shm->format.width * 8);
102         Con_Printf("%5d speed\n", shm->format.speed);
103         Con_Printf("%p dma buffer\n", shm->buffer);
104         Con_Printf("%5u total_channels\n", total_channels);
105 }
106
107
108 void S_Startup(void)
109 {
110         if (!snd_initialized.integer)
111                 return;
112
113         shm = &sn;
114         memset((void *)shm, 0, sizeof(*shm));
115
116         // create a piece of DMA memory
117         if (fakedma)
118         {
119                 shm->format.width = 2;
120                 shm->format.speed = 22050;
121                 shm->format.channels = 2;
122                 shm->samples = 32768;
123                 shm->samplepos = 0;
124                 shm->buffer = Mem_Alloc(snd_mempool, shm->format.channels * shm->samples * shm->format.width);
125         }
126         else
127         {
128                 if (!SNDDMA_Init())
129                 {
130                         Con_Print("S_Startup: SNDDMA_Init failed.\n");
131                         shm = NULL;
132                         sound_started = false;
133                         sound_spatialized = false;
134                         return;
135                 }
136         }
137
138         sound_started = true;
139
140         Con_DPrintf("Sound sampling rate: %i\n", shm->format.speed);
141
142         S_StopAllSounds ();
143 }
144
145 void S_Shutdown(void)
146 {
147         if (!sound_started)
148                 return;
149
150         if (fakedma)
151                 Mem_Free(shm->buffer);
152         else
153                 SNDDMA_Shutdown();
154
155         shm = NULL;
156         sound_started = false;
157         sound_spatialized = false;
158 }
159
160 void S_Restart_f(void)
161 {
162         S_Shutdown();
163         S_Startup();
164 }
165
166 /*
167 ================
168 S_Init
169 ================
170 */
171 void S_Init(void)
172 {
173         Con_DPrint("\nSound Initialization\n");
174
175         Cvar_RegisterVariable(&volume);
176         Cvar_RegisterVariable(&bgmvolume);
177         Cvar_RegisterVariable(&snd_staticvolume);
178
179 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
180         if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
181                 return;
182
183         snd_mempool = Mem_AllocPool("sound", 0, NULL);
184
185 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
186         if (COM_CheckParm("-simsound"))
187                 fakedma = true;
188
189         Cmd_AddCommand("play", S_Play);
190         Cmd_AddCommand("play2", S_Play2);
191         Cmd_AddCommand("playvol", S_PlayVol);
192         Cmd_AddCommand("stopsound", S_StopAllSounds);
193         Cmd_AddCommand("soundlist", S_SoundList);
194         Cmd_AddCommand("soundinfo", S_SoundInfo_f);
195         Cmd_AddCommand("snd_restart", S_Restart_f);
196
197         Cvar_RegisterVariable(&nosound);
198         Cvar_RegisterVariable(&snd_precache);
199         Cvar_RegisterVariable(&snd_initialized);
200         Cvar_RegisterVariable(&snd_streaming);
201         Cvar_RegisterVariable(&bgmbuffer);
202         Cvar_RegisterVariable(&ambient_level);
203         Cvar_RegisterVariable(&ambient_fade);
204         Cvar_RegisterVariable(&snd_noextraupdate);
205         Cvar_RegisterVariable(&snd_show);
206         Cvar_RegisterVariable(&_snd_mixahead);
207         Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
208
209         Cvar_SetValueQuick(&snd_initialized, true);
210
211         known_sfx = NULL;
212
213         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
214         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
215
216         OGG_OpenLibrary ();
217 }
218
219
220 // =======================================================================
221 // Load a sound
222 // =======================================================================
223
224 /*
225 ==================
226 S_FindName
227
228 ==================
229 */
230 sfx_t *S_FindName (const char *name)
231 {
232         sfx_t *sfx;
233
234         if (!snd_initialized.integer)
235                 return NULL;
236
237         // Add the default sound directory to the path
238         if (strlen (name) >= sizeof (sfx->name))
239                 Host_Error ("S_FindName: sound name too long (%s)", name);
240
241         // Look for this sound in the list of known sfx
242         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
243                 if(!strcmp (sfx->name, name))
244                         return sfx;
245
246         // Add a sfx_t struct for this sound
247         sfx = Mem_Alloc (snd_mempool, sizeof (*sfx));
248         memset (sfx, 0, sizeof(*sfx));
249         strlcpy (sfx->name, name, sizeof (sfx->name));
250         sfx->next = known_sfx;
251         known_sfx = sfx;
252
253         return sfx;
254 }
255
256
257 /*
258 ==================
259 S_FreeSfx
260
261 ==================
262 */
263 void S_FreeSfx (sfx_t *sfx)
264 {
265         // Never free a locked sfx
266         if (sfx->locks > 0)
267                 return;
268
269         Con_DPrintf ("S_FreeSfx: freeing %s\n", sfx->name);
270
271         // Remove it from the list of known sfx
272         if (sfx == known_sfx)
273                 known_sfx = known_sfx->next;
274         else
275         {
276                 sfx_t *prev_sfx;
277
278                 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
279                         if (prev_sfx->next == sfx)
280                         {
281                                 prev_sfx->next = sfx->next;
282                                 break;
283                         }
284                 if (prev_sfx == NULL)
285                         Sys_Error ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
286         }
287
288         // Free it
289         Mem_FreePool (&sfx->mempool);
290         Mem_Free (sfx);
291 }
292
293
294 /*
295 ==================
296 S_ServerSounds
297
298 ==================
299 */
300 void S_ServerSounds (char serversound [][MAX_QPATH], unsigned int numsounds)
301 {
302         sfx_t *sfx;
303         unsigned int i;
304
305         // Start the ambient sounds and make them loop
306         channels[AMBIENT_WATER].sfx = S_PrecacheSound ("sound/ambience/water1.wav", false, true);
307         channels[AMBIENT_SKY].sfx = S_PrecacheSound ("sound/ambience/wind2.wav", false, true);
308         for (i = 0; i < NUM_AMBIENTS; i++)
309                 channels[i].flags |= CHANNELFLAG_FORCELOOP;
310
311         // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
312         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
313                 if (sfx->flags & SFXFLAG_SERVERSOUND)
314                 {
315                         sfx->locks--;
316                         sfx->flags &= ~SFXFLAG_SERVERSOUND;
317                 }
318
319         // Add 1 lock and the SFXFLAG_SERVERSOUND flag to each sfx in "serversound"
320         for (i = 1; i < numsounds; i++)
321         {
322                 sfx = S_FindName (serversound[i]);
323                 if (sfx != NULL)
324                 {
325                         sfx->locks++;
326                         sfx->flags |= SFXFLAG_SERVERSOUND;
327                 }
328         }
329
330         // Free all unlocked sfx
331         sfx = known_sfx;
332         while (sfx != NULL)
333         {
334                 sfx_t* crtsfx;
335
336                 // We may lose the "next" pointer after S_FreeSfx
337                 crtsfx = sfx;
338                 sfx = sfx->next;
339
340                 S_FreeSfx (crtsfx);
341         }
342 }
343
344
345 /*
346 ==================
347 S_PrecacheSound
348
349 ==================
350 */
351 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean lock)
352 {
353         sfx_t *sfx;
354
355         if (!snd_initialized.integer)
356                 return NULL;
357
358         sfx = S_FindName (name);
359         if (sfx == NULL)
360                 return NULL;
361
362         if (lock)
363                 sfx->locks++;
364
365         if (!nosound.integer && snd_precache.integer)
366                 S_LoadSound(sfx, complain);
367
368         return sfx;
369 }
370
371 /*
372 ==================
373 S_UnlockSfx
374
375 Remove a lock from a SFX and freed it if possible
376 ==================
377 */
378 void S_UnlockSfx (sfx_t *sfx)
379 {
380         sfx->locks--;
381         S_FreeSfx (sfx);
382 }
383
384
385 //=============================================================================
386
387 /*
388 =================
389 SND_PickChannel
390
391 Picks a channel based on priorities, empty slots, number of channels
392 =================
393 */
394 channel_t *SND_PickChannel(int entnum, int entchannel)
395 {
396         int ch_idx;
397         int first_to_die;
398         int life_left;
399         channel_t* ch;
400
401 // Check for replacement sound, or find the best one to replace
402         first_to_die = -1;
403         life_left = 0x7fffffff;
404         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
405         {
406                 ch = &channels[ch_idx];
407                 if (entchannel != 0             // channel 0 never overrides
408                 && ch->entnum == entnum
409                 && (ch->entchannel == entchannel || entchannel == -1) )
410                 {       // always override sound from same entity
411                         first_to_die = ch_idx;
412                         break;
413                 }
414
415                 // don't let monster sounds override player sounds
416                 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
417                         continue;
418
419                 // don't override looped sounds
420                 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
421                         (ch->sfx != NULL && ch->sfx->loopstart >= 0))
422                         continue;
423
424                 if (ch->end - paintedtime < life_left)
425                 {
426                         life_left = ch->end - paintedtime;
427                         first_to_die = ch_idx;
428                 }
429         }
430
431         if (first_to_die == -1)
432                 return NULL;
433
434         S_StopChannel (first_to_die);
435
436         return &channels[first_to_die];
437 }
438
439 /*
440 =================
441 SND_Spatialize
442
443 Spatializes a channel
444 =================
445 */
446 void SND_Spatialize(channel_t *ch, qboolean isstatic)
447 {
448         vec_t dist, scale, pan;
449         vec3_t source_vec;
450
451         // anything coming from the view entity will always be full volume
452         // LordHavoc: make sounds with ATTN_NONE have no spatialization
453         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
454         {
455                 ch->leftvol = ch->master_vol;
456                 ch->rightvol = ch->master_vol;
457         }
458         else
459         {
460                 // update sound origin if we know about the entity
461                 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
462                 {
463                         //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]);
464                         VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
465                         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)
466                                 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);
467                 }
468
469                 // calculate stereo seperation and distance attenuation
470                 Matrix4x4_Transform(&listener_matrix, ch->origin, source_vec);
471                 dist = VectorNormalizeLength(source_vec);
472                 // distance
473                 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
474                 // panning
475                 pan = scale * source_vec[1];
476                 // calculate the volumes
477                 ch->leftvol = (int) (scale + pan);
478                 ch->rightvol = (int) (scale - pan);
479         }
480
481         // Adjust volume of static sounds
482         if (isstatic)
483         {
484                 ch->leftvol *= snd_staticvolume.value;
485                 ch->rightvol *= snd_staticvolume.value;
486         }
487
488         // clamp volumes
489         ch->leftvol = bound(0, ch->leftvol, 255);
490         ch->rightvol = bound(0, ch->rightvol, 255);
491 }
492
493
494 // =======================================================================
495 // Start a sound effect
496 // =======================================================================
497
498 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
499 {
500         // Initialize the channel
501         memset (target_chan, 0, sizeof (*target_chan));
502         VectorCopy (origin, target_chan->origin);
503         target_chan->master_vol = fvol * 255;
504         target_chan->sfx = sfx;
505         target_chan->end = paintedtime + sfx->total_length;
506         target_chan->lastptime = paintedtime;
507         target_chan->flags = flags;
508
509         // If it's a static sound
510         if (isstatic)
511         {
512                 if (sfx->loopstart == -1)
513                         Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
514                 target_chan->dist_mult = attenuation / (64.0f * sound_nominal_clip_dist);
515         }
516         else
517                 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
518
519         // Lock the SFX during play
520         sfx->locks++;
521 }
522
523
524 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
525 {
526         channel_t *target_chan, *check;
527         int             ch_idx;
528         size_t  skip;
529
530         if (!sound_started || !sfx || !sfx->fetcher || nosound.integer)
531                 return -1;
532
533         // Pick a channel to play on
534         target_chan = SND_PickChannel(entnum, entchannel);
535         if (!target_chan)
536                 return -1;
537
538         if (!S_LoadSound (sfx, true))
539                 return -1;              // couldn't load the sound's data
540
541         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
542         target_chan->entnum = entnum;
543         target_chan->entchannel = entchannel;
544
545         SND_Spatialize(target_chan, false);
546
547         // if an identical sound has also been started this frame, offset the pos
548         // a bit to keep it from just making the first one louder
549         check = &channels[NUM_AMBIENTS];
550         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
551         {
552                 if (check == target_chan)
553                         continue;
554                 if (check->sfx == sfx && !check->pos)
555                 {
556                         skip = 0.1 * sfx->format.speed;
557                         if (skip > sfx->total_length)
558                                 skip = sfx->total_length;
559                         if (skip > 0)
560                                 skip = rand() % skip;
561                         target_chan->pos += skip;
562                         target_chan->end -= skip;
563                         break;
564                 }
565         }
566
567         return (target_chan - channels);
568 }
569
570 void S_StopChannel (unsigned int channel_ind)
571 {
572         channel_t *ch;
573
574         if (channel_ind >= total_channels)
575                 return;
576
577         ch = &channels[channel_ind];
578         if (ch->sfx != NULL)
579         {
580                 sfx_t *sfx = ch->sfx;
581
582                 if (sfx->fetcher != NULL)
583                 {
584                         snd_fetcher_end_t fetcher_end = sfx->fetcher->end;
585                         if (fetcher_end != NULL)
586                                 fetcher_end (ch);
587                 }
588
589                 // Remove the lock it holds
590                 S_UnlockSfx (sfx);
591
592                 ch->sfx = NULL;
593         }
594         ch->end = 0;
595 }
596
597
598 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
599 {
600         if (ch_ind >= total_channels)
601                 return false;
602
603         if (flag != CHANNELFLAG_FORCELOOP &&
604                 flag != CHANNELFLAG_PAUSED &&
605                 flag != CHANNELFLAG_FULLVOLUME)
606                 return false;
607
608         if (value)
609                 channels[ch_ind].flags |= flag;
610         else
611                 channels[ch_ind].flags &= ~flag;
612
613         return true;
614 }
615
616 void S_StopSound(int entnum, int entchannel)
617 {
618         unsigned int i;
619
620         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
621                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
622                 {
623                         S_StopChannel (i);
624                         return;
625                 }
626 }
627
628 void S_StopAllSounds (void)
629 {
630         unsigned int i;
631
632         for (i = 0; i < total_channels; i++)
633                 S_StopChannel (i);
634
635         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
636         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
637
638         S_ClearBuffer ();
639 }
640
641 void S_PauseGameSounds (qboolean toggle)
642 {
643         unsigned int i;
644
645         for (i = 0; i < total_channels; i++)
646         {
647                 channel_t *ch;
648
649                 ch = &channels[i];
650                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
651                         S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
652         }
653 }
654
655 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
656 {
657         channels[ch_ind].master_vol = fvol * 255;
658 }
659
660
661 void S_ClearBuffer(void)
662 {
663         int     clear;
664         unsigned char *pbuf;
665
666         if (!sound_started || !shm)
667                 return;
668
669         if (shm->format.width == 1)
670                 clear = 0x80;   // 8 bit sound (unsigned)
671         else
672                 clear = 0;              // 16 bit sound (signed)
673
674         pbuf = S_LockBuffer();
675         if (pbuf != NULL)
676         {
677                 int setsize = shm->samples * shm->format.width;
678
679                 while (setsize--)
680                         *pbuf++ = clear;
681
682                 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
683                 // reads the memory area before writing to it causing a seg fault
684                 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
685                 //memset(shm->buffer, clear, shm->samples * shm->format.width);
686
687                 S_UnlockBuffer ();
688         }
689 }
690
691
692 /*
693 =================
694 S_StaticSound
695 =================
696 */
697 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
698 {
699         channel_t       *target_chan;
700
701         if (!sfx)
702                 return;
703
704         if (total_channels == MAX_CHANNELS)
705         {
706                 Con_Print("total_channels == MAX_CHANNELS\n");
707                 return;
708         }
709
710         if (!S_LoadSound (sfx, true))
711                 return;
712
713         target_chan = &channels[total_channels++];
714         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
715
716         SND_Spatialize (target_chan, true);
717 }
718
719
720 //=============================================================================
721
722 /*
723 ===================
724 S_UpdateAmbientSounds
725
726 ===================
727 */
728 void S_UpdateAmbientSounds (void)
729 {
730         float           vol;
731         int                     ambient_channel;
732         channel_t       *chan;
733         qbyte           ambientlevels[NUM_AMBIENTS];
734
735         // Mute ambient sounds until proven otherwise
736         for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
737                 channels[ambient_channel].master_vol = 0;
738
739         if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
740                 return;
741
742         cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
743
744         // Calc ambient sound levels
745         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
746         {
747                 chan = &channels[ambient_channel];
748                 if (chan->sfx == NULL || (chan->sfx->flags & SFXFLAG_FILEMISSING))
749                         continue;
750
751                 vol = ambient_level.value * ambientlevels[ambient_channel];
752                 if (vol < 8)
753                         vol = 0;
754
755                 // Don't adjust volume too fast
756                 if (chan->master_vol < vol)
757                 {
758                         chan->master_vol += host_realframetime * ambient_fade.value;
759                         if (chan->master_vol > vol)
760                                 chan->master_vol = vol;
761                 }
762                 else if (chan->master_vol > vol)
763                 {
764                         chan->master_vol -= host_realframetime * ambient_fade.value;
765                         if (chan->master_vol < vol)
766                                 chan->master_vol = vol;
767                 }
768
769                 chan->leftvol = chan->rightvol = chan->master_vol;
770         }
771 }
772
773
774 /*
775 ============
776 S_Update
777
778 Called once each time through the main loop
779 ============
780 */
781 void S_Update(const matrix4x4_t *listenermatrix)
782 {
783         unsigned int i, j, total;
784         channel_t *ch, *combine;
785
786         if (!snd_initialized.integer || (snd_blocked > 0))
787                 return;
788
789         Matrix4x4_Invert_Simple(&listener_matrix, listenermatrix);
790         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
791
792         // update general area ambient sound sources
793         S_UpdateAmbientSounds ();
794
795         combine = NULL;
796
797         // update spatialization for static and dynamic sounds
798         ch = channels+NUM_AMBIENTS;
799         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
800         {
801                 if (!ch->sfx)
802                         continue;
803                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);         // respatialize channel
804                 if (!ch->leftvol && !ch->rightvol)
805                         continue;
806
807                 // try to combine static sounds with a previous channel of the same
808                 // sound effect so we don't mix five torches every frame
809                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
810                 {
811                         // see if it can just use the last one
812                         if (combine && combine->sfx == ch->sfx)
813                         {
814                                 combine->leftvol += ch->leftvol;
815                                 combine->rightvol += ch->rightvol;
816                                 ch->leftvol = ch->rightvol = 0;
817                                 continue;
818                         }
819                         // search for one
820                         combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
821                         for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
822                                 if (combine->sfx == ch->sfx)
823                                         break;
824
825                         if (j == total_channels)
826                                 combine = NULL;
827                         else
828                         {
829                                 if (combine != ch)
830                                 {
831                                         combine->leftvol += ch->leftvol;
832                                         combine->rightvol += ch->rightvol;
833                                         ch->leftvol = ch->rightvol = 0;
834                                 }
835                                 continue;
836                         }
837                 }
838         }
839
840         sound_spatialized = true;
841
842         // debugging output
843         if (snd_show.integer)
844         {
845                 total = 0;
846                 ch = channels;
847                 for (i=0 ; i<total_channels; i++, ch++)
848                         if (ch->sfx && (ch->leftvol || ch->rightvol) )
849                                 total++;
850
851                 Con_Printf("----(%u)----\n", total);
852         }
853
854         S_Update_();
855 }
856
857 void GetSoundtime(void)
858 {
859         int             samplepos;
860         static  int             buffers;
861         static  int             oldsamplepos;
862         int             fullsamples;
863
864         fullsamples = shm->samples / shm->format.channels;
865
866         // it is possible to miscount buffers if it has wrapped twice between
867         // calls to S_Update.  Oh well.
868         samplepos = SNDDMA_GetDMAPos();
869
870         if (samplepos < oldsamplepos)
871         {
872                 buffers++;                                      // buffer wrapped
873
874                 if (paintedtime > 0x40000000)
875                 {       // time to chop things off to avoid 32 bit limits
876                         buffers = 0;
877                         paintedtime = fullsamples;
878                         S_StopAllSounds ();
879                 }
880         }
881         oldsamplepos = samplepos;
882
883         soundtime = buffers * fullsamples + samplepos / shm->format.channels;
884 }
885
886 void S_ExtraUpdate (void)
887 {
888         if (snd_noextraupdate.integer || !sound_spatialized)
889                 return;
890
891         S_Update_();
892 }
893
894 void S_Update_(void)
895 {
896         unsigned        endtime;
897         int                             samps;
898
899         if (!sound_started || (snd_blocked > 0))
900                 return;
901
902         // Updates DMA time
903         GetSoundtime();
904
905         // check to make sure that we haven't overshot
906         if (paintedtime < soundtime)
907                 paintedtime = soundtime;
908
909         // mix ahead of current position
910         endtime = soundtime + _snd_mixahead.value * shm->format.speed;
911         samps = shm->samples >> (shm->format.channels - 1);
912         if (endtime > (unsigned int)(soundtime + samps))
913                 endtime = soundtime + samps;
914
915         S_PaintChannels (endtime);
916
917         SNDDMA_Submit ();
918 }
919
920 /*
921 ===============================================================================
922
923 console functions
924
925 ===============================================================================
926 */
927
928 static void S_Play_Common(float fvol, float attenuation)
929 {
930         int     i, ch_ind;
931         char name[256];
932         sfx_t   *sfx;
933
934         i = 1;
935         while (i<Cmd_Argc())
936         {
937                 if (!strrchr(Cmd_Argv(i), '.'))
938                         snprintf(name, sizeof(name), "%s.wav", Cmd_Argv(i));
939                 else
940                         strlcpy(name, Cmd_Argv(i), sizeof(name));
941                 sfx = S_PrecacheSound (name, true, false);
942
943                 // If we need to get the volume from the command line
944                 if (fvol == -1.0f)
945                 {
946                         fvol = atof(Cmd_Argv(i+1));
947                         i += 2;
948                 }
949                 else
950                         i++;
951
952                 ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
953
954                 // Free the sfx if the file didn't exist
955                 if (ch_ind < 0)
956                         S_FreeSfx (sfx);
957                 else
958                         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
959         }
960 }
961
962 void S_Play(void)
963 {
964         S_Play_Common (1.0f, 1.0f);
965 }
966
967 void S_Play2(void)
968 {
969         S_Play_Common (1.0f, 0.0f);
970 }
971
972 void S_PlayVol(void)
973 {
974         S_Play_Common (-1.0f, 0.0f);
975 }
976
977 void S_SoundList(void)
978 {
979         unsigned int i;
980         sfx_t   *sfx;
981         int             size, total;
982
983         total = 0;
984         for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
985         {
986                 if (sfx->fetcher != NULL)
987                 {
988                         size = sfx->mempool->totalsize;
989                         total += size;
990                         Con_Printf ("%c%c(%2db, %6s) %8i : %s\n",
991                                                 (sfx->loopstart >= 0) ? 'L' : ' ',
992                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
993                                                 sfx->format.width * 8,
994                                                 (sfx->format.channels == 1) ? "mono" : "stereo",
995                                                 size,
996                                                 sfx->name);
997                 }
998         }
999         Con_Printf("Total resident: %i\n", total);
1000 }
1001
1002
1003 qboolean S_LocalSound (const char *sound)
1004 {
1005         sfx_t   *sfx;
1006         int             ch_ind;
1007
1008         if (!snd_initialized.integer || nosound.integer)
1009                 return true;
1010
1011         sfx = S_PrecacheSound (sound, true, false);
1012         if (!sfx)
1013         {
1014                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1015                 return false;
1016         }
1017
1018         ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 1);
1019         if (ch_ind < 0)
1020                 return false;
1021
1022         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1023         return true;
1024 }