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