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