]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_dma.c
winquake.h is gone, absorbed into the respective files which used it, also cleaned...
[xonotic/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_IsCached
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         S_FindName(name);
346 }
347
348 /*
349 ==================
350 S_PrecacheSound
351
352 ==================
353 */
354 sfx_t *S_PrecacheSound (char *name, int complain)
355 {
356         sfx_t *sfx;
357
358         if (!snd_initialized.integer)
359                 return NULL;
360
361         sfx = S_FindName(name);
362
363         if (!nosound.integer && snd_precache.integer)
364                 S_LoadSound(sfx, complain);
365
366         return sfx;
367 }
368
369
370 //=============================================================================
371
372 /*
373 =================
374 SND_PickChannel
375 =================
376 */
377 channel_t *SND_PickChannel(int entnum, int entchannel)
378 {
379         int ch_idx;
380         int first_to_die;
381         int life_left;
382
383 // Check for replacement sound, or find the best one to replace
384         first_to_die = -1;
385         life_left = 0x7fffffff;
386         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
387         {
388                 if (entchannel != 0             // channel 0 never overrides
389                 && channels[ch_idx].entnum == entnum
390                 && (channels[ch_idx].entchannel == entchannel || entchannel == -1) )
391                 {       // always override sound from same entity
392                         first_to_die = ch_idx;
393                         break;
394                 }
395
396                 // don't let monster sounds override player sounds
397                 if (channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && channels[ch_idx].sfx)
398                         continue;
399
400                 if (channels[ch_idx].end - paintedtime < life_left)
401                 {
402                         life_left = channels[ch_idx].end - paintedtime;
403                         first_to_die = ch_idx;
404                 }
405         }
406
407         if (first_to_die == -1)
408                 return NULL;
409
410         if (channels[first_to_die].sfx)
411                 channels[first_to_die].sfx = NULL;
412
413         return &channels[first_to_die];
414 }
415
416 /*
417 =================
418 SND_Spatialize
419 =================
420 */
421 void SND_Spatialize(channel_t *ch, int isstatic)
422 {
423         vec_t dist, scale, pan;
424         vec3_t source_vec;
425
426         // anything coming from the view entity will always be full volume
427         // LordHavoc: make sounds with ATTN_NONE have no spatialization
428         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
429         {
430                 ch->leftvol = ch->master_vol;
431                 ch->rightvol = ch->master_vol;
432         }
433         else
434         {
435                 // update sound origin if we know about the entity
436                 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
437                 {
438                         //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]);
439                         VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
440                         if (cl_entities[ch->entnum].state_current.modelindex && cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->soundfromcenter)
441                                 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);
442                 }
443
444                 // calculate stereo seperation and distance attenuation
445                 VectorSubtract(ch->origin, listener_vieworigin, source_vec);
446                 dist = VectorNormalizeLength(source_vec);
447                 // distance
448                 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
449                 // panning
450                 pan = scale * DotProduct(listener_viewleft, source_vec);
451                 // calculate the volumes
452                 ch->leftvol = (int) (scale + pan);
453                 ch->rightvol = (int) (scale - pan);
454         }
455
456         // LordHavoc: allow adjusting volume of static sounds
457         if (isstatic)
458         {
459                 ch->leftvol *= snd_staticvolume.value;
460                 ch->rightvol *= snd_staticvolume.value;
461         }
462
463         // clamp volumes
464         ch->leftvol = bound(0, ch->leftvol, 255);
465         ch->rightvol = bound(0, ch->rightvol, 255);
466 }
467
468
469 // =======================================================================
470 // Start a sound effect
471 // =======================================================================
472
473 void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
474 {
475         channel_t *target_chan, *check;
476         sfxcache_t      *sc;
477         int             vol;
478         int             ch_idx;
479         int             skip;
480
481         if (!sound_started || !sfx || !sfx->sfxcache || nosound.integer)
482                 return;
483
484         vol = fvol*255;
485
486 // pick a channel to play on
487         target_chan = SND_PickChannel(entnum, entchannel);
488         if (!target_chan)
489                 return;
490
491 // spatialize
492         memset (target_chan, 0, sizeof(*target_chan));
493         VectorCopy(origin, target_chan->origin);
494         target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
495         target_chan->master_vol = vol;
496         target_chan->entnum = entnum;
497         target_chan->entchannel = entchannel;
498         SND_Spatialize(target_chan, false);
499
500         // LordHavoc: spawn the sound anyway because the player might teleport to it
501         //if (!target_chan->leftvol && !target_chan->rightvol)
502         //      return;         // not audible at all
503
504 // new channel
505         sc = S_LoadSound (sfx, true);
506         if (!sc)
507         {
508                 target_chan->sfx = NULL;
509                 return;         // couldn't load the sound's data
510         }
511
512         target_chan->sfx = sfx;
513         target_chan->pos = 0.0;
514         target_chan->end = paintedtime + sc->length;
515
516 // if an identical sound has also been started this frame, offset the pos
517 // a bit to keep it from just making the first one louder
518         check = &channels[NUM_AMBIENTS];
519         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
520         {
521                 if (check == target_chan)
522                         continue;
523                 if (check->sfx == sfx && !check->pos)
524                 {
525                         // LordHavoc: fixed skip calculations
526                         skip = 0.1 * sc->speed;
527                         if (skip > sc->length)
528                                 skip = sc->length;
529                         if (skip > 0)
530                                 skip = rand() % skip;
531                         target_chan->pos += skip;
532                         target_chan->end -= skip;
533                         break;
534                 }
535         }
536 }
537
538 void S_StopSound(int entnum, int entchannel)
539 {
540         int i;
541
542         for (i=0 ; i<MAX_DYNAMIC_CHANNELS ; i++)
543         {
544                 if (channels[i].entnum == entnum
545                         && channels[i].entchannel == entchannel)
546                 {
547                         channels[i].end = 0;
548                         channels[i].sfx = NULL;
549                         return;
550                 }
551         }
552 }
553
554 void S_StopAllSounds(qboolean clear)
555 {
556         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
557         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
558
559         if (clear)
560                 S_ClearBuffer();
561 }
562
563 void S_StopAllSoundsC(void)
564 {
565         S_StopAllSounds(true);
566 }
567
568 void S_ClearBuffer(void)
569 {
570         int             clear;
571
572         if (!sound_started || !shm)
573                 return;
574
575         if (shm->samplebits == 8)
576                 clear = 0x80;
577         else
578                 clear = 0;
579
580 #ifdef _WIN32
581         if (pDSBuf)
582         {
583                 DWORD   dwSize;
584                 DWORD   *pData;
585                 int             reps;
586                 HRESULT hresult;
587
588                 reps = 0;
589
590                 while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, (LPVOID*)&pData, &dwSize, NULL, NULL, 0)) != DS_OK)
591                 {
592                         if (hresult != DSERR_BUFFERLOST)
593                         {
594                                 Con_Printf ("S_ClearBuffer: DS::Lock Sound Buffer Failed\n");
595                                 S_Shutdown ();
596                                 return;
597                         }
598
599                         if (++reps > 10000)
600                         {
601                                 Con_Printf ("S_ClearBuffer: DS: couldn't restore buffer\n");
602                                 S_Shutdown ();
603                                 return;
604                         }
605                 }
606
607                 memset(pData, clear, shm->samples * shm->samplebits/8);
608
609                 pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0);
610
611         }
612         else
613 #endif
614         if (shm->buffer)
615         {
616                 int             setsize = shm->samples * shm->samplebits / 8;
617                 char    *buf = shm->buffer;
618
619                 while (setsize--)
620                         *buf++ = clear;
621
622 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
623 // reads the memory area before writing to it causing a seg fault
624 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
625 //              memset(shm->buffer, clear, shm->samples * shm->samplebits/8);
626         }
627 }
628
629
630 /*
631 =================
632 S_StaticSound
633 =================
634 */
635 void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation)
636 {
637         channel_t       *ss;
638         sfxcache_t              *sc;
639
640         if (!sfx)
641                 return;
642
643         if (total_channels == MAX_CHANNELS)
644         {
645                 Con_Printf ("total_channels == MAX_CHANNELS\n");
646                 return;
647         }
648
649         sc = S_LoadSound (sfx, true);
650         if (!sc)
651                 return;
652
653         if (sc->loopstart == -1)
654                 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
655
656         ss = &channels[total_channels++];
657         memset(ss, 0, sizeof(*ss));
658         ss->forceloop = true;
659         ss->sfx = sfx;
660         VectorCopy (origin, ss->origin);
661         ss->master_vol = vol;
662         ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist;
663         ss->end = paintedtime + sc->length;
664
665         SND_Spatialize (ss, true);
666 }
667
668
669 //=============================================================================
670
671 /*
672 ===================
673 S_UpdateAmbientSounds
674 ===================
675 */
676 void S_UpdateAmbientSounds (void)
677 {
678         float           vol;
679         int                     ambient_channel;
680         channel_t       *chan;
681         qbyte           ambientlevels[NUM_AMBIENTS];
682
683         // LordHavoc: kill ambient sounds until proven otherwise
684         for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
685                 channels[ambient_channel].sfx = NULL;
686
687         if (!snd_ambient || ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
688                 return;
689
690         cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_vieworigin, ambientlevels, sizeof(ambientlevels));
691
692 // calc ambient sound levels
693         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
694         {
695                 if (ambient_sfx[ambient_channel] && ambient_sfx[ambient_channel]->silentlymissing)
696                         continue;
697                 chan = &channels[ambient_channel];
698                 chan->forceloop = true;
699                 chan->sfx = ambient_sfx[ambient_channel];
700
701                 vol = ambient_level.value * ambientlevels[ambient_channel];
702                 if (vol < 8)
703                         vol = 0;
704
705         // don't adjust volume too fast
706                 if (chan->master_vol < vol)
707                 {
708                         chan->master_vol += host_realframetime * ambient_fade.value;
709                         if (chan->master_vol > vol)
710                                 chan->master_vol = vol;
711                 }
712                 else if (chan->master_vol > vol)
713                 {
714                         chan->master_vol -= host_realframetime * ambient_fade.value;
715                         if (chan->master_vol < vol)
716                                 chan->master_vol = vol;
717                 }
718
719                 chan->leftvol = chan->rightvol = chan->master_vol;
720         }
721 }
722
723
724 /*
725 ============
726 S_Update
727
728 Called once each time through the main loop
729 ============
730 */
731 void S_Update(vec3_t origin, vec3_t forward, vec3_t left, vec3_t up)
732 {
733         int                     i, j;
734         int                     total;
735         channel_t       *ch;
736         channel_t       *combine;
737
738         if (!snd_initialized.integer || (snd_blocked > 0))
739                 return;
740
741         VectorCopy(origin, listener_vieworigin);
742         VectorCopy(forward, listener_viewforward);
743         VectorCopy(left, listener_viewleft);
744         VectorCopy(up, listener_viewup);
745
746 // update general area ambient sound sources
747         S_UpdateAmbientSounds ();
748
749         combine = NULL;
750
751 // update spatialization for static and dynamic sounds
752         ch = channels+NUM_AMBIENTS;
753         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
754         {
755                 if (!ch->sfx)
756                         continue;
757                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);         // respatialize channel
758                 if (!ch->leftvol && !ch->rightvol)
759                         continue;
760
761         // try to combine static sounds with a previous channel of the same
762         // sound effect so we don't mix five torches every frame
763
764                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
765                 {
766                 // see if it can just use the last one
767                         if (combine && combine->sfx == ch->sfx)
768                         {
769                                 combine->leftvol += ch->leftvol;
770                                 combine->rightvol += ch->rightvol;
771                                 ch->leftvol = ch->rightvol = 0;
772                                 continue;
773                         }
774                 // search for one
775                         combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
776                         for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
777                                 if (combine->sfx == ch->sfx)
778                                         break;
779
780                         if (j == total_channels)
781                                 combine = NULL;
782                         else
783                         {
784                                 if (combine != ch)
785                                 {
786                                         combine->leftvol += ch->leftvol;
787                                         combine->rightvol += ch->rightvol;
788                                         ch->leftvol = ch->rightvol = 0;
789                                 }
790                                 continue;
791                         }
792                 }
793         }
794
795 //
796 // debugging output
797 //
798         if (snd_show.integer)
799         {
800                 total = 0;
801                 ch = channels;
802                 for (i=0 ; i<total_channels; i++, ch++)
803                         if (ch->sfx && (ch->leftvol || ch->rightvol) )
804                                 total++;
805
806                 Con_Printf ("----(%i)----\n", total);
807         }
808
809 // mix some sound
810         S_Update_();
811 }
812
813 void GetSoundtime(void)
814 {
815         int             samplepos;
816         static  int             buffers;
817         static  int             oldsamplepos;
818         int             fullsamples;
819
820         fullsamples = shm->samples / shm->channels;
821
822 // it is possible to miscount buffers if it has wrapped twice between
823 // calls to S_Update.  Oh well.
824         samplepos = SNDDMA_GetDMAPos();
825
826         if (samplepos < oldsamplepos)
827         {
828                 buffers++;                                      // buffer wrapped
829
830                 if (paintedtime > 0x40000000)
831                 {       // time to chop things off to avoid 32 bit limits
832                         buffers = 0;
833                         paintedtime = fullsamples;
834                         S_StopAllSounds (true);
835                 }
836         }
837         oldsamplepos = samplepos;
838
839         soundtime = buffers*fullsamples + samplepos/shm->channels;
840 }
841
842 void IN_Accumulate (void);
843
844 void S_ExtraUpdate (void)
845 {
846
847 #ifdef _WIN32
848         IN_Accumulate ();
849 #endif
850
851         if (snd_noextraupdate.integer)
852                 return;         // don't pollute timings
853         S_Update_();
854 }
855
856 void S_Update_(void)
857 {
858         unsigned        endtime;
859         int                             samps;
860
861         if (!sound_started || (snd_blocked > 0))
862                 return;
863
864 // Updates DMA time
865         GetSoundtime();
866
867 // check to make sure that we haven't overshot
868         if (paintedtime < soundtime)
869                 paintedtime = soundtime;
870
871 // mix ahead of current position
872         endtime = soundtime + _snd_mixahead.value * shm->speed;
873         samps = shm->samples >> (shm->channels-1);
874         if (endtime > (unsigned int)(soundtime + samps))
875                 endtime = soundtime + samps;
876
877 #ifdef _WIN32
878 // if the buffer was lost or stopped, restore it and/or restart it
879         {
880                 DWORD   dwStatus;
881
882                 if (pDSBuf)
883                 {
884                         if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DD_OK)
885                                 Con_Printf ("Couldn't get sound buffer status\n");
886
887                         if (dwStatus & DSBSTATUS_BUFFERLOST)
888                                 pDSBuf->lpVtbl->Restore (pDSBuf);
889
890                         if (!(dwStatus & DSBSTATUS_PLAYING))
891                                 pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
892                 }
893         }
894 #endif
895
896         S_PaintChannels (endtime);
897
898         SNDDMA_Submit ();
899 }
900
901 /*
902 ===============================================================================
903
904 console functions
905
906 ===============================================================================
907 */
908
909 static void S_Play_Common(float fvol, float attenuation)
910 {
911         int     i;
912         char name[256];
913         sfx_t   *sfx;
914
915         i = 1;
916         while (i<Cmd_Argc())
917         {
918                 if (!strrchr(Cmd_Argv(i), '.'))
919                         snprintf(name, sizeof(name), "%s.wav", Cmd_Argv(i));
920                 else
921                         strlcpy(name, Cmd_Argv(i), sizeof(name));
922                 sfx = S_PrecacheSound(name, true);
923
924                 // If we need to get the volume from the command line
925                 if (fvol == -1.0f)
926                 {
927                         fvol = atof(Cmd_Argv(i+1));
928                         i += 2;
929                 }
930                 else
931                         i++;
932
933                 S_StartSound(-1, 0, sfx, listener_vieworigin, fvol, attenuation);
934         }
935 }
936
937 void S_Play(void)
938 {
939         S_Play_Common (1.0f, 1.0f);
940 }
941
942 void S_Play2(void)
943 {
944         S_Play_Common (1.0f, 0.0f);
945 }
946
947 void S_PlayVol(void)
948 {
949         S_Play_Common (-1.0f, 0.0f);
950 }
951
952 void S_SoundList(void)
953 {
954         int             i;
955         sfx_t   *sfx;
956         sfxcache_t      *sc;
957         int             size, total;
958
959         total = 0;
960         for (sfx=known_sfx, i=0 ; i<num_sfx ; i++, sfx++)
961         {
962                 sc = sfx->sfxcache;
963                 if (sc)
964                 {
965                         size = sc->length*sc->width*(sc->stereo+1);
966                         total += size;
967                         Con_Printf("%c(%2db) %6i : %s\n", sc->loopstart >= 0 ? 'L' : ' ',sc->width*8,  size, sfx->name);
968                 }
969         }
970         Con_Printf("Total resident: %i\n", total);
971 }
972
973
974 void S_LocalSound (char *sound)
975 {
976         sfx_t   *sfx;
977
978         if (!snd_initialized.integer || nosound.integer)
979                 return;
980
981         sfx = S_PrecacheSound (sound, true);
982         if (!sfx)
983         {
984                 Con_Printf ("S_LocalSound: can't precache %s\n", sound);
985                 return;
986         }
987         S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1);
988 }
989
990
991 void S_ClearPrecache (void)
992 {
993 }
994
995
996 void S_BeginPrecaching (void)
997 {
998 }
999
1000
1001 void S_EndPrecaching (void)
1002 {
1003 }
1004
1005
1006 #define RAWSAMPLESBUFFER 32768
1007 short s_rawsamplesbuffer[RAWSAMPLESBUFFER * 2];
1008 int s_rawsamplesbuffer_start;
1009 int s_rawsamplesbuffer_count;
1010
1011 void S_RawSamples_Enqueue(short *samples, unsigned int length)
1012 {
1013         int b2, b3;
1014         //Con_Printf("S_RawSamples_Enqueue: %i samples\n", length);
1015         if (s_rawsamplesbuffer_count + length > RAWSAMPLESBUFFER)
1016                 return;
1017         b2 = (s_rawsamplesbuffer_start + s_rawsamplesbuffer_count) % RAWSAMPLESBUFFER;
1018         if (b2 + length > RAWSAMPLESBUFFER)
1019         {
1020                 b3 = (b2 + length) % RAWSAMPLESBUFFER;
1021                 memcpy(s_rawsamplesbuffer + b2 * 2, samples, (RAWSAMPLESBUFFER - b2) * sizeof(short[2]));
1022                 memcpy(s_rawsamplesbuffer, samples + (RAWSAMPLESBUFFER - b2) * 2, b3 * sizeof(short[2]));
1023         }
1024         else
1025                 memcpy(s_rawsamplesbuffer + b2 * 2, samples, length * sizeof(short[2]));
1026         s_rawsamplesbuffer_count += length;
1027 }
1028
1029 void S_RawSamples_Dequeue(int *samples, unsigned int length)
1030 {
1031         int b1, b2, l;
1032         int i;
1033         short *in;
1034         int *out;
1035         int count;
1036         l = length;
1037         if (l > s_rawsamplesbuffer_count)
1038                 l = s_rawsamplesbuffer_count;
1039         b1 = (s_rawsamplesbuffer_start) % RAWSAMPLESBUFFER;
1040         if (b1 + l > RAWSAMPLESBUFFER)
1041         {
1042                 b2 = (b1 + l) % RAWSAMPLESBUFFER;
1043                 //memcpy(samples, s_rawsamplesbuffer + b1 * 2, (RAWSAMPLESBUFFER - b1) * sizeof(short[2]));
1044                 //memcpy(samples + (RAWSAMPLESBUFFER - b1) * 2, s_rawsamplesbuffer, b2 * sizeof(short[2]));
1045                 for (out = samples, in = s_rawsamplesbuffer + b1 * 2, count = (RAWSAMPLESBUFFER - b1) * 2, i = 0;i < count;i++)
1046                         out[i] = in[i];
1047                 for (out = samples + (RAWSAMPLESBUFFER - b1) * 2, in = s_rawsamplesbuffer, count = b2 * 2, i = 0;i < count;i++)
1048                         out[i] = in[i];
1049                 //Con_Printf("S_RawSamples_Dequeue: buffer wrap %i %i\n", (RAWSAMPLESBUFFER - b1), b2);
1050         }
1051         else
1052         {
1053                 //memcpy(samples, s_rawsamplesbuffer + b1 * 2, l * sizeof(short[2]));
1054                 for (out = samples, in = s_rawsamplesbuffer + b1 * 2, count = l * 2, i = 0;i < count;i++)
1055                         out[i] = in[i];
1056                 //Con_Printf("S_RawSamples_Dequeue: normal      %i\n", l);
1057         }
1058         if (l < (int)length)
1059         {
1060                 memset(samples + l * 2, 0, (length - l) * sizeof(int[2]));
1061                 //Con_Printf("S_RawSamples_Dequeue: padding with %i samples\n", length - l);
1062         }
1063         s_rawsamplesbuffer_start = (s_rawsamplesbuffer_start + l) % RAWSAMPLESBUFFER;
1064         s_rawsamplesbuffer_count -= l;
1065 }
1066
1067 void S_RawSamples_ClearQueue(void)
1068 {
1069         s_rawsamplesbuffer_count = 0;
1070         s_rawsamplesbuffer_start = 0;
1071 }
1072
1073 int S_RawSamples_QueueWantsMore(void)
1074 {
1075         if (shm != NULL && s_rawsamplesbuffer_count < min(shm->speed >> 1, RAWSAMPLESBUFFER >> 1))
1076                 return RAWSAMPLESBUFFER - s_rawsamplesbuffer_count;
1077         else
1078                 return 0;
1079 }
1080
1081 void S_ResampleBuffer16Stereo(short *input, int inputlength, short *output, int outputlength)
1082 {
1083         if (inputlength != outputlength)
1084         {
1085                 int i, position, stopposition, step;
1086                 short *in, *out;
1087                 step = (float) inputlength * 256.0f / (float) outputlength;
1088                 position = 0;
1089                 stopposition = (inputlength - 1) << 8;
1090                 out = output;
1091                 for (i = 0;i < outputlength && position < stopposition;i++, position += step)
1092                 {
1093                         in = input + ((position >> 8) << 1);
1094                         out[0] = (((in[1] - in[0]) * (position & 255)) >> 8) + in[0];
1095                         out[1] = (((in[3] - in[2]) * (position & 255)) >> 8) + in[2];
1096                         out += 2;
1097                 }
1098                 stopposition = inputlength << 8;
1099                 for (i = 0;i < outputlength && position < stopposition;i++, position += step)
1100                 {
1101                         in = input + ((position >> 8) << 1);
1102                         out[0] = in[0];
1103                         out[1] = in[2];
1104                         out += 2;
1105                 }
1106         }
1107         else
1108                 memcpy(output, input, inputlength * sizeof(short[2]));
1109 }
1110
1111 int S_RawSamples_SampleRate(void)
1112 {
1113         return shm != NULL ? shm->speed : 0;
1114 }
1115