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
31 void S_SoundList(void);
33 void S_StopAllSounds(qboolean clear);
34 void S_StopAllSoundsC(void);
36 // =======================================================================
37 // Internal sound data & structures
38 // =======================================================================
40 channel_t channels[MAX_CHANNELS];
44 static qboolean snd_ambient = 1;
45 qboolean snd_initialized = false;
47 // pointer should go away
48 volatile dma_t *shm = 0;
51 vec3_t listener_origin;
52 vec3_t listener_forward;
53 vec3_t listener_right;
55 vec_t sound_nominal_clip_dist=1000.0;
56 mempool_t *snd_mempool;
63 //LordHavoc: increased the client sound limit from 512 to 4096 for the Nehahra movie
65 sfx_t *known_sfx; // allocated [MAX_SFX]
68 sfx_t *ambient_sfx[NUM_AMBIENTS];
70 int sound_started = 0;
72 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
73 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
75 cvar_t nosound = {0, "nosound", "0"};
76 cvar_t precache = {0, "precache", "1"};
77 cvar_t bgmbuffer = {0, "bgmbuffer", "4096"};
78 cvar_t ambient_level = {0, "ambient_level", "0.3"};
79 cvar_t ambient_fade = {0, "ambient_fade", "100"};
80 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0"};
81 cvar_t snd_show = {0, "snd_show", "0"};
82 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1"};
83 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0"};
86 // ====================================================================
87 // User-setable variables
88 // ====================================================================
92 // Fake dma is a synchronous faking of the DMA progress used for
93 // isolating performance in the renderer. The fakedma_updates is
94 // number of times S_Update() is called per second.
97 qboolean fakedma = false;
98 int fakedma_updates = 15;
101 void S_AmbientOff (void)
107 void S_AmbientOn (void)
113 void S_SoundInfo_f(void)
115 if (!sound_started || !shm)
117 Con_Printf ("sound system not started\n");
121 Con_Printf("%5d stereo\n", shm->channels - 1);
122 Con_Printf("%5d samples\n", shm->samples);
123 Con_Printf("%5d samplepos\n", shm->samplepos);
124 Con_Printf("%5d samplebits\n", shm->samplebits);
125 Con_Printf("%5d submission_chunk\n", shm->submission_chunk);
126 Con_Printf("%5d speed\n", shm->speed);
127 Con_Printf("0x%x dma buffer\n", shm->buffer);
128 Con_Printf("%5d total_channels\n", total_channels);
137 void S_Startup (void)
141 if (!snd_initialized)
150 Con_Printf("S_Startup: SNDDMA_Init failed.\n");
166 Con_Printf("\nSound Initialization\n");
168 S_RawSamples_ClearQueue();
170 Cvar_RegisterVariable(&volume);
171 Cvar_RegisterVariable(&bgmvolume);
173 if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
176 snd_mempool = Mem_AllocPool("sound");
178 if (COM_CheckParm("-simsound"))
181 Cmd_AddCommand("play", S_Play);
182 Cmd_AddCommand("play2", S_Play2);
183 Cmd_AddCommand("playvol", S_PlayVol);
184 Cmd_AddCommand("stopsound", S_StopAllSoundsC);
185 Cmd_AddCommand("soundlist", S_SoundList);
186 Cmd_AddCommand("soundinfo", S_SoundInfo_f);
188 Cvar_RegisterVariable(&nosound);
189 Cvar_RegisterVariable(&precache);
190 Cvar_RegisterVariable(&bgmbuffer);
191 Cvar_RegisterVariable(&ambient_level);
192 Cvar_RegisterVariable(&ambient_fade);
193 Cvar_RegisterVariable(&snd_noextraupdate);
194 Cvar_RegisterVariable(&snd_show);
195 Cvar_RegisterVariable(&_snd_mixahead);
196 Cvar_RegisterVariable(&snd_swapstereo); // LordHavoc: for people with backwards sound wiring
198 snd_initialized = true;
200 known_sfx = Mem_Alloc(snd_mempool, MAX_SFX*sizeof(sfx_t));
205 SND_InitScaletable ();
207 // create a piece of DMA memory
211 shm = (void *) Mem_Alloc(snd_mempool, sizeof(*shm));
212 shm->splitbuffer = 0;
213 shm->samplebits = 16;
216 shm->samples = 32768;
218 shm->soundalive = true;
219 shm->gamealive = true;
220 shm->submission_chunk = 1;
221 shm->buffer = Mem_Alloc(snd_mempool, shm->channels * shm->samples * (shm->samplebits / 8));
227 Con_Printf ("Sound sampling rate: %i\n", shm->speed);
229 // provides a tick sound until washed clean
231 ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav", false);
232 ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav", false);
234 S_StopAllSounds (true);
238 // =======================================================================
239 // Shutdown sound engine
240 // =======================================================================
242 void S_Shutdown(void)
258 // =======================================================================
260 // =======================================================================
268 sfx_t *S_FindName (char *name)
274 Host_Error ("S_FindName: NULL\n");
276 if (strlen(name) >= MAX_QPATH)
277 Host_Error ("Sound name too long: %s", name);
279 // see if already loaded
280 for (i = 0;i < num_sfx;i++)
281 if (!strcmp(known_sfx[i].name, name))
282 return &known_sfx[i];
284 if (num_sfx == MAX_SFX)
285 Sys_Error ("S_FindName: out of sfx_t");
288 memset(sfx, 0, sizeof(*sfx));
289 strcpy (sfx->name, name);
303 void S_TouchSound (char *name)
310 sfx = S_FindName (name);
319 sfx_t *S_PrecacheSound (char *name, int complain)
323 if (!sound_started || nosound.integer)
326 sfx = S_FindName (name);
329 if (precache.integer)
330 S_LoadSound (sfx, complain);
336 //=============================================================================
343 channel_t *SND_PickChannel(int entnum, int entchannel)
349 // Check for replacement sound, or find the best one to replace
351 life_left = 0x7fffffff;
352 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
354 if (entchannel != 0 // channel 0 never overrides
355 && channels[ch_idx].entnum == entnum
356 && (channels[ch_idx].entchannel == entchannel || entchannel == -1) )
357 { // always override sound from same entity
358 first_to_die = ch_idx;
362 // don't let monster sounds override player sounds
363 if (channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && channels[ch_idx].sfx)
366 if (channels[ch_idx].end - paintedtime < life_left)
368 life_left = channels[ch_idx].end - paintedtime;
369 first_to_die = ch_idx;
373 if (first_to_die == -1)
376 if (channels[first_to_die].sfx)
377 channels[first_to_die].sfx = NULL;
379 return &channels[first_to_die];
387 void SND_Spatialize(channel_t *ch)
391 vec_t lscale, rscale, scale;
395 // anything coming from the view entity will always be full volume
396 // LordHavoc: make sounds with ATTN_NONE have no spatialization
397 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
399 ch->leftvol = ch->master_vol;
400 ch->rightvol = ch->master_vol;
404 // calculate stereo seperation and distance attenuation
407 VectorSubtract(ch->origin, listener_origin, source_vec);
409 dist = VectorNormalizeLength(source_vec) * ch->dist_mult;
411 dot = DotProduct(listener_right, source_vec);
413 if (shm->channels == 1)
424 // add in distance effect
425 scale = (1.0 - dist) * rscale;
426 ch->rightvol = (int) (ch->master_vol * scale);
427 if (ch->rightvol < 0)
430 scale = (1.0 - dist) * lscale;
431 ch->leftvol = (int) (ch->master_vol * scale);
437 // =======================================================================
438 // Start a sound effect
439 // =======================================================================
441 void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
443 channel_t *target_chan, *check;
460 // pick a channel to play on
461 target_chan = SND_PickChannel(entnum, entchannel);
466 memset (target_chan, 0, sizeof(*target_chan));
467 VectorCopy(origin, target_chan->origin);
468 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
469 target_chan->master_vol = vol;
470 target_chan->entnum = entnum;
471 target_chan->entchannel = entchannel;
472 SND_Spatialize(target_chan);
474 if (!target_chan->leftvol && !target_chan->rightvol)
475 return; // not audible at all
478 sc = S_LoadSound (sfx, true);
481 target_chan->sfx = NULL;
482 return; // couldn't load the sound's data
485 target_chan->sfx = sfx;
486 target_chan->pos = 0.0;
487 target_chan->end = paintedtime + sc->length;
489 // if an identical sound has also been started this frame, offset the pos
490 // a bit to keep it from just making the first one louder
491 check = &channels[NUM_AMBIENTS];
492 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
494 if (check == target_chan)
496 if (check->sfx == sfx && !check->pos)
498 // LordHavoc: fixed skip calculations
499 skip = 0.1 * shm->speed;
500 if (skip > sc->length)
503 skip = rand() % skip;
504 target_chan->pos += skip;
505 target_chan->end -= skip;
512 void S_StopSound(int entnum, int entchannel)
516 for (i=0 ; i<MAX_DYNAMIC_CHANNELS ; i++)
518 if (channels[i].entnum == entnum
519 && channels[i].entchannel == entchannel)
522 channels[i].sfx = NULL;
528 void S_StopAllSounds(qboolean clear)
535 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
537 for (i=0 ; i<MAX_CHANNELS ; i++)
539 channels[i].sfx = NULL;
541 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
547 void S_StopAllSoundsC (void)
549 S_StopAllSounds (true);
552 void S_ClearBuffer (void)
557 if (!sound_started || !shm || (!shm->buffer && !pDSBuf))
559 if (!sound_started || !shm || !shm->buffer)
563 if (shm->samplebits == 8)
578 while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &pData, &dwSize, NULL, NULL, 0)) != DS_OK)
580 if (hresult != DSERR_BUFFERLOST)
582 Con_Printf ("S_ClearBuffer: DS::Lock Sound Buffer Failed\n");
589 Con_Printf ("S_ClearBuffer: DS: couldn't restore buffer\n");
595 memset(pData, clear, shm->samples * shm->samplebits/8);
597 pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0);
603 int setsize = shm->samples * shm->samplebits / 8;
604 char *buf = shm->buffer;
609 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
610 // reads the memory area before writing to it causing a seg fault
611 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
612 // memset(shm->buffer, clear, shm->samples * shm->samplebits/8);
622 void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation)
630 if (total_channels == MAX_CHANNELS)
632 Con_Printf ("total_channels == MAX_CHANNELS\n");
636 ss = &channels[total_channels];
639 sc = S_LoadSound (sfx, true);
643 if (sc->loopstart == -1)
645 Con_Printf ("Sound %s not looped\n", sfx->name);
650 VectorCopy (origin, ss->origin);
651 ss->master_vol = vol;
652 ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist;
653 ss->end = paintedtime + sc->length;
659 //=============================================================================
663 S_UpdateAmbientSounds
666 void S_UpdateAmbientSounds (void)
673 // LordHavoc: kill ambient sounds until proven otherwise
674 for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
675 channels[ambient_channel].sfx = NULL;
677 if (!snd_ambient || !cl.worldmodel || ambient_level.value <= 0)
680 l = Mod_PointInLeaf (listener_origin, cl.worldmodel);
684 // calc ambient sound levels
685 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
687 if (ambient_sfx[ambient_channel] && ambient_sfx[ambient_channel]->silentlymissing)
689 chan = &channels[ambient_channel];
690 chan->sfx = ambient_sfx[ambient_channel];
692 vol = ambient_level.value * l->ambient_sound_level[ambient_channel];
696 // don't adjust volume too fast
697 if (chan->master_vol < vol)
699 chan->master_vol += host_realframetime * ambient_fade.value;
700 if (chan->master_vol > vol)
701 chan->master_vol = vol;
703 else if (chan->master_vol > vol)
705 chan->master_vol -= host_realframetime * ambient_fade.value;
706 if (chan->master_vol < vol)
707 chan->master_vol = vol;
710 chan->leftvol = chan->rightvol = chan->master_vol;
719 Called once each time through the main loop
722 void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up)
729 if (!sound_started || (snd_blocked > 0))
732 VectorCopy(origin, listener_origin);
733 VectorCopy(forward, listener_forward);
734 VectorCopy(right, listener_right);
735 VectorCopy(up, listener_up);
737 // update general area ambient sound sources
738 S_UpdateAmbientSounds ();
742 // update spatialization for static and dynamic sounds
743 ch = channels+NUM_AMBIENTS;
744 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
748 SND_Spatialize(ch); // respatialize channel
749 if (!ch->leftvol && !ch->rightvol)
752 // try to combine static sounds with a previous channel of the same
753 // sound effect so we don't mix five torches every frame
755 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
757 // see if it can just use the last one
758 if (combine && combine->sfx == ch->sfx)
760 combine->leftvol += ch->leftvol;
761 combine->rightvol += ch->rightvol;
762 ch->leftvol = ch->rightvol = 0;
766 combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
767 for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
768 if (combine->sfx == ch->sfx)
771 if (j == total_channels)
779 combine->leftvol += ch->leftvol;
780 combine->rightvol += ch->rightvol;
781 ch->leftvol = ch->rightvol = 0;
791 if (snd_show.integer)
795 for (i=0 ; i<total_channels; i++, ch++)
796 if (ch->sfx && (ch->leftvol || ch->rightvol) )
799 Con_Printf ("----(%i)----\n", total);
806 void GetSoundtime(void)
810 static int oldsamplepos;
813 fullsamples = shm->samples / shm->channels;
815 // it is possible to miscount buffers if it has wrapped twice between
816 // calls to S_Update. Oh well.
818 soundtime = SNDDMA_GetSamples();
820 samplepos = SNDDMA_GetDMAPos();
823 if (samplepos < oldsamplepos)
825 buffers++; // buffer wrapped
827 if (paintedtime > 0x40000000)
828 { // time to chop things off to avoid 32 bit limits
830 paintedtime = fullsamples;
831 S_StopAllSounds (true);
834 oldsamplepos = samplepos;
836 soundtime = buffers*fullsamples + samplepos/shm->channels;
840 void IN_Accumulate (void);
842 void S_ExtraUpdate (void)
849 if (snd_noextraupdate.integer)
850 return; // don't pollute timings
859 if (!sound_started || (snd_blocked > 0))
865 // check to make sure that we haven't overshot
866 if (paintedtime < soundtime)
867 paintedtime = soundtime;
869 // mix ahead of current position
870 endtime = soundtime + _snd_mixahead.value * shm->speed;
871 samps = shm->samples >> (shm->channels-1);
872 if (endtime > (unsigned int)(soundtime + samps))
873 endtime = soundtime + samps;
876 // if the buffer was lost or stopped, restore it and/or restart it
882 if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DD_OK)
883 Con_Printf ("Couldn't get sound buffer status\n");
885 if (dwStatus & DSBSTATUS_BUFFERLOST)
886 pDSBuf->lpVtbl->Restore (pDSBuf);
888 if (!(dwStatus & DSBSTATUS_PLAYING))
889 pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
894 S_PaintChannels (endtime);
900 ===============================================================================
904 ===============================================================================
917 if (!strrchr(Cmd_Argv(i), '.'))
919 strcpy(name, Cmd_Argv(i));
920 strcat(name, ".wav");
923 strcpy(name, Cmd_Argv(i));
924 sfx = S_PrecacheSound(name, true);
925 S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 1.0);
940 if (!strrchr(Cmd_Argv(i), '.'))
942 strcpy(name, Cmd_Argv(i));
943 strcat(name, ".wav");
946 strcpy(name, Cmd_Argv(i));
947 sfx = S_PrecacheSound(name, true);
948 S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 0.0);
964 if (!strrchr(Cmd_Argv(i), '.'))
966 strcpy(name, Cmd_Argv(i));
967 strcat(name, ".wav");
970 strcpy(name, Cmd_Argv(i));
971 sfx = S_PrecacheSound(name, true);
972 vol = atof(Cmd_Argv(i+1));
973 S_StartSound(hash++, 0, sfx, listener_origin, vol, 1.0);
978 void S_SoundList(void)
986 for (sfx=known_sfx, i=0 ; i<num_sfx ; i++, sfx++)
991 size = sc->length*sc->width*(sc->stereo+1);
993 if (sc->loopstart >= 0)
997 Con_Printf("(%2db) %6i : %s\n",sc->width*8, size, sfx->name);
999 Con_Printf ("Total resident: %i\n", total);
1003 void S_LocalSound (char *sound)
1007 if (nosound.integer)
1012 sfx = S_PrecacheSound (sound, true);
1015 Con_Printf ("S_LocalSound: can't precache %s\n", sound);
1018 S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1);
1022 void S_ClearPrecache (void)
1027 void S_BeginPrecaching (void)
1032 void S_EndPrecaching (void)
1037 #define RAWSAMPLESBUFFER 32768
1038 short s_rawsamplesbuffer[RAWSAMPLESBUFFER * 2];
1039 int s_rawsamplesbuffer_start;
1040 int s_rawsamplesbuffer_count;
1042 void S_RawSamples_Enqueue(short *samples, unsigned int length)
1045 //Con_Printf("S_RawSamples_Enqueue: %i samples\n", length);
1046 if (s_rawsamplesbuffer_count + length > RAWSAMPLESBUFFER)
1048 b2 = (s_rawsamplesbuffer_start + s_rawsamplesbuffer_count) % RAWSAMPLESBUFFER;
1049 if (b2 + length > RAWSAMPLESBUFFER)
1051 b3 = (b2 + length) % RAWSAMPLESBUFFER;
1052 memcpy(s_rawsamplesbuffer + b2 * 2, samples, (RAWSAMPLESBUFFER - b2) * sizeof(short[2]));
1053 memcpy(s_rawsamplesbuffer, samples + (RAWSAMPLESBUFFER - b2) * 2, b3 * sizeof(short[2]));
1056 memcpy(s_rawsamplesbuffer + b2 * 2, samples, length * sizeof(short[2]));
1057 s_rawsamplesbuffer_count += length;
1060 void S_RawSamples_Dequeue(int *samples, unsigned int length)
1068 if (l > s_rawsamplesbuffer_count)
1069 l = s_rawsamplesbuffer_count;
1070 b1 = (s_rawsamplesbuffer_start) % RAWSAMPLESBUFFER;
1071 if (b1 + l > RAWSAMPLESBUFFER)
1073 b2 = (b1 + l) % RAWSAMPLESBUFFER;
1074 //memcpy(samples, s_rawsamplesbuffer + b1 * 2, (RAWSAMPLESBUFFER - b1) * sizeof(short[2]));
1075 //memcpy(samples + (RAWSAMPLESBUFFER - b1) * 2, s_rawsamplesbuffer, b2 * sizeof(short[2]));
1076 for (out = samples, in = s_rawsamplesbuffer + b1 * 2, count = (RAWSAMPLESBUFFER - b1) * 2, i = 0;i < count;i++)
1078 for (out = samples + (RAWSAMPLESBUFFER - b1) * 2, in = s_rawsamplesbuffer, count = b2 * 2, i = 0;i < count;i++)
1080 //Con_Printf("S_RawSamples_Dequeue: buffer wrap %i %i\n", (RAWSAMPLESBUFFER - b1), b2);
1084 //memcpy(samples, s_rawsamplesbuffer + b1 * 2, l * sizeof(short[2]));
1085 for (out = samples, in = s_rawsamplesbuffer + b1 * 2, count = l * 2, i = 0;i < count;i++)
1087 //Con_Printf("S_RawSamples_Dequeue: normal %i\n", l);
1089 if (l < (int)length)
1091 memset(samples + l * 2, 0, (length - l) * sizeof(int[2]));
1092 //Con_Printf("S_RawSamples_Dequeue: padding with %i samples\n", length - l);
1094 s_rawsamplesbuffer_start = (s_rawsamplesbuffer_start + l) % RAWSAMPLESBUFFER;
1095 s_rawsamplesbuffer_count -= l;
1098 void S_RawSamples_ClearQueue(void)
1100 s_rawsamplesbuffer_count = 0;
1101 s_rawsamplesbuffer_start = 0;
1104 int S_RawSamples_QueueWantsMore(void)
1106 if (s_rawsamplesbuffer_count < min(shm->speed >> 1, RAWSAMPLESBUFFER >> 1))
1107 return RAWSAMPLESBUFFER - s_rawsamplesbuffer_count;
1112 void S_ResampleBuffer16Stereo(short *input, int inputlength, short *output, int outputlength)
1114 if (inputlength != outputlength)
1116 int i, position, stopposition, step;
1118 step = (float) inputlength * 256.0f / (float) outputlength;
1120 stopposition = (inputlength - 1) << 8;
1122 for (i = 0;i < outputlength && position < stopposition;i++, position += step)
1124 in = input + ((position >> 8) << 1);
1125 out[0] = (((in[1] - in[0]) * (position & 255)) >> 8) + in[0];
1126 out[1] = (((in[3] - in[2]) * (position & 255)) >> 8) + in[2];
1129 stopposition = inputlength << 8;
1130 for (i = 0;i < outputlength && position < stopposition;i++, position += step)
1132 in = input + ((position >> 8) << 1);
1139 memcpy(output, input, inputlength * sizeof(short[2]));
1142 int S_RawSamples_SampleRate(void)
1144 return shm != NULL ? shm->speed : 0;