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