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]);
323 if (sfx != NULL && !(sfx->flags & SFXFLAG_SERVERSOUND))
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);
362 if (lock && !(sfx->flags & SFXFLAG_PERMANENT))
364 sfx->flags |= SFXFLAG_PERMANENT;
368 if (!nosound.integer && snd_precache.integer)
369 S_LoadSound(sfx, complain);
378 Remove a lock from a SFX and freed it if possible
381 void S_UnlockSfx (sfx_t *sfx)
388 //=============================================================================
394 Picks a channel based on priorities, empty slots, number of channels
397 channel_t *SND_PickChannel(int entnum, int entchannel)
404 // Check for replacement sound, or find the best one to replace
406 life_left = 0x7fffffff;
407 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
409 ch = &channels[ch_idx];
410 if (entchannel != 0 // channel 0 never overrides
411 && ch->entnum == entnum
412 && (ch->entchannel == entchannel || entchannel == -1) )
413 { // always override sound from same entity
414 first_to_die = ch_idx;
418 // don't let monster sounds override player sounds
419 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
422 // don't override looped sounds
423 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
424 (ch->sfx != NULL && ch->sfx->loopstart >= 0))
427 if (ch->end - paintedtime < life_left)
429 life_left = ch->end - paintedtime;
430 first_to_die = ch_idx;
434 if (first_to_die == -1)
437 S_StopChannel (first_to_die);
439 return &channels[first_to_die];
446 Spatializes a channel
449 void SND_Spatialize(channel_t *ch, qboolean isstatic)
451 vec_t dist, scale, pan;
454 // anything coming from the view entity will always be full volume
455 // LordHavoc: make sounds with ATTN_NONE have no spatialization
456 if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
458 ch->leftvol = ch->master_vol;
459 ch->rightvol = ch->master_vol;
463 // update sound origin if we know about the entity
464 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
466 //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]);
467 VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
468 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)
469 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);
472 // calculate stereo seperation and distance attenuation
473 Matrix4x4_Transform(&listener_matrix, ch->origin, source_vec);
474 dist = VectorNormalizeLength(source_vec);
476 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
478 pan = scale * source_vec[1];
479 // calculate the volumes
480 ch->leftvol = (int) (scale + pan);
481 ch->rightvol = (int) (scale - pan);
484 // Adjust volume of static sounds
487 ch->leftvol *= snd_staticvolume.value;
488 ch->rightvol *= snd_staticvolume.value;
492 ch->leftvol = bound(0, ch->leftvol, 255);
493 ch->rightvol = bound(0, ch->rightvol, 255);
497 // =======================================================================
498 // Start a sound effect
499 // =======================================================================
501 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
503 // Initialize the channel
504 memset (target_chan, 0, sizeof (*target_chan));
505 VectorCopy (origin, target_chan->origin);
506 target_chan->master_vol = fvol * 255;
507 target_chan->sfx = sfx;
508 target_chan->end = paintedtime + sfx->total_length;
509 target_chan->lastptime = paintedtime;
510 target_chan->flags = flags;
512 // If it's a static sound
515 if (sfx->loopstart == -1)
516 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
517 target_chan->dist_mult = attenuation / (64.0f * sound_nominal_clip_dist);
520 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
522 // Lock the SFX during play
527 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
529 channel_t *target_chan, *check;
533 if (!sound_started || !sfx || nosound.integer)
536 // Pick a channel to play on
537 target_chan = SND_PickChannel(entnum, entchannel);
541 if (!S_LoadSound (sfx, true))
542 return -1; // couldn't load the sound's data
544 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
545 target_chan->entnum = entnum;
546 target_chan->entchannel = entchannel;
548 SND_Spatialize(target_chan, false);
550 // if an identical sound has also been started this frame, offset the pos
551 // a bit to keep it from just making the first one louder
552 check = &channels[NUM_AMBIENTS];
553 for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
555 if (check == target_chan)
557 if (check->sfx == sfx && !check->pos)
559 skip = 0.1 * sfx->format.speed;
560 if (skip > sfx->total_length)
561 skip = sfx->total_length;
563 skip = rand() % skip;
564 target_chan->pos += skip;
565 target_chan->end -= skip;
570 return (target_chan - channels);
573 void S_StopChannel (unsigned int channel_ind)
577 if (channel_ind >= total_channels)
580 ch = &channels[channel_ind];
583 sfx_t *sfx = ch->sfx;
585 if (sfx->fetcher != NULL)
587 snd_fetcher_end_t fetcher_end = sfx->fetcher->end;
588 if (fetcher_end != NULL)
592 // Remove the lock it holds
601 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
603 if (ch_ind >= total_channels)
606 if (flag != CHANNELFLAG_FORCELOOP &&
607 flag != CHANNELFLAG_PAUSED &&
608 flag != CHANNELFLAG_FULLVOLUME)
612 channels[ch_ind].flags |= flag;
614 channels[ch_ind].flags &= ~flag;
619 void S_StopSound(int entnum, int entchannel)
623 for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
624 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
631 void S_StopAllSounds (void)
635 for (i = 0; i < total_channels; i++)
638 total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics
639 memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
644 void S_PauseGameSounds (qboolean toggle)
648 for (i = 0; i < total_channels; i++)
653 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
654 S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
658 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
660 channels[ch_ind].master_vol = fvol * 255;
664 void S_ClearBuffer(void)
669 if (!sound_started || !shm)
672 if (shm->format.width == 1)
673 clear = 0x80; // 8 bit sound (unsigned)
675 clear = 0; // 16 bit sound (signed)
677 pbuf = S_LockBuffer();
680 int setsize = shm->samples * shm->format.width;
685 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
686 // reads the memory area before writing to it causing a seg fault
687 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
688 //memset(shm->buffer, clear, shm->samples * shm->format.width);
700 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
702 channel_t *target_chan;
707 if (total_channels == MAX_CHANNELS)
709 Con_Print("total_channels == MAX_CHANNELS\n");
713 if (!S_LoadSound (sfx, true))
716 target_chan = &channels[total_channels++];
717 S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
719 SND_Spatialize (target_chan, true);
723 //=============================================================================
727 S_UpdateAmbientSounds
731 void S_UpdateAmbientSounds (void)
736 qbyte ambientlevels[NUM_AMBIENTS];
738 // Mute ambient sounds until proven otherwise
739 for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
740 channels[ambient_channel].master_vol = 0;
742 if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
745 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
747 // Calc ambient sound levels
748 for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
750 chan = &channels[ambient_channel];
751 if (chan->sfx == NULL || (chan->sfx->flags & SFXFLAG_FILEMISSING))
754 vol = ambient_level.value * ambientlevels[ambient_channel];
758 // Don't adjust volume too fast
759 if (chan->master_vol < vol)
761 chan->master_vol += host_realframetime * ambient_fade.value;
762 if (chan->master_vol > vol)
763 chan->master_vol = vol;
765 else if (chan->master_vol > vol)
767 chan->master_vol -= host_realframetime * ambient_fade.value;
768 if (chan->master_vol < vol)
769 chan->master_vol = vol;
772 chan->leftvol = chan->rightvol = chan->master_vol;
781 Called once each time through the main loop
784 void S_Update(const matrix4x4_t *listenermatrix)
786 unsigned int i, j, total;
787 channel_t *ch, *combine;
789 if (!snd_initialized.integer || (snd_blocked > 0))
792 Matrix4x4_Invert_Simple(&listener_matrix, listenermatrix);
793 Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
795 // update general area ambient sound sources
796 S_UpdateAmbientSounds ();
800 // update spatialization for static and dynamic sounds
801 ch = channels+NUM_AMBIENTS;
802 for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
806 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS); // respatialize channel
807 if (!ch->leftvol && !ch->rightvol)
810 // try to combine static sounds with a previous channel of the same
811 // sound effect so we don't mix five torches every frame
812 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
814 // see if it can just use the last one
815 if (combine && combine->sfx == ch->sfx)
817 combine->leftvol += ch->leftvol;
818 combine->rightvol += ch->rightvol;
819 ch->leftvol = ch->rightvol = 0;
823 combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
824 for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
825 if (combine->sfx == ch->sfx)
828 if (j == total_channels)
834 combine->leftvol += ch->leftvol;
835 combine->rightvol += ch->rightvol;
836 ch->leftvol = ch->rightvol = 0;
843 sound_spatialized = true;
846 if (snd_show.integer)
850 for (i=0 ; i<total_channels; i++, ch++)
851 if (ch->sfx && (ch->leftvol || ch->rightvol) )
854 Con_Printf("----(%u)----\n", total);
860 void GetSoundtime(void)
864 static int oldsamplepos;
867 fullsamples = shm->samples / shm->format.channels;
869 // it is possible to miscount buffers if it has wrapped twice between
870 // calls to S_Update. Oh well.
871 samplepos = SNDDMA_GetDMAPos();
873 if (samplepos < oldsamplepos)
875 buffers++; // buffer wrapped
877 if (paintedtime > 0x40000000)
878 { // time to chop things off to avoid 32 bit limits
880 paintedtime = fullsamples;
884 oldsamplepos = samplepos;
886 soundtime = buffers * fullsamples + samplepos / shm->format.channels;
889 void S_ExtraUpdate (void)
891 if (snd_noextraupdate.integer || !sound_spatialized)
902 if (!sound_started || (snd_blocked > 0))
908 // check to make sure that we haven't overshot
909 if (paintedtime < soundtime)
910 paintedtime = soundtime;
912 // mix ahead of current position
913 endtime = soundtime + _snd_mixahead.value * shm->format.speed;
914 samps = shm->samples >> (shm->format.channels - 1);
915 if (endtime > (unsigned int)(soundtime + samps))
916 endtime = soundtime + samps;
918 S_PaintChannels (endtime);
924 ===============================================================================
928 ===============================================================================
931 static void S_Play_Common(float fvol, float attenuation)
940 strlcpy(name, Cmd_Argv(i), sizeof(name));
941 if (!strrchr(name, '.'))
942 strlcat(name, ".wav", sizeof(name));
944 sfx = S_PrecacheSound (name, true, false);
945 // add a lock and the serversound flag to the sfx so it will be kept
946 // until level change
947 if (sfx && !(sfx->flags & SFXFLAG_SERVERSOUND))
949 sfx->flags |= SFXFLAG_SERVERSOUND;
954 // If we need to get the volume from the command line
957 fvol = atof(Cmd_Argv(i));
961 ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
963 // Free the sfx if the file didn't exist
967 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
973 S_Play_Common (1.0f, 1.0f);
978 S_Play_Common (1.0f, 0.0f);
983 S_Play_Common (-1.0f, 0.0f);
986 void S_SoundList(void)
993 for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
995 if (sfx->fetcher != NULL)
997 size = sfx->mempool->totalsize;
999 Con_Printf ("%c%c(%2db, %6s) %8i : %s\n",
1000 (sfx->loopstart >= 0) ? 'L' : ' ',
1001 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
1002 sfx->format.width * 8,
1003 (sfx->format.channels == 1) ? "mono" : "stereo",
1008 Con_Printf("Total resident: %i\n", total);
1012 qboolean S_LocalSound (const char *sound)
1017 if (!snd_initialized.integer || nosound.integer)
1020 sfx = S_PrecacheSound (sound, true, true);
1023 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1027 ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 1);
1031 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;