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