Added function S_IsSoundPrecached to the sound engine API. "snd_main.h" shouldn't...
[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 #if SND_LISTENERS != 8
28 #error this data only supports up to 8 channel, update it!
29 #endif
30 typedef struct listener_s
31 {
32         float yawangle;
33         float dotscale;
34         float dotbias;
35         float ambientvolume;
36 }
37 listener_t;
38 typedef struct speakerlayout_s
39 {
40         const char *name;
41         unsigned int channels;
42         listener_t listeners[SND_LISTENERS];
43 }
44 speakerlayout_t;
45
46 static speakerlayout_t snd_speakerlayout;
47
48 void S_Play(void);
49 void S_PlayVol(void);
50 void S_Play2(void);
51 void S_SoundList(void);
52 void S_Update_();
53
54
55 // =======================================================================
56 // Internal sound data & structures
57 // =======================================================================
58
59 channel_t channels[MAX_CHANNELS];
60 unsigned int total_channels;
61
62 int snd_blocked = 0;
63 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0", "indicates the sound subsystem is active"};
64 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1", "enables keeping compressed ogg sound files compressed, decompressing them only as needed, otherwise they will be decompressed completely at load (may use a lot of memory)"};
65
66 volatile dma_t *shm = 0;
67 volatile dma_t sn;
68
69 vec3_t listener_origin;
70 matrix4x4_t listener_matrix[SND_LISTENERS];
71 vec_t sound_nominal_clip_dist=1000.0;
72 mempool_t *snd_mempool;
73
74 int soundtime;
75 int paintedtime;
76
77 // Linked list of known sfx
78 sfx_t *known_sfx = NULL;
79
80 qboolean sound_spatialized = false;
81
82 // Fake dma is a synchronous faking of the DMA progress used for
83 // isolating performance in the renderer.
84 qboolean fakedma = false;
85
86 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1", "volume of background music (such as CD music or replacement files such as sound/cdtracks/track002.ogg)"};
87 cvar_t volume = {CVAR_SAVE, "volume", "0.7", "volume of sound effects"};
88 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1", "volume of ambient sound effects (such as swampy sounds at the start of e1m2)"};
89
90 cvar_t nosound = {0, "nosound", "0", "disables sound"};
91 cvar_t snd_precache = {0, "snd_precache", "1", "loads sounds before they are used"};
92 //cvar_t bgmbuffer = {0, "bgmbuffer", "4096", "unused quake cvar"};
93 cvar_t ambient_level = {0, "ambient_level", "0.3", "volume of environment noises (water and wind)"};
94 cvar_t ambient_fade = {0, "ambient_fade", "100", "rate of volume fading when moving from one environment to another"};
95 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0", "disables extra sound mixer calls that are meant to reduce the chance of sound breakup at very low framerates"};
96 cvar_t snd_show = {0, "snd_show", "0", "shows some statistics about sound mixing"};
97 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1", "how much sound to mix ahead of time"};
98 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0", "swaps left/right speakers for old ISA soundblaster cards"};
99
100 // Ambient sounds
101 sfx_t* ambient_sfxs [2] = { NULL, NULL };
102 const char* ambient_names [2] = { "sound/ambience/water1.wav", "sound/ambience/wind2.wav" };
103
104
105 // ====================================================================
106 // Functions
107 // ====================================================================
108
109 void S_FreeSfx (sfx_t *sfx, qboolean force);
110
111
112 void S_SoundInfo_f(void)
113 {
114         if (!shm)
115         {
116                 Con_Print("sound system not started\n");
117                 return;
118         }
119
120         Con_Printf("%5d speakers\n", shm->format.channels);
121         Con_Printf("%5d frames\n", shm->sampleframes);
122         Con_Printf("%5d samples\n", shm->samples);
123         Con_Printf("%5d samplepos\n", shm->samplepos);
124         Con_Printf("%5d samplebits\n", shm->format.width * 8);
125         Con_Printf("%5d speed\n", shm->format.speed);
126         Con_Printf("%p dma buffer\n", shm->buffer);
127         Con_Printf("%5u total_channels\n", total_channels);
128 }
129
130
131 void S_Startup(void)
132 {
133         if (!snd_initialized.integer)
134                 return;
135
136         shm = &sn;
137         memset((void *)shm, 0, sizeof(*shm));
138
139         // create a piece of DMA memory
140         if (fakedma)
141         {
142                 shm->format.width = 2;
143                 shm->format.speed = 22050;
144                 shm->format.channels = 2;
145                 shm->sampleframes = 16384;
146                 shm->samples = shm->sampleframes * shm->format.channels;
147                 shm->samplepos = 0;
148                 shm->buffer = (unsigned char *)Mem_Alloc(snd_mempool, shm->samples * shm->format.width);
149         }
150         else
151         {
152                 if (!SNDDMA_Init())
153                 {
154                         Con_Print("S_Startup: SNDDMA_Init failed.\n");
155                         shm = NULL;
156                         sound_spatialized = false;
157                         return;
158                 }
159         }
160
161         Con_Printf("Sound format: %dHz, %d bit, %d channels\n", shm->format.speed,
162                            shm->format.width * 8, shm->format.channels);
163 }
164
165 void S_Shutdown(void)
166 {
167         if (!shm)
168                 return;
169
170         if (fakedma)
171                 Mem_Free(shm->buffer);
172         else
173                 SNDDMA_Shutdown();
174
175         shm = NULL;
176         sound_spatialized = false;
177 }
178
179 void S_Restart_f(void)
180 {
181         S_Shutdown();
182         S_Startup();
183 }
184
185 /*
186 ================
187 S_Init
188 ================
189 */
190 void S_Init(void)
191 {
192         Con_DPrint("\nSound Initialization\n");
193
194         Cvar_RegisterVariable(&volume);
195         Cvar_RegisterVariable(&bgmvolume);
196         Cvar_RegisterVariable(&snd_staticvolume);
197
198 // COMMANDLINEOPTION: Sound: -nosound disables sound (including CD audio)
199         if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
200                 return;
201
202         snd_mempool = Mem_AllocPool("sound", 0, NULL);
203
204 // COMMANDLINEOPTION: Sound: -simsound runs sound mixing but with no output
205         if (COM_CheckParm("-simsound"))
206                 fakedma = true;
207
208         Cmd_AddCommand("play", S_Play, "play a sound at your current location (not heard by anyone else)");
209         Cmd_AddCommand("play2", S_Play2, "play a sound globally throughout the level (not heard by anyone else)");
210         Cmd_AddCommand("playvol", S_PlayVol, "play a sound at the specified volume level at your current location (not heard by anyone else)");
211         Cmd_AddCommand("stopsound", S_StopAllSounds, "silence");
212         Cmd_AddCommand("soundlist", S_SoundList, "list loaded sounds");
213         Cmd_AddCommand("soundinfo", S_SoundInfo_f, "print sound system information (such as channels and speed)");
214         Cmd_AddCommand("snd_restart", S_Restart_f, "restart sound system");
215
216         Cvar_RegisterVariable(&nosound);
217         Cvar_RegisterVariable(&snd_precache);
218         Cvar_RegisterVariable(&snd_initialized);
219         Cvar_RegisterVariable(&snd_streaming);
220         //Cvar_RegisterVariable(&bgmbuffer);
221         Cvar_RegisterVariable(&ambient_level);
222         Cvar_RegisterVariable(&ambient_fade);
223         Cvar_RegisterVariable(&snd_noextraupdate);
224         Cvar_RegisterVariable(&snd_show);
225         Cvar_RegisterVariable(&_snd_mixahead);
226         Cvar_RegisterVariable(&snd_swapstereo); // for people with backwards sound wiring
227
228         Cvar_SetValueQuick(&snd_initialized, true);
229
230         known_sfx = NULL;
231
232         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
233         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
234
235         OGG_OpenLibrary ();
236 }
237
238
239 /*
240 ================
241 S_Terminate
242
243 Shutdown and free all resources
244 ================
245 */
246 void S_Terminate (void)
247 {
248         S_Shutdown ();
249         OGG_CloseLibrary ();
250
251         // Free all SFXs
252         while (known_sfx != NULL)
253                 S_FreeSfx (known_sfx, true);
254
255         Cvar_SetValueQuick (&snd_initialized, false);
256         Mem_FreePool (&snd_mempool);
257 }
258
259
260 // =======================================================================
261 // Load a sound
262 // =======================================================================
263
264 /*
265 ==================
266 S_FindName
267
268 ==================
269 */
270 sfx_t *S_FindName (const char *name)
271 {
272         sfx_t *sfx;
273
274         if (!snd_initialized.integer)
275                 return NULL;
276
277         if (strlen (name) >= sizeof (sfx->name))
278         {
279                 Con_Printf ("S_FindName: sound name too long (%s)\n", name);
280                 return NULL;
281         }
282
283         // Look for this sound in the list of known sfx
284         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
285                 if(!strcmp (sfx->name, name))
286                         return sfx;
287
288         // Add a sfx_t struct for this sound
289         sfx = (sfx_t *)Mem_Alloc (snd_mempool, sizeof (*sfx));
290         memset (sfx, 0, sizeof(*sfx));
291         strlcpy (sfx->name, name, sizeof (sfx->name));
292         sfx->memsize = sizeof(*sfx);
293         sfx->next = known_sfx;
294         known_sfx = sfx;
295
296         return sfx;
297 }
298
299
300 /*
301 ==================
302 S_FreeSfx
303
304 ==================
305 */
306 void S_FreeSfx (sfx_t *sfx, qboolean force)
307 {
308         unsigned int i;
309
310         // Never free a locked sfx unless forced
311         if (!force && (sfx->locks > 0 || (sfx->flags & SFXFLAG_PERMANENTLOCK)))
312                 return;
313
314         Con_DPrintf ("S_FreeSfx: freeing %s\n", sfx->name);
315
316         // Remove it from the list of known sfx
317         if (sfx == known_sfx)
318                 known_sfx = known_sfx->next;
319         else
320         {
321                 sfx_t *prev_sfx;
322
323                 for (prev_sfx = known_sfx; prev_sfx != NULL; prev_sfx = prev_sfx->next)
324                         if (prev_sfx->next == sfx)
325                         {
326                                 prev_sfx->next = sfx->next;
327                                 break;
328                         }
329                 if (prev_sfx == NULL)
330                 {
331                         Con_Printf ("S_FreeSfx: Can't find SFX %s in the list!\n", sfx->name);
332                         return;
333                 }
334         }
335
336         // Stop all channels using this sfx
337         for (i = 0; i < total_channels; i++)
338                 if (channels[i].sfx == sfx)
339                         S_StopChannel (i);
340
341         // Free it
342         if (sfx->fetcher != NULL && sfx->fetcher->free != NULL)
343                 sfx->fetcher->free (sfx);
344         Mem_Free (sfx);
345 }
346
347
348 /*
349 ==================
350 S_ServerSounds
351
352 ==================
353 */
354 void S_ServerSounds (char serversound [][MAX_QPATH], unsigned int numsounds)
355 {
356         sfx_t *sfx;
357         sfx_t *sfxnext;
358         unsigned int i;
359
360         // Start the ambient sounds and make them loop
361         for (i = 0; i < sizeof (ambient_sfxs) / sizeof (ambient_sfxs[0]); i++)
362         {
363                 // Precache it if it's not done (request a lock to make sure it will never be freed)
364                 if (ambient_sfxs[i] == NULL)
365                         ambient_sfxs[i] = S_PrecacheSound (ambient_names[i], false, true);
366                 if (ambient_sfxs[i] != NULL)
367                 {
368                         // Add a lock to the SFX while playing. It will be
369                         // removed by S_StopAllSounds at the end of the level
370                         S_LockSfx (ambient_sfxs[i]);
371
372                         channels[i].sfx = ambient_sfxs[i];
373                         channels[i].flags |= CHANNELFLAG_FORCELOOP;
374                         channels[i].master_vol = 0;
375                 }
376         }
377
378         // Remove 1 lock from all sfx with the SFXFLAG_SERVERSOUND flag, and remove the flag
379         for (sfx = known_sfx; sfx != NULL; sfx = sfx->next)
380                 if (sfx->flags & SFXFLAG_SERVERSOUND)
381                 {
382                         S_UnlockSfx (sfx);
383                         sfx->flags &= ~SFXFLAG_SERVERSOUND;
384                 }
385
386         // Add 1 lock and the SFXFLAG_SERVERSOUND flag to each sfx in "serversound"
387         for (i = 1; i < numsounds; i++)
388         {
389                 sfx = S_FindName (serversound[i]);
390                 if (sfx != NULL)
391                 {
392                         S_LockSfx (sfx);
393                         sfx->flags |= SFXFLAG_SERVERSOUND;
394                 }
395         }
396
397         // Free all unlocked sfx
398         for (sfx = known_sfx;sfx;sfx = sfxnext)
399         {
400                 sfxnext = sfx->next;
401                 S_FreeSfx (sfx, false);
402         }
403 }
404
405
406 /*
407 ==================
408 S_PrecacheSound
409
410 ==================
411 */
412 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean lock)
413 {
414         sfx_t *sfx;
415
416         if (!snd_initialized.integer)
417                 return NULL;
418
419         sfx = S_FindName (name);
420         if (sfx == NULL)
421                 return NULL;
422
423         if (lock)
424                 S_LockSfx (sfx);
425
426         if (!nosound.integer && snd_precache.integer)
427                 S_LoadSound(sfx, complain);
428
429         return sfx;
430 }
431
432 /*
433 ==================
434 S_IsSoundPrecached
435 ==================
436 */
437 qboolean S_IsSoundPrecached (const sfx_t *sfx)
438 {
439         return (sfx != NULL && sfx->fetcher != NULL);
440 }
441
442 /*
443 ==================
444 S_LockSfx
445
446 Add a lock to a SFX
447 ==================
448 */
449 void S_LockSfx (sfx_t *sfx)
450 {
451         sfx->locks++;
452 }
453
454 /*
455 ==================
456 S_UnlockSfx
457
458 Remove a lock from a SFX
459 ==================
460 */
461 void S_UnlockSfx (sfx_t *sfx)
462 {
463         sfx->locks--;
464 }
465
466
467 //=============================================================================
468
469 /*
470 =================
471 SND_PickChannel
472
473 Picks a channel based on priorities, empty slots, number of channels
474 =================
475 */
476 channel_t *SND_PickChannel(int entnum, int entchannel)
477 {
478         int ch_idx;
479         int first_to_die;
480         int life_left;
481         channel_t* ch;
482
483 // Check for replacement sound, or find the best one to replace
484         first_to_die = -1;
485         life_left = 0x7fffffff;
486         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
487         {
488                 ch = &channels[ch_idx];
489                 if (entchannel != 0)
490                 {
491                         // try to override an existing channel
492                         if (ch->entnum == entnum && (ch->entchannel == entchannel || entchannel == -1) )
493                         {
494                                 // always override sound from same entity
495                                 first_to_die = ch_idx;
496                                 break;
497                         }
498                 }
499                 else
500                 {
501                         if (!ch->sfx)
502                         {
503                                 // no sound on this channel
504                                 first_to_die = ch_idx;
505                                 break;
506                         }
507                 }
508
509                 if (ch->sfx)
510                 {
511                         // don't let monster sounds override player sounds
512                         if (ch->entnum == cl.viewentity && entnum != cl.viewentity)
513                                 continue;
514
515                         // don't override looped sounds
516                         if ((ch->flags & CHANNELFLAG_FORCELOOP) || ch->sfx->loopstart >= 0)
517                                 continue;
518                 }
519
520                 if (ch->end - paintedtime < life_left)
521                 {
522                         life_left = ch->end - paintedtime;
523                         first_to_die = ch_idx;
524                 }
525         }
526
527         if (first_to_die == -1)
528                 return NULL;
529
530         S_StopChannel (first_to_die);
531
532         return &channels[first_to_die];
533 }
534
535 /*
536 =================
537 SND_Spatialize
538
539 Spatializes a channel
540 =================
541 */
542 void SND_Spatialize(channel_t *ch, qboolean isstatic)
543 {
544         int i;
545         vec_t dist, mastervol, intensity, vol;
546         vec3_t source_vec;
547
548         // update sound origin if we know about the entity
549         if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
550         {
551                 //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]);
552                 VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
553                 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)
554                         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);
555         }
556
557         mastervol = ch->master_vol;
558         // Adjust volume of static sounds
559         if (isstatic)
560                 mastervol *= snd_staticvolume.value;
561
562         // anything coming from the view entity will always be full volume
563         // LordHavoc: make sounds with ATTN_NONE have no spatialization
564         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
565         {
566                 for (i = 0;i < SND_LISTENERS;i++)
567                 {
568                         vol = mastervol * snd_speakerlayout.listeners[i].ambientvolume;
569                         ch->listener_volume[i] = bound(0, vol, 255);
570                 }
571         }
572         else
573         {
574                 // calculate stereo seperation and distance attenuation
575                 VectorSubtract(listener_origin, ch->origin, source_vec);
576                 dist = VectorLength(source_vec);
577                 intensity = mastervol * (1.0 - dist * ch->dist_mult);
578                 if (intensity > 0)
579                 {
580                         for (i = 0;i < SND_LISTENERS;i++)
581                         {
582                                 Matrix4x4_Transform(&listener_matrix[i], ch->origin, source_vec);
583                                 VectorNormalize(source_vec);
584                                 vol = intensity * max(0, source_vec[0] * snd_speakerlayout.listeners[i].dotscale + snd_speakerlayout.listeners[i].dotbias);
585                                 ch->listener_volume[i] = bound(0, vol, 255);
586                         }
587                 }
588                 else
589                         for (i = 0;i < SND_LISTENERS;i++)
590                                 ch->listener_volume[i] = 0;
591         }
592 }
593
594
595 // =======================================================================
596 // Start a sound effect
597 // =======================================================================
598
599 void S_PlaySfxOnChannel (sfx_t *sfx, channel_t *target_chan, unsigned int flags, vec3_t origin, float fvol, float attenuation, qboolean isstatic)
600 {
601         // Initialize the channel
602         memset (target_chan, 0, sizeof (*target_chan));
603         VectorCopy (origin, target_chan->origin);
604         target_chan->master_vol = fvol * 255;
605         target_chan->sfx = sfx;
606         target_chan->end = paintedtime + sfx->total_length;
607         target_chan->lastptime = paintedtime;
608         target_chan->flags = flags;
609
610         // If it's a static sound
611         if (isstatic)
612         {
613                 if (sfx->loopstart == -1)
614                         Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
615                 target_chan->dist_mult = attenuation / (64.0f * sound_nominal_clip_dist);
616         }
617         else
618                 target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
619
620         // Lock the SFX during play
621         S_LockSfx (sfx);
622 }
623
624
625 int S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
626 {
627         channel_t *target_chan, *check;
628         int             ch_idx;
629         int             skip;
630
631         if (!shm || !sfx || nosound.integer)
632                 return -1;
633         if (!sfx->fetcher)
634         {
635                 Con_DPrintf ("S_StartSound: \"%s\" hasn't been precached\n", sfx->name);
636                 return -1;
637         }
638
639         if (entnum && entnum >= cl_max_entities)
640                 CL_ExpandEntities(entnum);
641
642         // Pick a channel to play on
643         target_chan = SND_PickChannel(entnum, entchannel);
644         if (!target_chan)
645                 return -1;
646
647         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_NONE, origin, fvol, attenuation, false);
648         target_chan->entnum = entnum;
649         target_chan->entchannel = entchannel;
650
651         SND_Spatialize(target_chan, false);
652
653         // if an identical sound has also been started this frame, offset the pos
654         // a bit to keep it from just making the first one louder
655         check = &channels[NUM_AMBIENTS];
656         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
657         {
658                 if (check == target_chan)
659                         continue;
660                 if (check->sfx == sfx && !check->pos)
661                 {
662                         skip = 0.1 * sfx->format.speed;
663                         if (skip > (int)sfx->total_length)
664                                 skip = (int)sfx->total_length;
665                         if (skip > 0)
666                                 skip = rand() % skip;
667                         target_chan->pos += skip;
668                         target_chan->end -= skip;
669                         break;
670                 }
671         }
672
673         return (target_chan - channels);
674 }
675
676 void S_StopChannel (unsigned int channel_ind)
677 {
678         channel_t *ch;
679
680         if (channel_ind >= total_channels)
681                 return;
682
683         ch = &channels[channel_ind];
684         if (ch->sfx != NULL)
685         {
686                 sfx_t *sfx = ch->sfx;
687
688                 if (sfx->fetcher != NULL)
689                 {
690                         snd_fetcher_endsb_t fetcher_endsb = sfx->fetcher->endsb;
691                         if (fetcher_endsb != NULL)
692                                 fetcher_endsb (ch);
693                 }
694
695                 // Remove the lock it holds
696                 S_UnlockSfx (sfx);
697
698                 ch->sfx = NULL;
699         }
700         ch->end = 0;
701 }
702
703
704 qboolean S_SetChannelFlag (unsigned int ch_ind, unsigned int flag, qboolean value)
705 {
706         if (ch_ind >= total_channels)
707                 return false;
708
709         if (flag != CHANNELFLAG_FORCELOOP &&
710                 flag != CHANNELFLAG_PAUSED &&
711                 flag != CHANNELFLAG_FULLVOLUME)
712                 return false;
713
714         if (value)
715                 channels[ch_ind].flags |= flag;
716         else
717                 channels[ch_ind].flags &= ~flag;
718
719         return true;
720 }
721
722 void S_StopSound(int entnum, int entchannel)
723 {
724         unsigned int i;
725
726         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
727                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
728                 {
729                         S_StopChannel (i);
730                         return;
731                 }
732 }
733
734 void S_StopAllSounds (void)
735 {
736         unsigned int i;
737         unsigned char *pbuf;
738
739         if (!shm)
740                 return;
741
742         for (i = 0; i < total_channels; i++)
743                 S_StopChannel (i);
744
745         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
746         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
747
748         // Clear sound buffer
749         pbuf = (unsigned char *)S_LockBuffer();
750         if (pbuf != NULL)
751         {
752                 int setsize = shm->samples * shm->format.width;
753                 int     clear = (shm->format.width == 1) ? 0x80 : 0;
754
755                 // FIXME: is it (still) true? (check with OSS and ALSA)
756                 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
757                 // reads the memory area before writing to it causing a seg fault
758                 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
759                 //memset(shm->buffer, clear, shm->samples * shm->format.width);
760                 while (setsize--)
761                         *pbuf++ = clear;
762
763                 S_UnlockBuffer ();
764         }
765 }
766
767 void S_PauseGameSounds (qboolean toggle)
768 {
769         unsigned int i;
770
771         for (i = 0; i < total_channels; i++)
772         {
773                 channel_t *ch;
774
775                 ch = &channels[i];
776                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
777                         S_SetChannelFlag (i, CHANNELFLAG_PAUSED, toggle);
778         }
779 }
780
781 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
782 {
783         channels[ch_ind].master_vol = fvol * 255;
784 }
785
786
787 /*
788 =================
789 S_StaticSound
790 =================
791 */
792 void S_StaticSound (sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
793 {
794         channel_t       *target_chan;
795
796         if (!shm || !sfx || nosound.integer)
797                 return;
798         if (!sfx->fetcher)
799         {
800                 Con_DPrintf ("S_StaticSound: \"%s\" hasn't been precached\n", sfx->name);
801                 return;
802         }
803
804         if (total_channels == MAX_CHANNELS)
805         {
806                 Con_Print("S_StaticSound: total_channels == MAX_CHANNELS\n");
807                 return;
808         }
809
810         target_chan = &channels[total_channels++];
811         S_PlaySfxOnChannel (sfx, target_chan, CHANNELFLAG_FORCELOOP, origin, fvol, attenuation, true);
812
813         SND_Spatialize (target_chan, true);
814 }
815
816
817 //=============================================================================
818
819 /*
820 ===================
821 S_UpdateAmbientSounds
822
823 ===================
824 */
825 void S_UpdateAmbientSounds (void)
826 {
827         int                     i;
828         float           vol;
829         int                     ambient_channel;
830         channel_t       *chan;
831         unsigned char           ambientlevels[NUM_AMBIENTS];
832
833         memset(ambientlevels, 0, sizeof(ambientlevels));
834         if (cl.worldmodel && cl.worldmodel->brush.AmbientSoundLevelsForPoint)
835                 cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_origin, ambientlevels, sizeof(ambientlevels));
836
837         // Calc ambient sound levels
838         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
839         {
840                 chan = &channels[ambient_channel];
841                 if (chan->sfx == NULL || chan->sfx->fetcher == NULL)
842                         continue;
843
844                 vol = ambientlevels[ambient_channel];
845                 if (vol < 8)
846                         vol = 0;
847
848                 // Don't adjust volume too fast
849                 if (chan->master_vol < vol)
850                 {
851                         chan->master_vol += host_realframetime * ambient_fade.value;
852                         if (chan->master_vol > vol)
853                                 chan->master_vol = vol;
854                 }
855                 else if (chan->master_vol > vol)
856                 {
857                         chan->master_vol -= host_realframetime * ambient_fade.value;
858                         if (chan->master_vol < vol)
859                                 chan->master_vol = vol;
860                 }
861
862                 for (i = 0;i < SND_LISTENERS;i++)
863                         chan->listener_volume[i] = (int)(chan->master_vol * ambient_level.value * snd_speakerlayout.listeners[i].ambientvolume);
864         }
865 }
866
867 #define SND_SPEAKERLAYOUTS 5
868 static speakerlayout_t snd_speakerlayouts[SND_SPEAKERLAYOUTS] =
869 {
870         {
871                 "surround71", 8,
872                 {
873                         {45, 0.2, 0.2, 0.5}, // front left
874                         {315, 0.2, 0.2, 0.5}, // front right
875                         {135, 0.2, 0.2, 0.5}, // rear left
876                         {225, 0.2, 0.2, 0.5}, // rear right
877                         {0, 0.2, 0.2, 0.5}, // front center
878                         {0, 0, 0, 0}, // lfe (we don't have any good lfe sound sources and it would take some filtering work to generate them (and they'd probably still be wrong), so...  no lfe)
879                         {90, 0.2, 0.2, 0.5}, // side left
880                         {180, 0.2, 0.2, 0.5}, // side right
881                 }
882         },
883         {
884                 "surround51", 6,
885                 {
886                         {45, 0.2, 0.2, 0.5}, // front left
887                         {315, 0.2, 0.2, 0.5}, // front right
888                         {135, 0.2, 0.2, 0.5}, // rear left
889                         {225, 0.2, 0.2, 0.5}, // rear right
890                         {0, 0.2, 0.2, 0.5}, // front center
891                         {0, 0, 0, 0}, // lfe (we don't have any good lfe sound sources and it would take some filtering work to generate them (and they'd probably still be wrong), so...  no lfe)
892                         {0, 0, 0, 0},
893                         {0, 0, 0, 0},
894                 }
895         },
896         {
897                 // these systems sometimes have a subwoofer as well, but it has no
898                 // channel of its own
899                 "surround40", 4,
900                 {
901                         {45, 0.3, 0.3, 0.8}, // front left
902                         {315, 0.3, 0.3, 0.8}, // front right
903                         {135, 0.3, 0.3, 0.8}, // rear left
904                         {225, 0.3, 0.3, 0.8}, // rear right
905                         {0, 0, 0, 0},
906                         {0, 0, 0, 0},
907                         {0, 0, 0, 0},
908                         {0, 0, 0, 0},
909                 }
910         },
911         {
912                 // these systems sometimes have a subwoofer as well, but it has no
913                 // channel of its own
914                 "stereo", 2,
915                 {
916                         {90, 0.5, 0.5, 1}, // side left
917                         {270, 0.5, 0.5, 1}, // side right
918                         {0, 0, 0, 0},
919                         {0, 0, 0, 0},
920                         {0, 0, 0, 0},
921                         {0, 0, 0, 0},
922                         {0, 0, 0, 0},
923                         {0, 0, 0, 0},
924                 }
925         },
926         {
927                 "mono", 1,
928                 {
929                         {0, 0, 1, 1}, // center
930                         {0, 0, 0, 0},
931                         {0, 0, 0, 0},
932                         {0, 0, 0, 0},
933                         {0, 0, 0, 0},
934                         {0, 0, 0, 0},
935                         {0, 0, 0, 0},
936                         {0, 0, 0, 0},
937                 }
938         }
939 };
940
941 /*
942 ============
943 S_Update
944
945 Called once each time through the main loop
946 ============
947 */
948 void S_Update(const matrix4x4_t *listenermatrix)
949 {
950         unsigned int i, j, total;
951         channel_t *ch, *combine;
952         matrix4x4_t basematrix, rotatematrix;
953
954         if (!snd_initialized.integer || (snd_blocked > 0) || !shm)
955                 return;
956
957         Matrix4x4_Invert_Simple(&basematrix, listenermatrix);
958         Matrix4x4_OriginFromMatrix(listenermatrix, listener_origin);
959
960         // select speaker layout
961         for (i = 0;i < SND_SPEAKERLAYOUTS - 1;i++)
962                 if (snd_speakerlayouts[i].channels == shm->format.channels)
963                         break;
964         snd_speakerlayout = snd_speakerlayouts[i];
965
966         // calculate the current matrices
967         for (j = 0;j < SND_LISTENERS;j++)
968         {
969                 Matrix4x4_CreateFromQuakeEntity(&rotatematrix, 0, 0, 0, 0, -snd_speakerlayout.listeners[j].yawangle, 0, 1);
970                 Matrix4x4_Concat(&listener_matrix[j], &rotatematrix, &basematrix);
971                 // I think this should now do this:
972                 //   1. create a rotation matrix for rotating by e.g. -90 degrees CCW
973                 //      (note: the matrix will rotate the OBJECT, not the VIEWER, so its
974                 //       angle has to be taken negative)
975                 //   2. create a transform which first rotates and moves its argument
976                 //      into the player's view coordinates (using basematrix which is
977                 //      an inverted "absolute" listener matrix), then applies the
978                 //      rotation matrix for the ear
979                 // Isn't Matrix4x4_CreateFromQuakeEntity a bit misleading because this
980                 // does not actually refer to an entity?
981         }
982
983         // update general area ambient sound sources
984         S_UpdateAmbientSounds ();
985
986         combine = NULL;
987
988         // update spatialization for static and dynamic sounds
989         ch = channels+NUM_AMBIENTS;
990         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
991         {
992                 if (!ch->sfx)
993                         continue;
994
995                 // respatialize channel
996                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);
997
998                 // try to combine static sounds with a previous channel of the same
999                 // sound effect so we don't mix five torches every frame
1000                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
1001                 {
1002                         // no need to merge silent channels
1003                         for (j = 0;j < SND_LISTENERS;j++)
1004                                 if (ch->listener_volume[j])
1005                                         break;
1006                         if (j == SND_LISTENERS)
1007                                 continue;
1008                         // if the last combine chosen isn't suitable, find a new one
1009                         if (!(combine && combine != ch && combine->sfx == ch->sfx))
1010                         {
1011                                 // search for one
1012                                 combine = NULL;
1013                                 for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;j < i;j++)
1014                                 {
1015                                         if (channels[j].sfx == ch->sfx)
1016                                         {
1017                                                 combine = channels + j;
1018                                                 break;
1019                                         }
1020                                 }
1021                         }
1022                         if (combine && combine != ch && combine->sfx == ch->sfx)
1023                         {
1024                                 for (j = 0;j < SND_LISTENERS;j++)
1025                                 {
1026                                         combine->listener_volume[j] += ch->listener_volume[j];
1027                                         ch->listener_volume[j] = 0;
1028                                 }
1029                         }
1030                 }
1031         }
1032
1033         sound_spatialized = true;
1034
1035         // debugging output
1036         if (snd_show.integer)
1037         {
1038                 total = 0;
1039                 ch = channels;
1040                 for (i=0 ; i<total_channels; i++, ch++)
1041                 {
1042                         if (ch->sfx)
1043                         {
1044                                 for (j = 0;j < SND_LISTENERS;j++)
1045                                         if (ch->listener_volume[j])
1046                                                 break;
1047                                 if (j < SND_LISTENERS)
1048                                         total++;
1049                         }
1050                 }
1051
1052                 Con_Printf("----(%u)----\n", total);
1053         }
1054
1055         S_Update_();
1056 }
1057
1058 void GetSoundtime(void)
1059 {
1060         int             samplepos;
1061         static  int             buffers;
1062         static  int             oldsamplepos;
1063         int             fullsamples;
1064
1065         fullsamples = shm->sampleframes;
1066
1067         // it is possible to miscount buffers if it has wrapped twice between
1068         // calls to S_Update.  Oh well.
1069         samplepos = SNDDMA_GetDMAPos();
1070
1071         if (samplepos < oldsamplepos)
1072         {
1073                 buffers++;                                      // buffer wrapped
1074
1075                 if (paintedtime > 0x40000000)
1076                 {       // time to chop things off to avoid 32 bit limits
1077                         buffers = 0;
1078                         paintedtime = fullsamples;
1079                         S_StopAllSounds ();
1080                 }
1081         }
1082         oldsamplepos = samplepos;
1083
1084         soundtime = buffers * fullsamples + samplepos / shm->format.channels;
1085 }
1086
1087 void S_ExtraUpdate (void)
1088 {
1089         if (snd_noextraupdate.integer || !sound_spatialized)
1090                 return;
1091
1092         S_Update_();
1093 }
1094
1095 void S_Update_(void)
1096 {
1097         unsigned        endtime;
1098
1099         if (!shm || (snd_blocked > 0))
1100                 return;
1101
1102         // Updates DMA time
1103         GetSoundtime();
1104
1105         // check to make sure that we haven't overshot
1106         if (paintedtime < soundtime)
1107                 paintedtime = soundtime;
1108
1109         // mix ahead of current position
1110         endtime = soundtime + _snd_mixahead.value * shm->format.speed;
1111         endtime = min(endtime, (unsigned int)(soundtime + shm->sampleframes));
1112
1113         S_PaintChannels (endtime);
1114
1115         SNDDMA_Submit ();
1116 }
1117
1118 /*
1119 ===============================================================================
1120
1121 console functions
1122
1123 ===============================================================================
1124 */
1125
1126 static void S_Play_Common(float fvol, float attenuation)
1127 {
1128         int     i, ch_ind;
1129         char name[MAX_QPATH];
1130         sfx_t   *sfx;
1131
1132         i = 1;
1133         while (i<Cmd_Argc())
1134         {
1135                 // Get the name
1136                 strlcpy(name, Cmd_Argv(i), sizeof(name));
1137                 if (!strrchr(name, '.'))
1138                         strlcat(name, ".wav", sizeof(name));
1139                 i++;
1140
1141                 // If we need to get the volume from the command line
1142                 if (fvol == -1.0f)
1143                 {
1144                         fvol = atof(Cmd_Argv(i));
1145                         i++;
1146                 }
1147
1148                 sfx = S_PrecacheSound (name, true, false);
1149                 if (sfx)
1150                 {
1151                         ch_ind = S_StartSound(-1, 0, sfx, listener_origin, fvol, attenuation);
1152
1153                         // Free the sfx if the file didn't exist
1154                         if (ch_ind < 0)
1155                                 S_FreeSfx (sfx, false);
1156                         else
1157                                 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1158                 }
1159         }
1160 }
1161
1162 void S_Play(void)
1163 {
1164         S_Play_Common (1.0f, 1.0f);
1165 }
1166
1167 void S_Play2(void)
1168 {
1169         S_Play_Common (1.0f, 0.0f);
1170 }
1171
1172 void S_PlayVol(void)
1173 {
1174         S_Play_Common (-1.0f, 0.0f);
1175 }
1176
1177 void S_SoundList(void)
1178 {
1179         unsigned int i;
1180         sfx_t   *sfx;
1181         int             size, total;
1182
1183         total = 0;
1184         for (sfx = known_sfx, i = 0; sfx != NULL; sfx = sfx->next, i++)
1185         {
1186                 if (sfx->fetcher != NULL)
1187                 {
1188                         size = (int)sfx->memsize;
1189                         total += size;
1190                         Con_Printf ("%c%c%c%c(%2db, %6s) %8i : %s\n",
1191                                                 (sfx->loopstart >= 0) ? 'L' : ' ',
1192                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
1193                                                 (sfx->locks > 0) ? 'K' : ' ',
1194                                                 (sfx->flags & SFXFLAG_PERMANENTLOCK) ? 'P' : ' ',
1195                                                 sfx->format.width * 8,
1196                                                 (sfx->format.channels == 1) ? "mono" : "stereo",
1197                                                 size,
1198                                                 sfx->name);
1199                 }
1200                 else
1201                         Con_Printf ("    (  unknown  ) unloaded : %s\n", sfx->name);
1202         }
1203         Con_Printf("Total resident: %i\n", total);
1204 }
1205
1206
1207 qboolean S_LocalSound (const char *sound)
1208 {
1209         sfx_t   *sfx;
1210         int             ch_ind;
1211
1212         if (!snd_initialized.integer || nosound.integer)
1213                 return true;
1214
1215         sfx = S_PrecacheSound (sound, true, false);
1216         if (!sfx)
1217         {
1218                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1219                 return false;
1220         }
1221
1222         // Local sounds must not be freed
1223         sfx->flags |= SFXFLAG_PERMANENTLOCK;
1224
1225         ch_ind = S_StartSound (cl.viewentity, 0, sfx, vec3_origin, 1, 0);
1226         if (ch_ind < 0)
1227                 return false;
1228
1229         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1230         return true;
1231 }