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