]> icculus.org git repositories - divverent/darkplaces.git/blob - snd_main.c
changed array pointer state to const float * instead of const void *
[divverent/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                 Host_Error ("S_FindName: sound name too long (%s)", name);
261
262         // Look for this sound in the list of known sfx
263         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
264                 if(!strcmp (sfx->name, name))
265                         return sfx;
266
267         // Add a sfx_t struct for this sound
268         sfx = Mem_Alloc (snd_mempool, sizeof (*sfx));
269         memset (sfx, 0, sizeof(*sfx));
270         strlcpy (sfx->name, name, sizeof (sfx->name));
271         sfx->next = known_sfx;
272         known_sfx = sfx;
273
274         return sfx;
275 }
276
277
278 /*
279 ==================
280 S_FreeSfx
281
282 ==================
283 */
284 void S_FreeSfx (sfx_t *sfx, qboolean force)
285 {
286         // Never free a locked sfx unless forced
287         if (!force && (sfx->locks > 0 || (sfx->flags & SFXFLAG_PERMANENTLOCK)))
288                 return;
289
290         Con_DPrintf ("S_FreeSfx: freeing %s\n", sfx->name);
291
292         // Remove it from the list of known sfx
293         if (sfx == known_sfx)
294                 known_sfx = known_sfx->next;
295         else
296         {
297                 sfx_t *prev_sfx;
298
299                 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
300                         if (prev_sfx->next == sfx)
301                         {
302                                 prev_sfx->next = sfx->next;
303                                 break;
304                         }
305                 if (prev_sfx == NULL)
306                         Sys_Error ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
307         }
308
309         // Free it
310         Mem_FreePool (&sfx->mempool);
311         Mem_Free (sfx);
312 }
313
314
315 /*
316 ==================
317 S_ServerSounds
318
319 ==================
320 */
321 void S_ServerSounds (char serversound [][MAX_QPATH], unsigned int numsounds)
322 {
323         sfx_t *sfx;
324         sfx_t *sfxnext;
325         unsigned int i;
326
327         // Start the ambient sounds and make them loop
328         for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
329         {
330                 // Precache it if it's not done (request a lock to make sure it will never be freed)
331                 if (ambient_sfxs[i] == NULL)
332                         ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, true);
333                 if (ambient_sfxs[i] != NULL)
334                 {
335                         // Add a lock to the SFX while playing. It will be
336                         // removed by S_StopAllSounds at the end of the level
337                         S_LockSfx (ambient_sfxs[i]);
338
339                         channels[i].sfx = ambient_sfxs[i];
340                         channels[i].flags |= CHANNELFLAG_FORCELOOP;
341                         channels[i].master_vol = 0;
342                 }
343         }
344
345         // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
346         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
347                 if (sfx->flags & SFXFLAG_SERVERSOUND)
348                 {
349                         S_UnlockSfx (sfx);
350                         sfx->flags &= ~SFXFLAG_SERVERSOUND;
351                 }
352
353         // Add 1 lock and the SFXFLAG_SERVERSOUND flag to each sfx in "serversound"
354         for (i = 1; i < numsounds; i++)
355         {
356                 sfx = S_FindName (serversound[i]);
357                 if (sfx != NULL)
358                 {
359                         S_LockSfx (sfx);
360                         sfx->flags |= SFXFLAG_SERVERSOUND;
361                 }
362         }
363
364         // Free all unlocked sfx
365         for (sfx = known_sfx;sfx;sfx = sfxnext)
366         {
367                 sfxnext = sfx->next;
368                 S_FreeSfx (sfx, false);
369         }
370 }
371
372
373 /*
374 ==================
375 S_PrecacheSound
376
377 ==================
378 */
379 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean lock)
380 {
381         sfx_t *sfx;
382
383         if (!snd_initialized.integer)
384                 return NULL;
385
386         sfx = S_FindName (name);
387         if (sfx == NULL)
388                 return NULL;
389
390         if (lock)
391                 S_LockSfx (sfx);
392
393         if (!nosound.integer && snd_precache.integer)
394                 S_LoadSound(sfx, complain);
395
396         return sfx;
397 }
398
399 /*
400 ==================
401 S_LockSfx
402
403 Add a lock to a SFX
404 ==================
405 */
406 void S_LockSfx (sfx_t *sfx)
407 {
408         sfx->locks++;
409 }
410
411 /*
412 ==================
413 S_UnlockSfx
414
415 Remove a lock from a SFX
416 ==================
417 */
418 void S_UnlockSfx (sfx_t *sfx)
419 {
420         sfx->locks--;
421 }
422
423
424 //=============================================================================
425
426 /*
427 =================
428 SND_PickChannel
429
430 Picks a channel based on priorities, empty slots, number of channels
431 =================
432 */
433 channel_t *SND_PickChannel(int entnum, int entchannel)
434 {
435         int ch_idx;
436         int first_to_die;
437         int life_left;
438         channel_t* ch;
439
440 // Check for replacement sound, or find the best one to replace
441         first_to_die = -1;
442         life_left = 0x7fffffff;
443         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
444         {
445                 ch = &channels[ch_idx];
446                 if (entchannel != 0             // channel 0 never overrides
447                 && ch->entnum == entnum
448                 && (ch->entchannel == entchannel || entchannel == -1) )
449                 {       // always override sound from same entity
450                         first_to_die = ch_idx;
451                         break;
452                 }
453
454                 // don't let monster sounds override player sounds
455                 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
456                         continue;
457
458                 // don't override looped sounds
459                 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
460                         (ch->sfx != NULL && ch->sfx->loopstart >= 0))
461                         continue;
462
463                 if (ch->end - paintedtime < life_left)
464                 {
465                         life_left = ch->end - paintedtime;
466                         first_to_die = ch_idx;
467                 }
468         }
469
470         if (first_to_die == -1)
471                 return NULL;
472
473         S_StopChannel (first_to_die);
474
475         return &channels[first_to_die];
476 }
477
478 /*
479 =================
480 SND_Spatialize
481
482 Spatializes a channel
483 =================
484 */
485 void SND_Spatialize(channel_t *ch, qboolean isstatic)
486 {
487         vec_t dist, scale, pan;
488         vec3_t source_vec;
489
490         // anything coming from the view entity will always be full volume
491         // LordHavoc: make sounds with ATTN_NONE have no spatialization
492         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
493         {
494                 ch->leftvol = ch->master_vol;
495                 ch->rightvol = ch->master_vol;
496         }
497         else
498         {
499                 // update sound origin if we know about the entity
500                 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
501                 {
502                         //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]);
503                         VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
504                         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)
505                                 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);
506                 }
507
508                 // calculate stereo seperation and distance attenuation
509                 Matrix4x4_Transform(&listener_matrix, ch->origin, source_vec);
510                 dist = VectorNormalizeLength(source_vec);
511                 // distance
512                 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
513                 // panning
514                 pan = scale * source_vec[1];
515                 // calculate the volumes
516                 ch->leftvol = (int) (scale + pan);
517                 ch->rightvol = (int) (scale - pan);
518         }
519
520         // Adjust volume of static sounds
521         if (isstatic)
522         {
523                 ch->leftvol *= snd_staticvolume.value;
524                 ch->rightvol *= snd_staticvolume.value;
525         }
526
527         // clamp volumes
528         ch->leftvol = bound(0, ch->leftvol, 255);
529         ch->rightvol = bound(0, ch->rightvol, 255);
530 }
531
532
533 // =======================================================================
534 // Start a sound effect
535 // =======================================================================
536
537 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
538 {
539         // Initialize the channel
540         memset (target_chan, 0, sizeof (*target_chan));
541         VectorCopy (origin, target_chan->origin);
542         target_chan->master_vol = fvol * 255;
543         target_chan->sfx = sfx;
544         target_chan->end = paintedtime + sfx->total_length;
545         target_chan->lastptime = paintedtime;
546         target_chan->flags = flags;
547
548         // If it's a static sound
549         if (isstatic)
550         {
551                 if (sfx->loopstart == -1)
552                         Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
553                 target_chan->dist_mult = attenuation / (64.0f * sound_nominal_clip_dist);
554         }
555         else
556                 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
557
558         // Lock the SFX during play
559         S_LockSfx (sfx);
560 }
561
562
563 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
564 {
565         channel_t *target_chan, *check;
566         int             ch_idx;
567         size_t  skip;
568
569         if (!sound_started || !sfx || nosound.integer)
570                 return -1;
571         if (!sfx->fetcher)
572         {
573                 Con_DPrintf ("S_StartSound: \"%s\" hasn't been precached\n", sfx->name);
574                 return -1;
575         }
576
577         // Pick a channel to play on
578         target_chan = SND_PickChannel(entnum, entchannel);
579         if (!target_chan)
580                 return -1;
581
582         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
583         target_chan->entnum = entnum;
584         target_chan->entchannel = entchannel;
585
586         SND_Spatialize(target_chan, false);
587
588         // if an identical sound has also been started this frame, offset the pos
589         // a bit to keep it from just making the first one louder
590         check = &channels[NUM_AMBIENTS];
591         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
592         {
593                 if (check == target_chan)
594                         continue;
595                 if (check->sfx == sfx && !check->pos)
596                 {
597                         skip = 0.1 * sfx->format.speed;
598                         if (skip > sfx->total_length)
599                                 skip = sfx->total_length;
600                         if (skip > 0)
601                                 skip = rand() % skip;
602                         target_chan->pos += skip;
603                         target_chan->end -= skip;
604                         break;
605                 }
606         }
607
608         return (target_chan - channels);
609 }
610
611 void S_StopChannel (unsigned int channel_ind)
612 {
613         channel_t *ch;
614
615         if (channel_ind >= total_channels)
616                 return;
617
618         ch = &channels[channel_ind];
619         if (ch->sfx != NULL)
620         {
621                 sfx_t *sfx = ch->sfx;
622
623                 if (sfx->fetcher != NULL)
624                 {
625                         snd_fetcher_end_t fetcher_end = sfx->fetcher->end;
626                         if (fetcher_end != NULL)
627                                 fetcher_end (ch);
628                 }
629
630                 // Remove the lock it holds
631                 S_UnlockSfx (sfx);
632
633                 ch->sfx = NULL;
634         }
635         ch->end = 0;
636 }
637
638
639 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
640 {
641         if (ch_ind >= total_channels)
642                 return false;
643
644         if (flag != CHANNELFLAG_FORCELOOP &&
645                 flag != CHANNELFLAG_PAUSED &&
646                 flag != CHANNELFLAG_FULLVOLUME)
647                 return false;
648
649         if (value)
650                 channels[ch_ind].flags |= flag;
651         else
652                 channels[ch_ind].flags &= ~flag;
653
654         return true;
655 }
656
657 void S_StopSound(int entnum, int entchannel)
658 {
659         unsigned int i;
660
661         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
662                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
663                 {
664                         S_StopChannel (i);
665                         return;
666                 }
667 }
668
669 void S_StopAllSounds (void)
670 {
671         unsigned int i;
672         unsigned char *pbuf;
673
674         if (!sound_started)
675                 return;
676
677         for (i = 0; i < total_channels; i++)
678                 S_StopChannel (i);
679
680         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
681         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
682
683         // Clear sound buffer
684         pbuf = S_LockBuffer();
685         if (pbuf != NULL)
686         {
687                 int setsize = shm->samples * shm->format.width;
688                 int     clear = (shm->format.width == 1) ? 0x80 : 0;
689
690                 // FIXME: is it (still) true? (check with OSS and ALSA)
691                 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
692                 // reads the memory area before writing to it causing a seg fault
693                 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
694                 //memset(shm->buffer, clear, shm->samples * shm->format.width);
695                 while (setsize--)
696                         *pbuf++ = clear;
697
698                 S_UnlockBuffer ();
699         }
700 }
701
702 void S_PauseGameSounds (qboolean toggle)
703 {
704         unsigned int i;
705
706         for (i = 0; i < total_channels; i++)
707         {
708                 channel_t *ch;
709
710                 ch = &channels[i];
711                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
712                         S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
713         }
714 }
715
716 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
717 {
718         channels[ch_ind].master_vol = fvol * 255;
719 }
720
721
722 /*
723 =================
724 S_StaticSound
725 =================
726 */
727 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
728 {
729         channel_t       *target_chan;
730
731         if (!sound_started || !sfx || nosound.integer)
732                 return;
733         if (!sfx->fetcher)
734         {
735                 Con_DPrintf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
736                 return;
737         }
738
739         if (total_channels == MAX_CHANNELS)
740         {
741                 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
742                 return;
743         }
744
745         target_chan = &channels[total_channels++];
746         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
747
748         SND_Spatialize (target_chan, true);
749 }
750
751
752 //=============================================================================
753
754 /*
755 ===================
756 S_UpdateAmbientSounds
757
758 ===================
759 */
760 void S_UpdateAmbientSounds (void)
761 {
762         float           vol;
763         int                     ambient_channel;
764         channel_t       *chan;
765         qbyte           ambientlevels[NUM_AMBIENTS];
766
767         if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
768                 return;
769
770         cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
771
772         // Calc ambient sound levels
773         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
774         {
775                 chan = &channels[ambient_channel];
776                 if (chan->sfx == NULL || chan->sfx->fetcher == NULL)
777                         continue;
778
779                 vol = ambient_level.value * ambientlevels[ambient_channel];
780                 if (vol < 8)
781                         vol = 0;
782
783                 // Don't adjust volume too fast
784                 if (chan->master_vol < vol)
785                 {
786                         chan->master_vol += host_realframetime * ambient_fade.value;
787                         if (chan->master_vol > vol)
788                                 chan->master_vol = vol;
789                 }
790                 else if (chan->master_vol > vol)
791                 {
792                         chan->master_vol -= host_realframetime * ambient_fade.value;
793                         if (chan->master_vol < vol)
794                                 chan->master_vol = vol;
795                 }
796
797                 chan->leftvol = chan->rightvol = chan->master_vol;
798         }
799 }
800
801
802 /*
803 ============
804 S_Update
805
806 Called once each time through the main loop
807 ============
808 */
809 void S_Update(const matrix4x4_t *listenermatrix)
810 {
811         unsigned int i, j, total;
812         channel_t *ch, *combine;
813
814         if (!snd_initialized.integer || (snd_blocked > 0))
815                 return;
816
817         Matrix4x4_Invert_Simple(&listener_matrix, listenermatrix);
818         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
819
820         // update general area ambient sound sources
821         S_UpdateAmbientSounds ();
822
823         combine = NULL;
824
825         // update spatialization for static and dynamic sounds
826         ch = channels+NUM_AMBIENTS;
827         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
828         {
829                 if (!ch->sfx)
830                         continue;
831                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);         // respatialize channel
832                 if (!ch->leftvol && !ch->rightvol)
833                         continue;
834
835                 // try to combine static sounds with a previous channel of the same
836                 // sound effect so we don't mix five torches every frame
837                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
838                 {
839                         // see if it can just use the last one
840                         if (combine && combine->sfx == ch->sfx)
841                         {
842                                 combine->leftvol += ch->leftvol;
843                                 combine->rightvol += ch->rightvol;
844                                 ch->leftvol = ch->rightvol = 0;
845                                 continue;
846                         }
847                         // search for one
848                         combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
849                         for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
850                                 if (combine->sfx == ch->sfx)
851                                         break;
852
853                         if (j == total_channels)
854                                 combine = NULL;
855                         else
856                         {
857                                 if (combine != ch)
858                                 {
859                                         combine->leftvol += ch->leftvol;
860                                         combine->rightvol += ch->rightvol;
861                                         ch->leftvol = ch->rightvol = 0;
862                                 }
863                                 continue;
864                         }
865                 }
866         }
867
868         sound_spatialized = true;
869
870         // debugging output
871         if (snd_show.integer)
872         {
873                 total = 0;
874                 ch = channels;
875                 for (i=0 ; i<total_channels; i++, ch++)
876                         if (ch->sfx && (ch->leftvol || ch->rightvol) )
877                                 total++;
878
879                 Con_Printf("----(%u)----\n", total);
880         }
881
882         S_Update_();
883 }
884
885 void GetSoundtime(void)
886 {
887         int             samplepos;
888         static  int             buffers;
889         static  int             oldsamplepos;
890         int             fullsamples;
891
892         fullsamples = shm->samples / shm->format.channels;
893
894         // it is possible to miscount buffers if it has wrapped twice between
895         // calls to S_Update.  Oh well.
896         samplepos = SNDDMA_GetDMAPos();
897
898         if (samplepos < oldsamplepos)
899         {
900                 buffers++;                                      // buffer wrapped
901
902                 if (paintedtime > 0x40000000)
903                 {       // time to chop things off to avoid 32 bit limits
904                         buffers = 0;
905                         paintedtime = fullsamples;
906                         S_StopAllSounds ();
907                 }
908         }
909         oldsamplepos = samplepos;
910
911         soundtime = buffers * fullsamples + samplepos / shm->format.channels;
912 }
913
914 void S_ExtraUpdate (void)
915 {
916         if (snd_noextraupdate.integer || !sound_spatialized)
917                 return;
918
919         S_Update_();
920 }
921
922 void S_Update_(void)
923 {
924         unsigned        endtime;
925         int                             samps;
926
927         if (!sound_started || (snd_blocked > 0))
928                 return;
929
930         // Updates DMA time
931         GetSoundtime();
932
933         // check to make sure that we haven't overshot
934         if (paintedtime < soundtime)
935                 paintedtime = soundtime;
936
937         // mix ahead of current position
938         endtime = soundtime + _snd_mixahead.value * shm->format.speed;
939         samps = shm->samples >> (shm->format.channels - 1);
940         if (endtime > (unsigned int)(soundtime + samps))
941                 endtime = soundtime + samps;
942
943         S_PaintChannels (endtime);
944
945         SNDDMA_Submit ();
946 }
947
948 /*
949 ===============================================================================
950
951 console functions
952
953 ===============================================================================
954 */
955
956 static void S_Play_Common(float fvol, float attenuation)
957 {
958         int     i, ch_ind;
959         char name[256];
960         sfx_t   *sfx;
961
962         i = 1;
963         while (i<Cmd_Argc())
964         {
965                 // Get the name
966                 strlcpy(name, Cmd_Argv(i), sizeof(name));
967                 if (!strrchr(name, '.'))
968                         strlcat(name, ".wav", sizeof(name));
969                 i++;
970
971                 // If we need to get the volume from the command line
972                 if (fvol == -1.0f)
973                 {
974                         fvol = atof(Cmd_Argv(i));
975                         i++;
976                 }
977
978                 sfx = S_PrecacheSound (name, true, false);
979                 if (sfx)
980                 {
981                         ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
982
983                         // Free the sfx if the file didn't exist
984                         if (ch_ind < 0)
985                                 S_FreeSfx (sfx, false);
986                         else
987                                 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
988                 }
989         }
990 }
991
992 void S_Play(void)
993 {
994         S_Play_Common (1.0f, 1.0f);
995 }
996
997 void S_Play2(void)
998 {
999         S_Play_Common (1.0f, 0.0f);
1000 }
1001
1002 void S_PlayVol(void)
1003 {
1004         S_Play_Common (-1.0f, 0.0f);
1005 }
1006
1007 void S_SoundList(void)
1008 {
1009         unsigned int i;
1010         sfx_t   *sfx;
1011         int             size, total;
1012
1013         total = 0;
1014         for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
1015         {
1016                 if (sfx->fetcher != NULL)
1017                 {
1018                         size = sfx->mempool->totalsize;
1019                         total += size;
1020                         Con_Printf ("%c%c%c%c(%2db, %6s) %8i : %s\n",
1021                                                 (sfx->loopstart >= 0) ? 'L' : ' ',
1022                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
1023                                                 (sfx->locks > 0) ? 'K' : ' ',
1024                                                 (sfx->flags & SFXFLAG_PERMANENTLOCK) ? 'P' : ' ',
1025                                                 sfx->format.width * 8,
1026                                                 (sfx->format.channels == 1) ? "mono" : "stereo",
1027                                                 size,
1028                                                 sfx->name);
1029                 }
1030                 else
1031                         Con_Printf ("    (  unknown  ) unloaded : %s\n", sfx->name);
1032         }
1033         Con_Printf("Total resident: %i\n", total);
1034 }
1035
1036
1037 qboolean S_LocalSound (const char *sound)
1038 {
1039         sfx_t   *sfx;
1040         int             ch_ind;
1041
1042         if (!snd_initialized.integer || nosound.integer)
1043                 return true;
1044
1045         sfx = S_PrecacheSound (sound, true, false);
1046         if (!sfx)
1047         {
1048                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1049                 return false;
1050         }
1051
1052         // Local sounds must not be freed
1053         sfx->flags |= SFXFLAG_PERMANENTLOCK;
1054
1055         ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 1);
1056         if (ch_ind < 0)
1057                 return false;
1058
1059         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1060         return true;
1061 }