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