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