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_main.c -- main control for any streaming sound output device
31 void S_SoundList(void);
34 void S_ClearBuffer (void);
37 // =======================================================================
38 // Internal sound data & structures
39 // =======================================================================
41 channel_t channels[MAX_CHANNELS];
42 unsigned int total_channels;
45 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0"};
46 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1"};
48 volatile dma_t *shm = 0;
51 vec3_t listener_origin;
52 matrix4x4_t listener_matrix;
53 vec_t sound_nominal_clip_dist=1000.0;
54 mempool_t *snd_mempool;
61 // Linked list of known sfx
62 sfx_t *known_sfx = NULL;
64 qboolean sound_started = false;
65 qboolean sound_spatialized = false;
67 // Fake dma is a synchronous faking of the DMA progress used for
68 // isolating performance in the renderer.
69 qboolean fakedma = false;
71 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
72 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
73 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1"};
75 cvar_t nosound = {0, "nosound", "0"};
76 cvar_t snd_precache = {0, "snd_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 // ====================================================================
90 void S_SoundInfo_f(void)
92 if (!sound_started || !shm)
94 Con_Print("sound system not started\n");
98 Con_Printf("%5d stereo\n", shm->format.channels - 1);
99 Con_Printf("%5d samples\n", shm->samples);
100 Con_Printf("%5d samplepos\n", shm->samplepos);
101 Con_Printf("%5d samplebits\n", shm->format.width * 8);
102 Con_Printf("%5d speed\n", shm->format.speed);
103 Con_Printf("%p dma buffer\n", shm->buffer);
104 Con_Printf("%5u total_channels\n", total_channels);
110 if (!snd_initialized.integer)
114 memset((void *)shm, 0, sizeof(*shm));
116 // create a piece of DMA memory
119 shm->format.width = 2;
120 shm->format.speed = 22050;
121 shm->format.channels = 2;
122 shm->samples = 32768;
124 shm->buffer = Mem_Alloc(snd_mempool, shm->format.channels * shm->samples * shm->format.width);
130 Con_Print("S_Startup: SNDDMA_Init failed.\n");
132 sound_started = false;
133 sound_spatialized = false;
138 sound_started = true;
140 Con_DPrintf("Sound sampling rate: %i\n", shm->format.speed);
145 void S_Shutdown(void)
151 Mem_Free(shm->buffer);
156 sound_started = false;
157 sound_spatialized = false;
160 void S_Restart_f(void)
173 Con_DPrint("\nSound Initialization\n");
175 Cvar_RegisterVariable(&volume);
176 Cvar_RegisterVariable(&bgmvolume);
177 Cvar_RegisterVariable(&snd_staticvolume);
179 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
180 if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
183 snd_mempool = Mem_AllocPool("sound", 0, NULL);
185 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
186 if (COM_CheckParm("-simsound"))
189 Cmd_AddCommand("play", S_Play);
190 Cmd_AddCommand("play2", S_Play2);
191 Cmd_AddCommand("playvol", S_PlayVol);
192 Cmd_AddCommand("stopsound", S_StopAllSounds);
193 Cmd_AddCommand("soundlist", S_SoundList);
194 Cmd_AddCommand("soundinfo", S_SoundInfo_f);
195 Cmd_AddCommand("snd_restart", S_Restart_f);
197 Cvar_RegisterVariable(&nosound);
198 Cvar_RegisterVariable(&snd_precache);
199 Cvar_RegisterVariable(&snd_initialized);
200 Cvar_RegisterVariable(&snd_streaming);
201 Cvar_RegisterVariable(&bgmbuffer);
202 Cvar_RegisterVariable(&ambient_level);
203 Cvar_RegisterVariable(&ambient_fade);
204 Cvar_RegisterVariable(&snd_noextraupdate);
205 Cvar_RegisterVariable(&snd_show);
206 Cvar_RegisterVariable(&_snd_mixahead);
207 Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
209 Cvar_SetValueQuick(&snd_initialized, true);
213 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
214 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
220 // =======================================================================
222 // =======================================================================
230 sfx_t *S_FindName (const char *name)
234 if (!snd_initialized.integer)
237 // Add the default sound directory to the path
238 if (strlen (name) >= sizeof (sfx->name))
239 Host_Error ("S_FindName: sound name too long (%s)", name);
241 // Look for this sound in the list of known sfx
242 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
243 if(!strcmp (sfx->name, name))
246 // Add a sfx_t struct for this sound
247 sfx = Mem_Alloc (snd_mempool, sizeof (*sfx));
248 memset (sfx, 0, sizeof(*sfx));
249 strlcpy (sfx->name, name, sizeof (sfx->name));
250 sfx->next = known_sfx;
263 void S_FreeSfx (sfx_t *sfx)
265 // Never free a locked sfx
269 Con_DPrintf ("S_FreeSfx: freeing %s\n", sfx->name);
271 // Remove it from the list of known sfx
272 if (sfx == known_sfx)
273 known_sfx = known_sfx->next;
278 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
279 if (prev_sfx->next == sfx)
281 prev_sfx->next = sfx->next;
284 if (prev_sfx == NULL)
285 Sys_Error ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
289 Mem_FreePool (&sfx->mempool);
300 void S_ServerSounds (char serversound [][MAX_QPATH], unsigned int numsounds)
305 // Start the ambient sounds and make them loop
306 channels[AMBIENT_WATER].sfx = S_PrecacheSound ("sound/ambience/water1.wav", false, true);
307 channels[AMBIENT_SKY].sfx = S_PrecacheSound ("sound/ambience/wind2.wav", false, true);
308 for (i = 0; i < NUM_AMBIENTS; i++)
309 channels[i].flags |= CHANNELFLAG_FORCELOOP;
311 // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
312 for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
313 if (sfx->flags & SFXFLAG_SERVERSOUND)
316 sfx->flags &= ~SFXFLAG_SERVERSOUND;
319 // Add 1 lock and the SFXFLAG_SERVERSOUND flag to each sfx in "serversound"
320 for (i = 1; i < numsounds; i++)
322 sfx = S_FindName (serversound[i]);
326 sfx->flags |= SFXFLAG_SERVERSOUND;
330 // Free all unlocked sfx
336 // We may lose the "next" pointer after S_FreeSfx
351 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean lock)
355 if (!snd_initialized.integer)
358 sfx = S_FindName (name);
365 if (!nosound.integer && snd_precache.integer)
366 S_LoadSound(sfx, complain);
375 Remove a lock from a SFX and freed it if possible
378 void S_UnlockSfx (sfx_t *sfx)
385 //=============================================================================
391 Picks a channel based on priorities, empty slots, number of channels
394 channel_t *SND_PickChannel(int entnum, int entchannel)
401 // Check for replacement sound, or find the best one to replace
403 life_left = 0x7fffffff;
404 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
406 ch = &channels[ch_idx];
407 if (entchannel != 0 // channel 0 never overrides
408 && ch->entnum == entnum
409 && (ch->entchannel == entchannel || entchannel == -1) )
410 { // always override sound from same entity
411 first_to_die = ch_idx;
415 // don't let monster sounds override player sounds
416 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
419 // don't override looped sounds
420 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
421 (ch->sfx != NULL && ch->sfx->loopstart >= 0))
424 if (ch->end - paintedtime < life_left)
426 life_left = ch->end - paintedtime;
427 first_to_die = ch_idx;
431 if (first_to_die == -1)
434 S_StopChannel (first_to_die);
436 return &channels[first_to_die];
443 Spatializes a channel
446 void SND_Spatialize(channel_t *ch, qboolean isstatic)
448 vec_t dist, scale, pan;
451 // anything coming from the view entity will always be full volume
452 // LordHavoc: make sounds with ATTN_NONE have no spatialization
453 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
455 ch->leftvol = ch->master_vol;
456 ch->rightvol = ch->master_vol;
460 // update sound origin if we know about the entity
461 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
463 //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]);
464 VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
465 if (cl_entities[ch->entnum].state_current.modelindex && cl.model_precache[cl_entities[ch->entnum].state_current.modelindex] && cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->soundfromcenter)
466 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);
469 // calculate stereo seperation and distance attenuation
470 Matrix4x4_Transform(&listener_matrix, ch->origin, source_vec);
471 dist = VectorNormalizeLength(source_vec);
473 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
475 pan = scale * source_vec[1];
476 // calculate the volumes
477 ch->leftvol = (int) (scale + pan);
478 ch->rightvol = (int) (scale - pan);
481 // Adjust volume of static sounds
484 ch->leftvol *= snd_staticvolume.value;
485 ch->rightvol *= snd_staticvolume.value;
489 ch->leftvol = bound(0, ch->leftvol, 255);
490 ch->rightvol = bound(0, ch->rightvol, 255);
494 // =======================================================================
495 // Start a sound effect
496 // =======================================================================
498 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
500 // Initialize the channel
501 memset (target_chan, 0, sizeof (*target_chan));
502 VectorCopy (origin, target_chan->origin);
503 target_chan->master_vol = fvol * 255;
504 target_chan->sfx = sfx;
505 target_chan->end = paintedtime + sfx->total_length;
506 target_chan->lastptime = paintedtime;
507 target_chan->flags = flags;
509 // If it's a static sound
512 if (sfx->loopstart == -1)
513 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
514 target_chan->dist_mult = attenuation / (64.0f * sound_nominal_clip_dist);
517 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
519 // Lock the SFX during play
524 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
526 channel_t *target_chan, *check;
530 if (!sound_started || !sfx || nosound.integer)
533 // Pick a channel to play on
534 target_chan = SND_PickChannel(entnum, entchannel);
538 if (!S_LoadSound (sfx, true))
539 return -1; // couldn't load the sound's data
541 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
542 target_chan->entnum = entnum;
543 target_chan->entchannel = entchannel;
545 SND_Spatialize(target_chan, false);
547 // if an identical sound has also been started this frame, offset the pos
548 // a bit to keep it from just making the first one louder
549 check = &channels[NUM_AMBIENTS];
550 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
552 if (check == target_chan)
554 if (check->sfx == sfx && !check->pos)
556 skip = 0.1 * sfx->format.speed;
557 if (skip > sfx->total_length)
558 skip = sfx->total_length;
560 skip = rand() % skip;
561 target_chan->pos += skip;
562 target_chan->end -= skip;
567 return (target_chan - channels);
570 void S_StopChannel (unsigned int channel_ind)
574 if (channel_ind >= total_channels)
577 ch = &channels[channel_ind];
580 sfx_t *sfx = ch->sfx;
582 if (sfx->fetcher != NULL)
584 snd_fetcher_end_t fetcher_end = sfx->fetcher->end;
585 if (fetcher_end != NULL)
589 // Remove the lock it holds
598 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
600 if (ch_ind >= total_channels)
603 if (flag != CHANNELFLAG_FORCELOOP &&
604 flag != CHANNELFLAG_PAUSED &&
605 flag != CHANNELFLAG_FULLVOLUME)
609 channels[ch_ind].flags |= flag;
611 channels[ch_ind].flags &= ~flag;
616 void S_StopSound(int entnum, int entchannel)
620 for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
621 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
628 void S_StopAllSounds (void)
632 for (i = 0; i < total_channels; i++)
635 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
636 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
641 void S_PauseGameSounds (qboolean toggle)
645 for (i = 0; i < total_channels; i++)
650 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
651 S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
655 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
657 channels[ch_ind].master_vol = fvol * 255;
661 void S_ClearBuffer(void)
666 if (!sound_started || !shm)
669 if (shm->format.width == 1)
670 clear = 0x80; // 8 bit sound (unsigned)
672 clear = 0; // 16 bit sound (signed)
674 pbuf = S_LockBuffer();
677 int setsize = shm->samples * shm->format.width;
682 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
683 // reads the memory area before writing to it causing a seg fault
684 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
685 //memset(shm->buffer, clear, shm->samples * shm->format.width);
697 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
699 channel_t *target_chan;
704 if (total_channels == MAX_CHANNELS)
706 Con_Print("total_channels == MAX_CHANNELS\n");
710 if (!S_LoadSound (sfx, true))
713 target_chan = &channels[total_channels++];
714 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
716 SND_Spatialize (target_chan, true);
720 //=============================================================================
724 S_UpdateAmbientSounds
728 void S_UpdateAmbientSounds (void)
733 qbyte ambientlevels[NUM_AMBIENTS];
735 // Mute ambient sounds until proven otherwise
736 for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
737 channels[ambient_channel].master_vol = 0;
739 if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
742 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
744 // Calc ambient sound levels
745 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
747 chan = &channels[ambient_channel];
748 if (chan->sfx == NULL || (chan->sfx->flags & SFXFLAG_FILEMISSING))
751 vol = ambient_level.value * ambientlevels[ambient_channel];
755 // Don't adjust volume too fast
756 if (chan->master_vol < vol)
758 chan->master_vol += host_realframetime * ambient_fade.value;
759 if (chan->master_vol > vol)
760 chan->master_vol = vol;
762 else if (chan->master_vol > vol)
764 chan->master_vol -= host_realframetime * ambient_fade.value;
765 if (chan->master_vol < vol)
766 chan->master_vol = vol;
769 chan->leftvol = chan->rightvol = chan->master_vol;
778 Called once each time through the main loop
781 void S_Update(const matrix4x4_t *listenermatrix)
783 unsigned int i, j, total;
784 channel_t *ch, *combine;
786 if (!snd_initialized.integer || (snd_blocked > 0))
789 Matrix4x4_Invert_Simple(&listener_matrix, listenermatrix);
790 Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
792 // update general area ambient sound sources
793 S_UpdateAmbientSounds ();
797 // update spatialization for static and dynamic sounds
798 ch = channels+NUM_AMBIENTS;
799 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
803 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS); // respatialize channel
804 if (!ch->leftvol && !ch->rightvol)
807 // try to combine static sounds with a previous channel of the same
808 // sound effect so we don't mix five torches every frame
809 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
811 // see if it can just use the last one
812 if (combine && combine->sfx == ch->sfx)
814 combine->leftvol += ch->leftvol;
815 combine->rightvol += ch->rightvol;
816 ch->leftvol = ch->rightvol = 0;
820 combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
821 for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
822 if (combine->sfx == ch->sfx)
825 if (j == total_channels)
831 combine->leftvol += ch->leftvol;
832 combine->rightvol += ch->rightvol;
833 ch->leftvol = ch->rightvol = 0;
840 sound_spatialized = true;
843 if (snd_show.integer)
847 for (i=0 ; i<total_channels; i++, ch++)
848 if (ch->sfx && (ch->leftvol || ch->rightvol) )
851 Con_Printf("----(%u)----\n", total);
857 void GetSoundtime(void)
861 static int oldsamplepos;
864 fullsamples = shm->samples / shm->format.channels;
866 // it is possible to miscount buffers if it has wrapped twice between
867 // calls to S_Update. Oh well.
868 samplepos = SNDDMA_GetDMAPos();
870 if (samplepos < oldsamplepos)
872 buffers++; // buffer wrapped
874 if (paintedtime > 0x40000000)
875 { // time to chop things off to avoid 32 bit limits
877 paintedtime = fullsamples;
881 oldsamplepos = samplepos;
883 soundtime = buffers * fullsamples + samplepos / shm->format.channels;
886 void S_ExtraUpdate (void)
888 if (snd_noextraupdate.integer || !sound_spatialized)
899 if (!sound_started || (snd_blocked > 0))
905 // check to make sure that we haven't overshot
906 if (paintedtime < soundtime)
907 paintedtime = soundtime;
909 // mix ahead of current position
910 endtime = soundtime + _snd_mixahead.value * shm->format.speed;
911 samps = shm->samples >> (shm->format.channels - 1);
912 if (endtime > (unsigned int)(soundtime + samps))
913 endtime = soundtime + samps;
915 S_PaintChannels (endtime);
921 ===============================================================================
925 ===============================================================================
928 static void S_Play_Common(float fvol, float attenuation)
937 if (!strrchr(Cmd_Argv(i), '.'))
938 snprintf(name, sizeof(name), "%s.wav", Cmd_Argv(i));
940 strlcpy(name, Cmd_Argv(i), sizeof(name));
941 sfx = S_PrecacheSound (name, true, false);
943 // If we need to get the volume from the command line
946 fvol = atof(Cmd_Argv(i+1));
952 ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
954 // Free the sfx if the file didn't exist
958 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
964 S_Play_Common (1.0f, 1.0f);
969 S_Play_Common (1.0f, 0.0f);
974 S_Play_Common (-1.0f, 0.0f);
977 void S_SoundList(void)
984 for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
986 if (sfx->fetcher != NULL)
988 size = sfx->mempool->totalsize;
990 Con_Printf ("%c%c(%2db, %6s) %8i : %s\n",
991 (sfx->loopstart >= 0) ? 'L' : ' ',
992 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
993 sfx->format.width * 8,
994 (sfx->format.channels == 1) ? "mono" : "stereo",
999 Con_Printf("Total resident: %i\n", total);
1003 qboolean S_LocalSound (const char *sound)
1008 if (!snd_initialized.integer || nosound.integer)
1011 sfx = S_PrecacheSound (sound, true, false);
1014 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1018 ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 1);
1022 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;