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