]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_main.c
When below 1 fps, the fps counter instead counts spf (seconds per frame). Note that...
[xonotic/darkplaces.git] / snd_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // snd_main.c -- main control for any streaming sound output device
21
22 #include "quakedef.h"
23
24 #include "snd_main.h"
25 #include "snd_ogg.h"
26
27
28 void S_Play(void);
29 void S_PlayVol(void);
30 void S_Play2(void);
31 void S_SoundList(void);
32 void S_Update_();
33
34
35 // =======================================================================
36 // Internal sound data & structures
37 // =======================================================================
38
39 channel_t channels[MAX_CHANNELS];
40 unsigned int total_channels;
41
42 int snd_blocked = 0;
43 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0"};
44 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1"};
45
46 volatile dma_t *shm = 0;
47 volatile dma_t sn;
48
49 vec3_t listener_origin;
50 matrix4x4_t listener_matrix;
51 vec_t sound_nominal_clip_dist=1000.0;
52 mempool_t *snd_mempool;
53
54 int soundtime;
55 int paintedtime;
56
57 // Linked list of known sfx
58 sfx_t *known_sfx = NULL;
59
60 qboolean sound_started = false;
61 qboolean sound_spatialized = false;
62
63 // Fake dma is a synchronous faking of the DMA progress used for
64 // isolating performance in the renderer.
65 qboolean fakedma = false;
66
67 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
68 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
69 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1"};
70
71 cvar_t nosound = {0, "nosound", "0"};
72 cvar_t snd_precache = {0, "snd_precache", "1"};
73 cvar_t bgmbuffer = {0, "bgmbuffer", "4096"};
74 cvar_t ambient_level = {0, "ambient_level", "0.3"};
75 cvar_t ambient_fade = {0, "ambient_fade", "100"};
76 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0"};
77 cvar_t snd_show = {0, "snd_show", "0"};
78 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1"};
79 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0"};
80
81 // Ambient sounds
82 sfx_t* ambient_sfxs [2] = { NULL, NULL };
83 const char* ambient_names [2] = { "sound/ambience/water1.wav", "sound/ambience/wind2.wav" };
84
85
86 // ====================================================================
87 // Functions
88 // ====================================================================
89
90 void S_FreeSfx (sfx_t *sfx, qboolean force);
91
92
93 void S_SoundInfo_f(void)
94 {
95         if (!sound_started)
96         {
97                 Con_Print("sound system not started\n");
98                 return;
99         }
100
101         Con_Printf("%5d stereo\n", shm->format.channels - 1);
102         Con_Printf("%5d samples\n", shm->samples);
103         Con_Printf("%5d samplepos\n", shm->samplepos);
104         Con_Printf("%5d samplebits\n", shm->format.width * 8);
105         Con_Printf("%5d speed\n", shm->format.speed);
106         Con_Printf("%p dma buffer\n", shm->buffer);
107         Con_Printf("%5u total_channels\n", total_channels);
108 }
109
110
111 void S_Startup(void)
112 {
113         if (!snd_initialized.integer)
114                 return;
115
116         shm = &sn;
117         memset((void *)shm, 0, sizeof(*shm));
118
119         // create a piece of DMA memory
120         if (fakedma)
121         {
122                 shm->format.width = 2;
123                 shm->format.speed = 22050;
124                 shm->format.channels = 2;
125                 shm->samples = 32768;
126                 shm->samplepos = 0;
127                 shm->buffer = Mem_Alloc(snd_mempool, shm->format.channels * shm->samples * shm->format.width);
128         }
129         else
130         {
131                 if (!SNDDMA_Init())
132                 {
133                         Con_Print("S_Startup: SNDDMA_Init failed.\n");
134                         shm = NULL;
135                         sound_started = false;
136                         sound_spatialized = false;
137                         return;
138                 }
139         }
140
141         sound_started = true;
142
143         Con_DPrintf("Sound sampling rate: %i\n", shm->format.speed);
144 }
145
146 void S_Shutdown(void)
147 {
148         if (!sound_started)
149                 return;
150
151         if (fakedma)
152                 Mem_Free(shm->buffer);
153         else
154                 SNDDMA_Shutdown();
155
156         shm = NULL;
157         sound_started = false;
158         sound_spatialized = false;
159 }
160
161 void S_Restart_f(void)
162 {
163         S_Shutdown();
164         S_Startup();
165 }
166
167 /*
168 ================
169 S_Init
170 ================
171 */
172 void S_Init(void)
173 {
174         Con_DPrint("\nSound Initialization\n");
175
176         Cvar_RegisterVariable(&volume);
177         Cvar_RegisterVariable(&bgmvolume);
178         Cvar_RegisterVariable(&snd_staticvolume);
179
180 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
181         if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
182                 return;
183
184         snd_mempool = Mem_AllocPool("sound", 0, NULL);
185
186 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
187         if (COM_CheckParm("-simsound"))
188                 fakedma = true;
189
190         Cmd_AddCommand("play", S_Play);
191         Cmd_AddCommand("play2", S_Play2);
192         Cmd_AddCommand("playvol", S_PlayVol);
193         Cmd_AddCommand("stopsound", S_StopAllSounds);
194         Cmd_AddCommand("soundlist", S_SoundList);
195         Cmd_AddCommand("soundinfo", S_SoundInfo_f);
196         Cmd_AddCommand("snd_restart", S_Restart_f);
197
198         Cvar_RegisterVariable(&nosound);
199         Cvar_RegisterVariable(&snd_precache);
200         Cvar_RegisterVariable(&snd_initialized);
201         Cvar_RegisterVariable(&snd_streaming);
202         Cvar_RegisterVariable(&bgmbuffer);
203         Cvar_RegisterVariable(&ambient_level);
204         Cvar_RegisterVariable(&ambient_fade);
205         Cvar_RegisterVariable(&snd_noextraupdate);
206         Cvar_RegisterVariable(&snd_show);
207         Cvar_RegisterVariable(&_snd_mixahead);
208         Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
209
210         Cvar_SetValueQuick(&snd_initialized, true);
211
212         known_sfx = NULL;
213
214         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
215         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
216
217         OGG_OpenLibrary ();
218 }
219
220
221 /*
222 ================
223 S_Terminate
224
225 Shutdown and free all resources
226 ================
227 */
228 void S_Terminate (void)
229 {
230         S_Shutdown ();
231         OGG_CloseLibrary ();
232
233         // Free all SFXs
234         while (known_sfx != NULL)
235                 S_FreeSfx (known_sfx, true);
236
237         Cvar_SetValueQuick (&snd_initialized, false);
238         Mem_FreePool (&snd_mempool);
239 }
240
241
242 // =======================================================================
243 // Load a sound
244 // =======================================================================
245
246 /*
247 ==================
248 S_FindName
249
250 ==================
251 */
252 sfx_t *S_FindName (const char *name)
253 {
254         sfx_t *sfx;
255
256         if (!snd_initialized.integer)
257                 return NULL;
258
259         if (strlen (name) >= sizeof (sfx->name))
260         {
261                 Con_Printf ("S_FindName: sound name too long (%s)", name);
262                 return NULL;
263         }
264
265         // Look for this sound in the list of known sfx
266         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
267                 if(!strcmp (sfx->name, name))
268                         return sfx;
269
270         // Add a sfx_t struct for this sound
271         sfx = Mem_Alloc (snd_mempool, sizeof (*sfx));
272         memset (sfx, 0, sizeof(*sfx));
273         strlcpy (sfx->name, name, sizeof (sfx->name));
274         sfx->next = known_sfx;
275         known_sfx = sfx;
276
277         return sfx;
278 }
279
280
281 /*
282 ==================
283 S_FreeSfx
284
285 ==================
286 */
287 void S_FreeSfx (sfx_t *sfx, qboolean force)
288 {
289         // Never free a locked sfx unless forced
290         if (!force && (sfx->locks > 0 || (sfx->flags & SFXFLAG_PERMANENTLOCK)))
291                 return;
292
293         Con_DPrintf ("S_FreeSfx: freeing %s\n", sfx->name);
294
295         // Remove it from the list of known sfx
296         if (sfx == known_sfx)
297                 known_sfx = known_sfx->next;
298         else
299         {
300                 sfx_t *prev_sfx;
301
302                 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
303                         if (prev_sfx->next == sfx)
304                         {
305                                 prev_sfx->next = sfx->next;
306                                 break;
307                         }
308                 if (prev_sfx == NULL)
309                 {
310                         Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
311                         return;
312                 }
313         }
314
315         // Free it
316         Mem_FreePool (&sfx->mempool);
317         Mem_Free (sfx);
318 }
319
320
321 /*
322 ==================
323 S_ServerSounds
324
325 ==================
326 */
327 void S_ServerSounds (char serversound [][MAX_QPATH], unsigned int numsounds)
328 {
329         sfx_t *sfx;
330         sfx_t *sfxnext;
331         unsigned int i;
332
333         // Start the ambient sounds and make them loop
334         for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
335         {
336                 // Precache it if it's not done (request a lock to make sure it will never be freed)
337                 if (ambient_sfxs[i] == NULL)
338                         ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, true);
339                 if (ambient_sfxs[i] != NULL)
340                 {
341                         // Add a lock to the SFX while playing. It will be
342                         // removed by S_StopAllSounds at the end of the level
343                         S_LockSfx (ambient_sfxs[i]);
344
345                         channels[i].sfx = ambient_sfxs[i];
346                         channels[i].flags |= CHANNELFLAG_FORCELOOP;
347                         channels[i].master_vol = 0;
348                 }
349         }
350
351         // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
352         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
353                 if (sfx->flags & SFXFLAG_SERVERSOUND)
354                 {
355                         S_UnlockSfx (sfx);
356                         sfx->flags &= ~SFXFLAG_SERVERSOUND;
357                 }
358
359         // Add 1 lock and the SFXFLAG_SERVERSOUND flag to each sfx in "serversound"
360         for (i = 1; i < numsounds; i++)
361         {
362                 sfx = S_FindName (serversound[i]);
363                 if (sfx != NULL)
364                 {
365                         S_LockSfx (sfx);
366                         sfx->flags |= SFXFLAG_SERVERSOUND;
367                 }
368         }
369
370         // Free all unlocked sfx
371         for (sfx = known_sfx;sfx;sfx = sfxnext)
372         {
373                 sfxnext = sfx->next;
374                 S_FreeSfx (sfx, false);
375         }
376 }
377
378
379 /*
380 ==================
381 S_PrecacheSound
382
383 ==================
384 */
385 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean lock)
386 {
387         sfx_t *sfx;
388
389         if (!snd_initialized.integer)
390                 return NULL;
391
392         sfx = S_FindName (name);
393         if (sfx == NULL)
394                 return NULL;
395
396         if (lock)
397                 S_LockSfx (sfx);
398
399         if (!nosound.integer && snd_precache.integer)
400                 S_LoadSound(sfx, complain);
401
402         return sfx;
403 }
404
405 /*
406 ==================
407 S_LockSfx
408
409 Add a lock to a SFX
410 ==================
411 */
412 void S_LockSfx (sfx_t *sfx)
413 {
414         sfx->locks++;
415 }
416
417 /*
418 ==================
419 S_UnlockSfx
420
421 Remove a lock from a SFX
422 ==================
423 */
424 void S_UnlockSfx (sfx_t *sfx)
425 {
426         sfx->locks--;
427 }
428
429
430 //=============================================================================
431
432 /*
433 =================
434 SND_PickChannel
435
436 Picks a channel based on priorities, empty slots, number of channels
437 =================
438 */
439 channel_t *SND_PickChannel(int entnum, int entchannel)
440 {
441         int ch_idx;
442         int first_to_die;
443         int life_left;
444         channel_t* ch;
445
446 // Check for replacement sound, or find the best one to replace
447         first_to_die = -1;
448         life_left = 0x7fffffff;
449         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
450         {
451                 ch = &channels[ch_idx];
452                 if (entchannel != 0             // channel 0 never overrides
453                 && ch->entnum == entnum
454                 && (ch->entchannel == entchannel || entchannel == -1) )
455                 {       // always override sound from same entity
456                         first_to_die = ch_idx;
457                         break;
458                 }
459
460                 // don't let monster sounds override player sounds
461                 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
462                         continue;
463
464                 // don't override looped sounds
465                 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
466                         (ch->sfx != NULL && ch->sfx->loopstart >= 0))
467                         continue;
468
469                 if (ch->end - paintedtime < life_left)
470                 {
471                         life_left = ch->end - paintedtime;
472                         first_to_die = ch_idx;
473                 }
474         }
475
476         if (first_to_die == -1)
477                 return NULL;
478
479         S_StopChannel (first_to_die);
480
481         return &channels[first_to_die];
482 }
483
484 /*
485 =================
486 SND_Spatialize
487
488 Spatializes a channel
489 =================
490 */
491 void SND_Spatialize(channel_t *ch, qboolean isstatic)
492 {
493         vec_t dist, scale, pan;
494         vec3_t source_vec;
495
496         // anything coming from the view entity will always be full volume
497         // LordHavoc: make sounds with ATTN_NONE have no spatialization
498         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
499         {
500                 ch->leftvol = ch->master_vol;
501                 ch->rightvol = ch->master_vol;
502         }
503         else
504         {
505                 // update sound origin if we know about the entity
506                 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].render.model)
507                 {
508                         //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].persistent.trail_origin[0], cl_entities[ch->entnum].persistent.trail_origin[1], cl_entities[ch->entnum].persistent.trail_origin[2]);
509                         VectorCopy(cl_entities[ch->entnum].persistent.trail_origin, ch->origin);
510                 }
511
512                 // calculate stereo seperation and distance attenuation
513                 Matrix4x4_Transform(&listener_matrix, ch->origin, source_vec);
514                 dist = VectorNormalizeLength(source_vec);
515                 // distance
516                 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
517                 // panning
518                 pan = scale * source_vec[1];
519                 // calculate the volumes
520                 ch->leftvol = (int) (scale + pan);
521                 ch->rightvol = (int) (scale - pan);
522                 //Con_Printf("%f %f %f:%f %f %f:%f %f:%d %d\n", ch->origin[0], ch->origin[1], ch->origin[2], source_vec[0], source_vec[1], source_vec[2], scale, pan, ch->leftvol, ch->rightvol);
523         }
524
525         // Adjust volume of static sounds
526         if (isstatic)
527         {
528                 ch->leftvol *= snd_staticvolume.value;
529                 ch->rightvol *= snd_staticvolume.value;
530         }
531
532         // clamp volumes
533         ch->leftvol = bound(0, ch->leftvol, 255);
534         ch->rightvol = bound(0, ch->rightvol, 255);
535 }
536
537
538 // =======================================================================
539 // Start a sound effect
540 // =======================================================================
541
542 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
543 {
544         // Initialize the channel
545         memset (target_chan, 0, sizeof (*target_chan));
546         VectorCopy (origin, target_chan->origin);
547         target_chan->master_vol = fvol * 255;
548         target_chan->sfx = sfx;
549         target_chan->end = paintedtime + sfx->total_length;
550         target_chan->lastptime = paintedtime;
551         target_chan->flags = flags;
552
553         // If it's a static sound
554         if (isstatic)
555         {
556                 if (sfx->loopstart == -1)
557                         Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
558                 target_chan->dist_mult = attenuation / (64.0f * sound_nominal_clip_dist);
559         }
560         else
561                 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
562
563         // Lock the SFX during play
564         S_LockSfx (sfx);
565 }
566
567
568 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
569 {
570         channel_t *target_chan, *check;
571         int             ch_idx;
572         int             skip;
573
574         if (!sound_started || !sfx || nosound.integer)
575                 return -1;
576         if (!sfx->fetcher)
577         {
578                 Con_DPrintf ("S_StartSound: \"%s\" hasn't been precached\n", sfx->name);
579                 return -1;
580         }
581
582         if (entnum && entnum >= cl_max_entities)
583                 CL_ExpandEntities(entnum);
584
585         // Pick a channel to play on
586         target_chan = SND_PickChannel(entnum, entchannel);
587         if (!target_chan)
588                 return -1;
589
590         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
591         target_chan->entnum = entnum;
592         target_chan->entchannel = entchannel;
593
594         SND_Spatialize(target_chan, false);
595
596         // if an identical sound has also been started this frame, offset the pos
597         // a bit to keep it from just making the first one louder
598         check = &channels[NUM_AMBIENTS];
599         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
600         {
601                 if (check == target_chan)
602                         continue;
603                 if (check->sfx == sfx && !check->pos)
604                 {
605                         skip = 0.1 * sfx->format.speed;
606                         if (skip > (int)sfx->total_length)
607                                 skip = (int)sfx->total_length;
608                         if (skip > 0)
609                                 skip = rand() % skip;
610                         target_chan->pos += skip;
611                         target_chan->end -= skip;
612                         break;
613                 }
614         }
615
616         return (target_chan - channels);
617 }
618
619 void S_StopChannel (unsigned int channel_ind)
620 {
621         channel_t *ch;
622
623         if (channel_ind >= total_channels)
624                 return;
625
626         ch = &channels[channel_ind];
627         if (ch->sfx != NULL)
628         {
629                 sfx_t *sfx = ch->sfx;
630
631                 if (sfx->fetcher != NULL)
632                 {
633                         snd_fetcher_end_t fetcher_end = sfx->fetcher->end;
634                         if (fetcher_end != NULL)
635                                 fetcher_end (ch);
636                 }
637
638                 // Remove the lock it holds
639                 S_UnlockSfx (sfx);
640
641                 ch->sfx = NULL;
642         }
643         ch->end = 0;
644 }
645
646
647 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
648 {
649         if (ch_ind >= total_channels)
650                 return false;
651
652         if (flag != CHANNELFLAG_FORCELOOP &&
653                 flag != CHANNELFLAG_PAUSED &&
654                 flag != CHANNELFLAG_FULLVOLUME)
655                 return false;
656
657         if (value)
658                 channels[ch_ind].flags |= flag;
659         else
660                 channels[ch_ind].flags &= ~flag;
661
662         return true;
663 }
664
665 void S_StopSound(int entnum, int entchannel)
666 {
667         unsigned int i;
668
669         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
670                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
671                 {
672                         S_StopChannel (i);
673                         return;
674                 }
675 }
676
677 void S_StopAllSounds (void)
678 {
679         unsigned int i;
680         unsigned char *pbuf;
681
682         if (!sound_started)
683                 return;
684
685         for (i = 0; i < total_channels; i++)
686                 S_StopChannel (i);
687
688         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
689         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
690
691         // Clear sound buffer
692         pbuf = S_LockBuffer();
693         if (pbuf != NULL)
694         {
695                 int setsize = shm->samples * shm->format.width;
696                 int     clear = (shm->format.width == 1) ? 0x80 : 0;
697
698                 // FIXME: is it (still) true? (check with OSS and ALSA)
699                 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
700                 // reads the memory area before writing to it causing a seg fault
701                 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
702                 //memset(shm->buffer, clear, shm->samples * shm->format.width);
703                 while (setsize--)
704                         *pbuf++ = clear;
705
706                 S_UnlockBuffer ();
707         }
708 }
709
710 void S_PauseGameSounds (qboolean toggle)
711 {
712         unsigned int i;
713
714         for (i = 0; i < total_channels; i++)
715         {
716                 channel_t *ch;
717
718                 ch = &channels[i];
719                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
720                         S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
721         }
722 }
723
724 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
725 {
726         channels[ch_ind].master_vol = fvol * 255;
727 }
728
729
730 /*
731 =================
732 S_StaticSound
733 =================
734 */
735 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
736 {
737         channel_t       *target_chan;
738
739         if (!sound_started || !sfx || nosound.integer)
740                 return;
741         if (!sfx->fetcher)
742         {
743                 Con_DPrintf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
744                 return;
745         }
746
747         if (total_channels == MAX_CHANNELS)
748         {
749                 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
750                 return;
751         }
752
753         target_chan = &channels[total_channels++];
754         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
755
756         SND_Spatialize (target_chan, true);
757 }
758
759
760 //=============================================================================
761
762 /*
763 ===================
764 S_UpdateAmbientSounds
765
766 ===================
767 */
768 void S_UpdateAmbientSounds (void)
769 {
770         float           vol;
771         int                     ambient_channel;
772         channel_t       *chan;
773         qbyte           ambientlevels[NUM_AMBIENTS];
774
775         if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
776                 return;
777
778         cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
779
780         // Calc ambient sound levels
781         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
782         {
783                 chan = &channels[ambient_channel];
784                 if (chan->sfx == NULL || chan->sfx->fetcher == NULL)
785                         continue;
786
787                 vol = ambient_level.value * ambientlevels[ambient_channel];
788                 if (vol < 8)
789                         vol = 0;
790
791                 // Don't adjust volume too fast
792                 if (chan->master_vol < vol)
793                 {
794                         chan->master_vol += host_realframetime * ambient_fade.value;
795                         if (chan->master_vol > vol)
796                                 chan->master_vol = vol;
797                 }
798                 else if (chan->master_vol > vol)
799                 {
800                         chan->master_vol -= host_realframetime * ambient_fade.value;
801                         if (chan->master_vol < vol)
802                                 chan->master_vol = vol;
803                 }
804
805                 chan->leftvol = chan->rightvol = chan->master_vol;
806         }
807 }
808
809
810 /*
811 ============
812 S_Update
813
814 Called once each time through the main loop
815 ============
816 */
817 void S_Update(const matrix4x4_t *listenermatrix)
818 {
819         unsigned int i, j, total;
820         channel_t *ch, *combine;
821
822         if (!snd_initialized.integer || (snd_blocked > 0))
823                 return;
824
825         Matrix4x4_Invert_Simple(&listener_matrix, listenermatrix);
826         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
827
828         // update general area ambient sound sources
829         S_UpdateAmbientSounds ();
830
831         combine = NULL;
832
833         // update spatialization for static and dynamic sounds
834         ch = channels+NUM_AMBIENTS;
835         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
836         {
837                 if (!ch->sfx)
838                         continue;
839                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);         // respatialize channel
840                 if (!ch->leftvol && !ch->rightvol)
841                         continue;
842
843                 // try to combine static sounds with a previous channel of the same
844                 // sound effect so we don't mix five torches every frame
845                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
846                 {
847                         // see if it can just use the last one
848                         if (combine && combine->sfx == ch->sfx)
849                         {
850                                 combine->leftvol += ch->leftvol;
851                                 combine->rightvol += ch->rightvol;
852                                 ch->leftvol = ch->rightvol = 0;
853                                 continue;
854                         }
855                         // search for one
856                         combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
857                         for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
858                                 if (combine->sfx == ch->sfx)
859                                         break;
860
861                         if (j == total_channels)
862                                 combine = NULL;
863                         else
864                         {
865                                 if (combine != ch)
866                                 {
867                                         combine->leftvol += ch->leftvol;
868                                         combine->rightvol += ch->rightvol;
869                                         ch->leftvol = ch->rightvol = 0;
870                                 }
871                                 continue;
872                         }
873                 }
874         }
875
876         sound_spatialized = true;
877
878         // debugging output
879         if (snd_show.integer)
880         {
881                 total = 0;
882                 ch = channels;
883                 for (i=0 ; i<total_channels; i++, ch++)
884                         if (ch->sfx && (ch->leftvol || ch->rightvol) )
885                                 total++;
886
887                 Con_Printf("----(%u)----\n", total);
888         }
889
890         S_Update_();
891 }
892
893 void GetSoundtime(void)
894 {
895         int             samplepos;
896         static  int             buffers;
897         static  int             oldsamplepos;
898         int             fullsamples;
899
900         fullsamples = shm->samples / shm->format.channels;
901
902         // it is possible to miscount buffers if it has wrapped twice between
903         // calls to S_Update.  Oh well.
904         samplepos = SNDDMA_GetDMAPos();
905
906         if (samplepos < oldsamplepos)
907         {
908                 buffers++;                                      // buffer wrapped
909
910                 if (paintedtime > 0x40000000)
911                 {       // time to chop things off to avoid 32 bit limits
912                         buffers = 0;
913                         paintedtime = fullsamples;
914                         S_StopAllSounds ();
915                 }
916         }
917         oldsamplepos = samplepos;
918
919         soundtime = buffers * fullsamples + samplepos / shm->format.channels;
920 }
921
922 void S_ExtraUpdate (void)
923 {
924         if (snd_noextraupdate.integer || !sound_spatialized)
925                 return;
926
927         S_Update_();
928 }
929
930 void S_Update_(void)
931 {
932         unsigned        endtime;
933         int                             samps;
934
935         if (!sound_started || (snd_blocked > 0))
936                 return;
937
938         // Updates DMA time
939         GetSoundtime();
940
941         // check to make sure that we haven't overshot
942         if (paintedtime < soundtime)
943                 paintedtime = soundtime;
944
945         // mix ahead of current position
946         endtime = soundtime + _snd_mixahead.value * shm->format.speed;
947         samps = shm->samples >> (shm->format.channels - 1);
948         if (endtime > (unsigned int)(soundtime + samps))
949                 endtime = soundtime + samps;
950
951         S_PaintChannels (endtime);
952
953         SNDDMA_Submit ();
954 }
955
956 /*
957 ===============================================================================
958
959 console functions
960
961 ===============================================================================
962 */
963
964 static void S_Play_Common(float fvol, float attenuation)
965 {
966         int     i, ch_ind;
967         char name[256];
968         sfx_t   *sfx;
969
970         i = 1;
971         while (i<Cmd_Argc())
972         {
973                 // Get the name
974                 strlcpy(name, Cmd_Argv(i), sizeof(name));
975                 if (!strrchr(name, '.'))
976                         strlcat(name, ".wav", sizeof(name));
977                 i++;
978
979                 // If we need to get the volume from the command line
980                 if (fvol == -1.0f)
981                 {
982                         fvol = atof(Cmd_Argv(i));
983                         i++;
984                 }
985
986                 sfx = S_PrecacheSound (name, true, false);
987                 if (sfx)
988                 {
989                         ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
990
991                         // Free the sfx if the file didn't exist
992                         if (ch_ind < 0)
993                                 S_FreeSfx (sfx, false);
994                         else
995                                 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
996                 }
997         }
998 }
999
1000 void S_Play(void)
1001 {
1002         S_Play_Common (1.0f, 1.0f);
1003 }
1004
1005 void S_Play2(void)
1006 {
1007         S_Play_Common (1.0f, 0.0f);
1008 }
1009
1010 void S_PlayVol(void)
1011 {
1012         S_Play_Common (-1.0f, 0.0f);
1013 }
1014
1015 void S_SoundList(void)
1016 {
1017         unsigned int i;
1018         sfx_t   *sfx;
1019         int             size, total;
1020
1021         total = 0;
1022         for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
1023         {
1024                 if (sfx->fetcher != NULL)
1025                 {
1026                         size = (int)sfx->mempool->totalsize;
1027                         total += size;
1028                         Con_Printf ("%c%c%c%c(%2db, %6s) %8i : %s\n",
1029                                                 (sfx->loopstart >= 0) ? 'L' : ' ',
1030                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
1031                                                 (sfx->locks > 0) ? 'K' : ' ',
1032                                                 (sfx->flags & SFXFLAG_PERMANENTLOCK) ? 'P' : ' ',
1033                                                 sfx->format.width * 8,
1034                                                 (sfx->format.channels == 1) ? "mono" : "stereo",
1035                                                 size,
1036                                                 sfx->name);
1037                 }
1038                 else
1039                         Con_Printf ("    (  unknown  ) unloaded : %s\n", sfx->name);
1040         }
1041         Con_Printf("Total resident: %i\n", total);
1042 }
1043
1044
1045 qboolean S_LocalSound (const char *sound)
1046 {
1047         sfx_t   *sfx;
1048         int             ch_ind;
1049
1050         if (!snd_initialized.integer || nosound.integer)
1051                 return true;
1052
1053         sfx = S_PrecacheSound (sound, true, false);
1054         if (!sfx)
1055         {
1056                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1057                 return false;
1058         }
1059
1060         // Local sounds must not be freed
1061         sfx->flags |= SFXFLAG_PERMANENTLOCK;
1062
1063         ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 0);
1064         if (ch_ind < 0)
1065                 return false;
1066
1067         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1068         return true;
1069 }