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