2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // snd_dma.c -- main control for any streaming sound output device
30 void S_SoundList(void);
32 void S_StopAllSounds(qboolean clear);
33 void S_StopAllSoundsC(void);
35 // =======================================================================
36 // Internal sound data & structures
37 // =======================================================================
39 channel_t channels[MAX_CHANNELS];
43 static qboolean snd_ambient = 1;
44 qboolean snd_initialized = false;
46 // pointer should go away
47 volatile dma_t *shm = 0;
50 vec3_t listener_origin;
51 vec3_t listener_forward;
52 vec3_t listener_right;
54 vec_t sound_nominal_clip_dist=1000.0;
56 int soundtime; // sample PAIRS
57 int paintedtime; // sample PAIRS
60 //LordHavoc: increased the client sound limit from 512 to 4096 for the Nehahra movie
62 sfx_t *known_sfx; // hunk allocated [MAX_SFX]
65 sfx_t *ambient_sfx[NUM_AMBIENTS];
69 // FIXME: make bgmvolume/volume always be registered for sake of config saving, and add check for whether sound is enabled to menu
70 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
71 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
73 cvar_t nosound = {0, "nosound", "0"};
74 cvar_t precache = {0, "precache", "1"};
75 //cvar_t loadas8bit = {0, "loadas8bit", "0"};
76 cvar_t bgmbuffer = {0, "bgmbuffer", "4096"};
77 cvar_t ambient_level = {0, "ambient_level", "0.3"};
78 cvar_t ambient_fade = {0, "ambient_fade", "100"};
79 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0"};
80 cvar_t snd_show = {0, "snd_show", "0"};
81 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1"};
82 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0"};
85 // ====================================================================
86 // User-setable variables
87 // ====================================================================
91 // Fake dma is a synchronous faking of the DMA progress used for
92 // isolating performance in the renderer. The fakedma_updates is
93 // number of times S_Update() is called per second.
96 qboolean fakedma = false;
97 int fakedma_updates = 15;
100 void S_AmbientOff (void)
106 void S_AmbientOn (void)
112 void S_SoundInfo_f(void)
114 if (!sound_started || !shm)
116 Con_Printf ("sound system not started\n");
120 Con_Printf("%5d stereo\n", shm->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->samplebits);
124 Con_Printf("%5d submission_chunk\n", shm->submission_chunk);
125 Con_Printf("%5d speed\n", shm->speed);
126 Con_Printf("0x%x dma buffer\n", shm->buffer);
127 Con_Printf("%5d total_channels\n", total_channels);
137 void S_Startup (void)
141 if (!snd_initialized)
151 Con_Printf("S_Startup: SNDDMA_Init failed.\n");
172 Con_Printf("\nSound Initialization\n");
174 if (COM_CheckParm("-nosound"))
177 if (COM_CheckParm("-simsound"))
180 Cmd_AddCommand("play", S_Play);
181 Cmd_AddCommand("play2", S_Play2);
182 Cmd_AddCommand("playvol", S_PlayVol);
183 Cmd_AddCommand("stopsound", S_StopAllSoundsC);
184 Cmd_AddCommand("soundlist", S_SoundList);
185 Cmd_AddCommand("soundinfo", S_SoundInfo_f);
187 Cvar_RegisterVariable(&nosound);
188 Cvar_RegisterVariable(&volume);
189 Cvar_RegisterVariable(&precache);
190 // Cvar_RegisterVariable(&loadas8bit);
191 Cvar_RegisterVariable(&bgmvolume);
192 Cvar_RegisterVariable(&bgmbuffer);
193 Cvar_RegisterVariable(&ambient_level);
194 Cvar_RegisterVariable(&ambient_fade);
195 Cvar_RegisterVariable(&snd_noextraupdate);
196 Cvar_RegisterVariable(&snd_show);
197 Cvar_RegisterVariable(&_snd_mixahead);
198 Cvar_RegisterVariable(&snd_swapstereo); // LordHavoc: for people with backwards sound wiring
201 if (host_parms.memsize < 0x800000)
203 Cvar_Set ("loadas8bit", "1");
204 Con_Printf ("loading all sounds as 8bit\n");
210 snd_initialized = true;
214 SND_InitScaletable ();
216 known_sfx = Hunk_AllocName (MAX_SFX*sizeof(sfx_t), "sfx_t");
219 // create a piece of DMA memory
223 shm = (void *) Hunk_AllocName(sizeof(*shm), "shm");
224 shm->splitbuffer = 0;
225 shm->samplebits = 16;
228 shm->samples = 32768;
230 shm->soundalive = true;
231 shm->gamealive = true;
232 shm->submission_chunk = 1;
233 shm->buffer = Hunk_AllocName(1<<16, "shmbuf");
239 Con_Printf ("Sound sampling rate: %i\n", shm->speed);
241 // provides a tick sound until washed clean
244 // shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging
246 ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav");
247 ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav");
249 S_StopAllSounds (true);
253 // =======================================================================
254 // Shutdown sound engine
255 // =======================================================================
257 void S_Shutdown(void)
276 // =======================================================================
278 // =======================================================================
286 sfx_t *S_FindName (char *name)
292 Host_Error ("S_FindName: NULL\n");
294 if (strlen(name) >= MAX_QPATH)
295 Host_Error ("Sound name too long: %s", name);
297 // see if already loaded
298 for (i=0 ; i < num_sfx ; i++)
299 if (!strcmp(known_sfx[i].name, name))
301 return &known_sfx[i];
304 if (num_sfx == MAX_SFX)
305 Sys_Error ("S_FindName: out of sfx_t");
308 strcpy (sfx->name, name);
322 void S_TouchSound (char *name)
329 sfx = S_FindName (name);
330 Cache_Check (&sfx->cache);
339 sfx_t *S_PrecacheSound (char *name)
343 if (!sound_started || nosound.value)
346 sfx = S_FindName (name);
356 //=============================================================================
363 channel_t *SND_PickChannel(int entnum, int entchannel)
369 // Check for replacement sound, or find the best one to replace
371 life_left = 0x7fffffff;
372 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
374 if (entchannel != 0 // channel 0 never overrides
375 && channels[ch_idx].entnum == entnum
376 && (channels[ch_idx].entchannel == entchannel || entchannel == -1) )
377 { // always override sound from same entity
378 first_to_die = ch_idx;
382 // don't let monster sounds override player sounds
383 if (channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && channels[ch_idx].sfx)
386 if (channels[ch_idx].end - paintedtime < life_left)
388 life_left = channels[ch_idx].end - paintedtime;
389 first_to_die = ch_idx;
393 if (first_to_die == -1)
396 if (channels[first_to_die].sfx)
397 channels[first_to_die].sfx = NULL;
399 return &channels[first_to_die];
407 void SND_Spatialize(channel_t *ch)
411 vec_t lscale, rscale, scale;
415 // anything coming from the view entity will always be full volume
416 // LordHavoc: make sounds with ATTN_NONE have no spatialization
417 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
419 ch->leftvol = ch->master_vol;
420 ch->rightvol = ch->master_vol;
424 // calculate stereo seperation and distance attenuation
427 VectorSubtract(ch->origin, listener_origin, source_vec);
429 dist = VectorNormalizeLength(source_vec) * ch->dist_mult;
431 dot = DotProduct(listener_right, source_vec);
433 if (shm->channels == 1)
444 // add in distance effect
445 scale = (1.0 - dist) * rscale;
446 ch->rightvol = (int) (ch->master_vol * scale);
447 if (ch->rightvol < 0)
450 scale = (1.0 - dist) * lscale;
451 ch->leftvol = (int) (ch->master_vol * scale);
457 // =======================================================================
458 // Start a sound effect
459 // =======================================================================
461 void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
463 channel_t *target_chan, *check;
480 // pick a channel to play on
481 target_chan = SND_PickChannel(entnum, entchannel);
486 memset (target_chan, 0, sizeof(*target_chan));
487 VectorCopy(origin, target_chan->origin);
488 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
489 target_chan->master_vol = vol;
490 target_chan->entnum = entnum;
491 target_chan->entchannel = entchannel;
492 SND_Spatialize(target_chan);
494 if (!target_chan->leftvol && !target_chan->rightvol)
495 return; // not audible at all
498 sc = S_LoadSound (sfx);
501 target_chan->sfx = NULL;
502 return; // couldn't load the sound's data
505 target_chan->sfx = sfx;
506 target_chan->pos = 0.0;
507 target_chan->end = paintedtime + sc->length;
509 // if an identical sound has also been started this frame, offset the pos
510 // a bit to keep it from just making the first one louder
511 check = &channels[NUM_AMBIENTS];
512 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
514 if (check == target_chan)
516 if (check->sfx == sfx && !check->pos)
518 // LordHavoc: fixed skip calculations
519 skip = 0.1 * shm->speed;
520 if (skip > sc->length)
523 skip = rand() % skip;
524 target_chan->pos += skip;
525 target_chan->end -= skip;
532 void S_StopSound(int entnum, int entchannel)
536 for (i=0 ; i<MAX_DYNAMIC_CHANNELS ; i++)
538 if (channels[i].entnum == entnum
539 && channels[i].entchannel == entchannel)
542 channels[i].sfx = NULL;
548 void S_StopAllSounds(qboolean clear)
555 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
557 for (i=0 ; i<MAX_CHANNELS ; i++)
559 channels[i].sfx = NULL;
561 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
567 void S_StopAllSoundsC (void)
569 S_StopAllSounds (true);
572 void S_ClearBuffer (void)
577 if (!sound_started || !shm || (!shm->buffer && !pDSBuf))
579 if (!sound_started || !shm || !shm->buffer)
583 if (shm->samplebits == 8)
598 while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &pData, &dwSize, NULL, NULL, 0)) != DS_OK)
600 if (hresult != DSERR_BUFFERLOST)
602 Con_Printf ("S_ClearBuffer: DS::Lock Sound Buffer Failed\n");
609 Con_Printf ("S_ClearBuffer: DS: couldn't restore buffer\n");
615 memset(pData, clear, shm->samples * shm->samplebits/8);
617 pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0);
623 memset(shm->buffer, clear, shm->samples * shm->samplebits/8);
633 void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation)
641 if (total_channels == MAX_CHANNELS)
643 Con_Printf ("total_channels == MAX_CHANNELS\n");
647 ss = &channels[total_channels];
650 sc = S_LoadSound (sfx);
654 if (sc->loopstart == -1)
656 Con_Printf ("Sound %s not looped\n", sfx->name);
661 VectorCopy (origin, ss->origin);
662 ss->master_vol = vol;
663 ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist;
664 ss->end = paintedtime + sc->length;
670 //=============================================================================
674 S_UpdateAmbientSounds
677 void S_UpdateAmbientSounds (void)
684 // LordHavoc: kill ambient sounds until proven otherwise
685 for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
686 channels[ambient_channel].sfx = NULL;
688 if (!snd_ambient || !cl.worldmodel || ambient_level.value <= 0)
691 l = Mod_PointInLeaf (listener_origin, cl.worldmodel);
695 // calc ambient sound levels
696 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
698 chan = &channels[ambient_channel];
699 chan->sfx = ambient_sfx[ambient_channel];
701 vol = ambient_level.value * l->ambient_sound_level[ambient_channel];
705 // don't adjust volume too fast
706 if (chan->master_vol < vol)
708 chan->master_vol += host_realframetime * ambient_fade.value;
709 if (chan->master_vol > vol)
710 chan->master_vol = vol;
712 else if (chan->master_vol > vol)
714 chan->master_vol -= host_realframetime * ambient_fade.value;
715 if (chan->master_vol < vol)
716 chan->master_vol = vol;
719 chan->leftvol = chan->rightvol = chan->master_vol;
728 Called once each time through the main loop
731 void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up)
738 if (!sound_started || (snd_blocked > 0))
741 VectorCopy(origin, listener_origin);
742 VectorCopy(forward, listener_forward);
743 VectorCopy(right, listener_right);
744 VectorCopy(up, listener_up);
746 // update general area ambient sound sources
747 S_UpdateAmbientSounds ();
751 // update spatialization for static and dynamic sounds
752 ch = channels+NUM_AMBIENTS;
753 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
757 SND_Spatialize(ch); // respatialize channel
758 if (!ch->leftvol && !ch->rightvol)
761 // try to combine static sounds with a previous channel of the same
762 // sound effect so we don't mix five torches every frame
764 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
766 // see if it can just use the last one
767 if (combine && combine->sfx == ch->sfx)
769 combine->leftvol += ch->leftvol;
770 combine->rightvol += ch->rightvol;
771 ch->leftvol = ch->rightvol = 0;
775 combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
776 for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
777 if (combine->sfx == ch->sfx)
780 if (j == total_channels)
788 combine->leftvol += ch->leftvol;
789 combine->rightvol += ch->rightvol;
790 ch->leftvol = ch->rightvol = 0;
806 for (i=0 ; i<total_channels; i++, ch++)
807 if (ch->sfx && (ch->leftvol || ch->rightvol) )
809 //Con_Printf ("%3i %3i %s\n", ch->leftvol, ch->rightvol, ch->sfx->name);
813 Con_Printf ("----(%i)----\n", total);
820 void GetSoundtime(void)
824 static int oldsamplepos;
827 fullsamples = shm->samples / shm->channels;
829 // it is possible to miscount buffers if it has wrapped twice between
830 // calls to S_Update. Oh well.
832 soundtime = SNDDMA_GetSamples();
834 samplepos = SNDDMA_GetDMAPos();
837 if (samplepos < oldsamplepos)
839 buffers++; // buffer wrapped
841 if (paintedtime > 0x40000000)
842 { // time to chop things off to avoid 32 bit limits
844 paintedtime = fullsamples;
845 S_StopAllSounds (true);
848 oldsamplepos = samplepos;
850 soundtime = buffers*fullsamples + samplepos/shm->channels;
854 void IN_Accumulate (void);
856 void S_ExtraUpdate (void)
863 if (snd_noextraupdate.value)
864 return; // don't pollute timings
873 if (!sound_started || (snd_blocked > 0))
879 // check to make sure that we haven't overshot
880 if (paintedtime < soundtime)
882 //Con_Printf ("S_Update_ : overflow\n");
883 paintedtime = soundtime;
886 // mix ahead of current position
887 endtime = soundtime + _snd_mixahead.value * shm->speed;
888 samps = shm->samples >> (shm->channels-1);
889 if (endtime - soundtime > samps)
890 endtime = soundtime + samps;
893 // if the buffer was lost or stopped, restore it and/or restart it
899 if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DD_OK)
900 Con_Printf ("Couldn't get sound buffer status\n");
902 if (dwStatus & DSBSTATUS_BUFFERLOST)
903 pDSBuf->lpVtbl->Restore (pDSBuf);
905 if (!(dwStatus & DSBSTATUS_PLAYING))
906 pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
911 S_PaintChannels (endtime);
917 ===============================================================================
921 ===============================================================================
934 if (!strrchr(Cmd_Argv(i), '.'))
936 strcpy(name, Cmd_Argv(i));
937 strcat(name, ".wav");
940 strcpy(name, Cmd_Argv(i));
941 sfx = S_PrecacheSound(name);
942 S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 1.0);
957 if (!strrchr(Cmd_Argv(i), '.'))
959 strcpy(name, Cmd_Argv(i));
960 strcat(name, ".wav");
963 strcpy(name, Cmd_Argv(i));
964 sfx = S_PrecacheSound(name);
965 S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 0.0);
981 if (!strrchr(Cmd_Argv(i), '.'))
983 strcpy(name, Cmd_Argv(i));
984 strcat(name, ".wav");
987 strcpy(name, Cmd_Argv(i));
988 sfx = S_PrecacheSound(name);
989 vol = atof(Cmd_Argv(i+1));
990 S_StartSound(hash++, 0, sfx, listener_origin, vol, 1.0);
995 void S_SoundList(void)
1003 for (sfx=known_sfx, i=0 ; i<num_sfx ; i++, sfx++)
1005 sc = Cache_Check (&sfx->cache);
1008 size = sc->length*sc->width*(sc->stereo+1);
1010 if (sc->loopstart >= 0)
1014 Con_Printf("(%2db) %6i : %s\n",sc->width*8, size, sfx->name);
1016 Con_Printf ("Total resident: %i\n", total);
1020 void S_LocalSound (char *sound)
1029 sfx = S_PrecacheSound (sound);
1032 Con_Printf ("S_LocalSound: can't cache %s\n", sound);
1035 S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1);
1039 void S_ClearPrecache (void)
1044 void S_BeginPrecaching (void)
1049 void S_EndPrecaching (void)