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