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