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