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 cvar_t bgmvolume = {"bgmvolume", "1", true};
70 cvar_t volume = {"volume", "0.7", true};
72 cvar_t nosound = {"nosound", "0"};
73 cvar_t precache = {"precache", "1"};
74 //cvar_t loadas8bit = {"loadas8bit", "0"};
75 cvar_t bgmbuffer = {"bgmbuffer", "4096"};
76 cvar_t ambient_level = {"ambient_level", "0.3"};
77 cvar_t ambient_fade = {"ambient_fade", "100"};
78 cvar_t snd_noextraupdate = {"snd_noextraupdate", "0"};
79 cvar_t snd_show = {"snd_show", "0"};
80 cvar_t _snd_mixahead = {"_snd_mixahead", "0.1", true};
81 cvar_t snd_swapstereo = {"snd_swapstereo", "0", true};
84 // ====================================================================
85 // User-setable variables
86 // ====================================================================
90 // Fake dma is a synchronous faking of the DMA progress used for
91 // isolating performance in the renderer. The fakedma_updates is
92 // number of times S_Update() is called per second.
95 qboolean fakedma = false;
96 int fakedma_updates = 15;
99 void S_AmbientOff (void)
105 void S_AmbientOn (void)
111 void S_SoundInfo_f(void)
113 if (!sound_started || !shm)
115 Con_Printf ("sound system not started\n");
119 Con_Printf("%5d stereo\n", shm->channels - 1);
120 Con_Printf("%5d samples\n", shm->samples);
121 Con_Printf("%5d samplepos\n", shm->samplepos);
122 Con_Printf("%5d samplebits\n", shm->samplebits);
123 Con_Printf("%5d submission_chunk\n", shm->submission_chunk);
124 Con_Printf("%5d speed\n", shm->speed);
125 Con_Printf("0x%x dma buffer\n", shm->buffer);
126 Con_Printf("%5d total_channels\n", total_channels);
136 void S_Startup (void)
140 if (!snd_initialized)
150 Con_Printf("S_Startup: SNDDMA_Init failed.\n");
171 Con_Printf("\nSound Initialization\n");
173 if (COM_CheckParm("-nosound"))
176 if (COM_CheckParm("-simsound"))
179 Cmd_AddCommand("play", S_Play);
180 Cmd_AddCommand("play2", S_Play2);
181 Cmd_AddCommand("playvol", S_PlayVol);
182 Cmd_AddCommand("stopsound", S_StopAllSoundsC);
183 Cmd_AddCommand("soundlist", S_SoundList);
184 Cmd_AddCommand("soundinfo", S_SoundInfo_f);
186 Cvar_RegisterVariable(&nosound);
187 Cvar_RegisterVariable(&volume);
188 Cvar_RegisterVariable(&precache);
189 // Cvar_RegisterVariable(&loadas8bit);
190 Cvar_RegisterVariable(&bgmvolume);
191 Cvar_RegisterVariable(&bgmbuffer);
192 Cvar_RegisterVariable(&ambient_level);
193 Cvar_RegisterVariable(&ambient_fade);
194 Cvar_RegisterVariable(&snd_noextraupdate);
195 Cvar_RegisterVariable(&snd_show);
196 Cvar_RegisterVariable(&_snd_mixahead);
197 Cvar_RegisterVariable(&snd_swapstereo); // LordHavoc: for people with backwards sound wiring
200 if (host_parms.memsize < 0x800000)
202 Cvar_Set ("loadas8bit", "1");
203 Con_Printf ("loading all sounds as 8bit\n");
209 snd_initialized = true;
213 SND_InitScaletable ();
215 known_sfx = Hunk_AllocName (MAX_SFX*sizeof(sfx_t), "sfx_t");
218 // create a piece of DMA memory
222 shm = (void *) Hunk_AllocName(sizeof(*shm), "shm");
223 shm->splitbuffer = 0;
224 shm->samplebits = 16;
227 shm->samples = 32768;
229 shm->soundalive = true;
230 shm->gamealive = true;
231 shm->submission_chunk = 1;
232 shm->buffer = Hunk_AllocName(1<<16, "shmbuf");
238 Con_Printf ("Sound sampling rate: %i\n", shm->speed);
240 // provides a tick sound until washed clean
243 // shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging
245 ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav");
246 ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav");
248 S_StopAllSounds (true);
252 // =======================================================================
253 // Shutdown sound engine
254 // =======================================================================
256 void S_Shutdown(void)
275 // =======================================================================
277 // =======================================================================
285 sfx_t *S_FindName (char *name)
291 Host_Error ("S_FindName: NULL\n");
293 if (strlen(name) >= MAX_QPATH)
294 Host_Error ("Sound name too long: %s", name);
296 // see if already loaded
297 for (i=0 ; i < num_sfx ; i++)
298 if (!strcmp(known_sfx[i].name, name))
300 return &known_sfx[i];
303 if (num_sfx == MAX_SFX)
304 Sys_Error ("S_FindName: out of sfx_t");
307 strcpy (sfx->name, name);
321 void S_TouchSound (char *name)
328 sfx = S_FindName (name);
329 Cache_Check (&sfx->cache);
338 sfx_t *S_PrecacheSound (char *name)
342 if (!sound_started || nosound.value)
345 sfx = S_FindName (name);
355 //=============================================================================
362 channel_t *SND_PickChannel(int entnum, int entchannel)
368 // Check for replacement sound, or find the best one to replace
370 life_left = 0x7fffffff;
371 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
373 if (entchannel != 0 // channel 0 never overrides
374 && channels[ch_idx].entnum == entnum
375 && (channels[ch_idx].entchannel == entchannel || entchannel == -1) )
376 { // always override sound from same entity
377 first_to_die = ch_idx;
381 // don't let monster sounds override player sounds
382 if (channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && channels[ch_idx].sfx)
385 if (channels[ch_idx].end - paintedtime < life_left)
387 life_left = channels[ch_idx].end - paintedtime;
388 first_to_die = ch_idx;
392 if (first_to_die == -1)
395 if (channels[first_to_die].sfx)
396 channels[first_to_die].sfx = NULL;
398 return &channels[first_to_die];
406 void SND_Spatialize(channel_t *ch)
410 vec_t lscale, rscale, scale;
414 // anything coming from the view entity will always be full volume
415 // LordHavoc: make sounds with ATTN_NONE have no spatialization
416 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
418 ch->leftvol = ch->master_vol;
419 ch->rightvol = ch->master_vol;
423 // calculate stereo seperation and distance attenuation
426 VectorSubtract(ch->origin, listener_origin, source_vec);
428 dist = VectorNormalizeLength(source_vec) * ch->dist_mult;
430 dot = DotProduct(listener_right, source_vec);
432 if (shm->channels == 1)
443 // add in distance effect
444 scale = (1.0 - dist) * rscale;
445 ch->rightvol = (int) (ch->master_vol * scale);
446 if (ch->rightvol < 0)
449 scale = (1.0 - dist) * lscale;
450 ch->leftvol = (int) (ch->master_vol * scale);
456 // =======================================================================
457 // Start a sound effect
458 // =======================================================================
460 void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
462 channel_t *target_chan, *check;
479 // pick a channel to play on
480 target_chan = SND_PickChannel(entnum, entchannel);
485 memset (target_chan, 0, sizeof(*target_chan));
486 VectorCopy(origin, target_chan->origin);
487 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
488 target_chan->master_vol = vol;
489 target_chan->entnum = entnum;
490 target_chan->entchannel = entchannel;
491 SND_Spatialize(target_chan);
493 if (!target_chan->leftvol && !target_chan->rightvol)
494 return; // not audible at all
497 sc = S_LoadSound (sfx);
500 target_chan->sfx = NULL;
501 return; // couldn't load the sound's data
504 target_chan->sfx = sfx;
505 target_chan->pos = 0.0;
506 target_chan->end = paintedtime + sc->length;
508 // if an identical sound has also been started this frame, offset the pos
509 // a bit to keep it from just making the first one louder
510 check = &channels[NUM_AMBIENTS];
511 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
513 if (check == target_chan)
515 if (check->sfx == sfx && !check->pos)
517 // LordHavoc: fixed skip calculations
518 skip = 0.1 * shm->speed;
519 if (skip > sc->length)
522 skip = rand() % skip;
523 target_chan->pos += skip;
524 target_chan->end -= skip;
531 void S_StopSound(int entnum, int entchannel)
535 for (i=0 ; i<MAX_DYNAMIC_CHANNELS ; i++)
537 if (channels[i].entnum == entnum
538 && channels[i].entchannel == entchannel)
541 channels[i].sfx = NULL;
547 void S_StopAllSounds(qboolean clear)
554 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
556 for (i=0 ; i<MAX_CHANNELS ; i++)
558 channels[i].sfx = NULL;
560 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
566 void S_StopAllSoundsC (void)
568 S_StopAllSounds (true);
571 void S_ClearBuffer (void)
576 if (!sound_started || !shm || (!shm->buffer && !pDSBuf))
578 if (!sound_started || !shm || !shm->buffer)
582 if (shm->samplebits == 8)
597 while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &pData, &dwSize, NULL, NULL, 0)) != DS_OK)
599 if (hresult != DSERR_BUFFERLOST)
601 Con_Printf ("S_ClearBuffer: DS::Lock Sound Buffer Failed\n");
608 Con_Printf ("S_ClearBuffer: DS: couldn't restore buffer\n");
614 memset(pData, clear, shm->samples * shm->samplebits/8);
616 pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0);
622 memset(shm->buffer, clear, shm->samples * shm->samplebits/8);
632 void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation)
640 if (total_channels == MAX_CHANNELS)
642 Con_Printf ("total_channels == MAX_CHANNELS\n");
646 ss = &channels[total_channels];
649 sc = S_LoadSound (sfx);
653 if (sc->loopstart == -1)
655 Con_Printf ("Sound %s not looped\n", sfx->name);
660 VectorCopy (origin, ss->origin);
661 ss->master_vol = vol;
662 ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist;
663 ss->end = paintedtime + sc->length;
669 //=============================================================================
673 S_UpdateAmbientSounds
676 void S_UpdateAmbientSounds (void)
686 // calc ambient sound levels
690 l = Mod_PointInLeaf (listener_origin, cl.worldmodel);
691 if (!l || !ambient_level.value)
693 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
694 channels[ambient_channel].sfx = NULL;
698 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
700 chan = &channels[ambient_channel];
701 chan->sfx = ambient_sfx[ambient_channel];
703 vol = ambient_level.value * l->ambient_sound_level[ambient_channel];
707 // don't adjust volume too fast
708 if (chan->master_vol < vol)
710 chan->master_vol += host_realframetime * ambient_fade.value;
711 if (chan->master_vol > vol)
712 chan->master_vol = vol;
714 else if (chan->master_vol > vol)
716 chan->master_vol -= host_realframetime * ambient_fade.value;
717 if (chan->master_vol < vol)
718 chan->master_vol = vol;
721 chan->leftvol = chan->rightvol = chan->master_vol;
730 Called once each time through the main loop
733 void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up)
740 if (!sound_started || (snd_blocked > 0))
743 VectorCopy(origin, listener_origin);
744 VectorCopy(forward, listener_forward);
745 VectorCopy(right, listener_right);
746 VectorCopy(up, listener_up);
748 // update general area ambient sound sources
749 S_UpdateAmbientSounds ();
753 // update spatialization for static and dynamic sounds
754 ch = channels+NUM_AMBIENTS;
755 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
759 SND_Spatialize(ch); // respatialize channel
760 if (!ch->leftvol && !ch->rightvol)
763 // try to combine static sounds with a previous channel of the same
764 // sound effect so we don't mix five torches every frame
766 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
768 // see if it can just use the last one
769 if (combine && combine->sfx == ch->sfx)
771 combine->leftvol += ch->leftvol;
772 combine->rightvol += ch->rightvol;
773 ch->leftvol = ch->rightvol = 0;
777 combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
778 for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
779 if (combine->sfx == ch->sfx)
782 if (j == total_channels)
790 combine->leftvol += ch->leftvol;
791 combine->rightvol += ch->rightvol;
792 ch->leftvol = ch->rightvol = 0;
808 for (i=0 ; i<total_channels; i++, ch++)
809 if (ch->sfx && (ch->leftvol || ch->rightvol) )
811 //Con_Printf ("%3i %3i %s\n", ch->leftvol, ch->rightvol, ch->sfx->name);
815 Con_Printf ("----(%i)----\n", total);
822 void GetSoundtime(void)
826 static int oldsamplepos;
829 fullsamples = shm->samples / shm->channels;
831 // it is possible to miscount buffers if it has wrapped twice between
832 // calls to S_Update. Oh well.
834 soundtime = SNDDMA_GetSamples();
836 samplepos = SNDDMA_GetDMAPos();
839 if (samplepos < oldsamplepos)
841 buffers++; // buffer wrapped
843 if (paintedtime > 0x40000000)
844 { // time to chop things off to avoid 32 bit limits
846 paintedtime = fullsamples;
847 S_StopAllSounds (true);
850 oldsamplepos = samplepos;
852 soundtime = buffers*fullsamples + samplepos/shm->channels;
856 void IN_Accumulate (void);
858 void S_ExtraUpdate (void)
865 if (snd_noextraupdate.value)
866 return; // don't pollute timings
875 if (!sound_started || (snd_blocked > 0))
881 // check to make sure that we haven't overshot
882 if (paintedtime < soundtime)
884 //Con_Printf ("S_Update_ : overflow\n");
885 paintedtime = soundtime;
888 // mix ahead of current position
889 endtime = soundtime + _snd_mixahead.value * shm->speed;
890 samps = shm->samples >> (shm->channels-1);
891 if (endtime - soundtime > samps)
892 endtime = soundtime + samps;
895 // if the buffer was lost or stopped, restore it and/or restart it
901 if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DD_OK)
902 Con_Printf ("Couldn't get sound buffer status\n");
904 if (dwStatus & DSBSTATUS_BUFFERLOST)
905 pDSBuf->lpVtbl->Restore (pDSBuf);
907 if (!(dwStatus & DSBSTATUS_PLAYING))
908 pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
913 S_PaintChannels (endtime);
919 ===============================================================================
923 ===============================================================================
936 if (!strrchr(Cmd_Argv(i), '.'))
938 strcpy(name, Cmd_Argv(i));
939 strcat(name, ".wav");
942 strcpy(name, Cmd_Argv(i));
943 sfx = S_PrecacheSound(name);
944 S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 1.0);
959 if (!strrchr(Cmd_Argv(i), '.'))
961 strcpy(name, Cmd_Argv(i));
962 strcat(name, ".wav");
965 strcpy(name, Cmd_Argv(i));
966 sfx = S_PrecacheSound(name);
967 S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 0.0);
983 if (!strrchr(Cmd_Argv(i), '.'))
985 strcpy(name, Cmd_Argv(i));
986 strcat(name, ".wav");
989 strcpy(name, Cmd_Argv(i));
990 sfx = S_PrecacheSound(name);
991 vol = atof(Cmd_Argv(i+1));
992 S_StartSound(hash++, 0, sfx, listener_origin, vol, 1.0);
997 void S_SoundList(void)
1005 for (sfx=known_sfx, i=0 ; i<num_sfx ; i++, sfx++)
1007 sc = Cache_Check (&sfx->cache);
1010 size = sc->length*sc->width*(sc->stereo+1);
1012 if (sc->loopstart >= 0)
1016 Con_Printf("(%2db) %6i : %s\n",sc->width*8, size, sfx->name);
1018 Con_Printf ("Total resident: %i\n", total);
1022 void S_LocalSound (char *sound)
1031 sfx = S_PrecacheSound (sound);
1034 Con_Printf ("S_LocalSound: can't cache %s\n", sound);
1037 S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1);
1041 void S_ClearPrecache (void)
1046 void S_BeginPrecaching (void)
1051 void S_EndPrecaching (void)