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