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