Debian Codegraph @

prboom2/src/SDL/i_sound.c

raw
1 /* Emacs style mode select -*- C -*-
2 *-----------------------------------------------------------------------------
3 *
4 *
5 * PrBoom: a Doom port merged with LxDoom and LSDLDoom
6 * based on BOOM, a modified and improved DOOM engine
7 * Copyright (C) 1999 by
8 * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman
9 * Copyright (C) 1999-2000 by
10 * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze
11 * Copyright 2005, 2006 by
12 * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko
13 *
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 * 02111-1307, USA.
28 *
29 * DESCRIPTION:
30 * System interface for sound.
31 *
32 *-----------------------------------------------------------------------------
33 */
34
35 #ifdef HAVE_CONFIG_H
36 #include "config.h"
37 #endif
38 #include <math.h>
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42
43 #include "SDL.h"
44 #include "SDL_audio.h"
45 #include "SDL_mutex.h"
46
47 #include "SDL_endian.h"
48
49 #include "SDL_version.h"
50 #include "SDL_thread.h"
51 #define USE_RWOPS
52 #include "SDL_mixer.h"
53
54 #include "z_zone.h"
55
56 #include "m_swap.h"
57 #include "i_sound.h"
58 #include "i_sndfile.h"
59 #include "m_misc.h"
60 #include "w_wad.h"
61 #include "lprintf.h"
62 #include "s_sound.h"
63
64 #include "doomdef.h"
65 #include "doomstat.h"
66 #include "doomtype.h"
67
68 #include "d_main.h"
69 #include "i_system.h"
70
71 //e6y
72 #include "e6y.h"
73
74 #include "dsda/ambient.h"
75 #include "dsda/settings.h"
76
77 static dboolean registered_non_rw = false;
78
79 // The number of internal mixing channels,
80 // the samples calculated for each mixing step,
81 // the size of the 16bit, 2 hardware channel (stereo)
82 // mixing buffer, and the samplerate of the raw data.
83
84 // The actual output device.
85 int audio_fd;
86
87 typedef struct
88 {
89 // SFX id of the playing sound effect.
90 // Used to catch duplicates (like chainsaw).
91 int id;
92 // The channel step amount...
93 unsigned int step;
94 // ... and a 0.16 bit remainder of last step.
95 unsigned int stepremainder;
96 unsigned int samplerate;
97 unsigned int bits;
98 // The channel data pointers, start and end.
99 const unsigned char *data;
100 const unsigned char *startdata;
101 const unsigned char *enddata;
102 // Time/gametic that the channel started playing,
103 // used to determine oldest, which automatically
104 // has lowest priority.
105 // In case number of active sounds exceeds
106 // available channels.
107 int starttime;
108 // left and right channel volume (0-127)
109 int leftvol;
110 int rightvol;
111 dboolean loop;
112 } channel_info_t;
113
114 channel_info_t channelinfo[MAX_CHANNELS];
115
116 // Pitch to stepping lookup.
117 int steptable[256];
118
119 // Volume lookups.
120 //int vol_lookup[128 * 256];
121
122 // NSM
123 static int dumping_sound = 0;
124
125
126 // lock for updating any params related to sfx
127 SDL_mutex *sfxmutex;
128 // lock for updating any params related to music
129 SDL_mutex *musmutex;
130
131 static int pitched_sounds;
132 int snd_samplerate; // samples per second
133 static int snd_samplecount;
134
135 static const char *snd_midiplayer;
136
137 void I_InitSoundParams(void)
138 {
139 pitched_sounds = dsda_IntConfig(dsda_config_pitched_sounds);
140
141 // TODO: can we reinitialize sound with new sample rate / count?
142 if (!snd_samplerate)
143 snd_samplerate = dsda_IntConfig(dsda_config_snd_samplerate);
144 if (!snd_samplecount)
145 snd_samplecount = dsda_IntConfig(dsda_config_snd_samplecount);
146 }
147
148 /* cph
149 * stopchan
150 * Stops a sound, unlocks the data
151 */
152
153 static void stopchan(int i)
154 {
155 if (channelinfo[i].data) /* cph - prevent excess unlocks */
156 {
157 channelinfo[i].data = NULL;
158 }
159 }
160
161 // [FG] support multi-channel samples by converting them to mono first
162 static Uint8 *ConvertAudioFormat(void **data, SDL_AudioSpec *sample, Uint32 *len)
163 {
164 SDL_AudioCVT cvt;
165
166 if (SDL_BuildAudioCVT(&cvt,
167 sample->format, sample->channels, sample->freq,
168 AUDIO_S16, 1, snd_samplerate) < 0)
169 {
170 lprintf(LO_WARN, "SDL_BuildAudioCVT: %s\n", SDL_GetError());
171 return NULL;
172 }
173
174 cvt.len = *len;
175 cvt.buf = Z_Malloc(cvt.len * cvt.len_mult);
176 memcpy(cvt.buf, *data, cvt.len);
177
178 if (SDL_ConvertAudio(&cvt) < 0)
179 {
180 Z_Free(cvt.buf);
181 lprintf(LO_WARN, "SDL_ConvertAudio: %s\n", SDL_GetError());
182 return NULL;
183 }
184
185 Z_Free(*data);
186
187 sample->channels = 1;
188 sample->format = AUDIO_S16;
189 sample->freq = snd_samplerate;
190 *data = cvt.buf;
191 *len = cvt.len_cvt;
192
193 return *data;
194 }
195
196 typedef struct snd_data_s
197 {
198 int sfxid;
199 unsigned char *data;
200 int samplelen;
201 int samplerate;
202 struct snd_data_s *next;
203 } snd_data_t;
204
205 #define SND_DATA_HASH_SIZE 32
206 static snd_data_t *snd_data_hash[SND_DATA_HASH_SIZE];
207
208 static snd_data_t *GetSndData(int sfxid, const unsigned char *data, size_t len)
209 {
210 int key;
211 snd_data_t *target = NULL;
212
213 key = (sfxid % SND_DATA_HASH_SIZE);
214
215 if (snd_data_hash[key])
216 {
217 snd_data_t *rover = snd_data_hash[key];
218
219 while (rover)
220 {
221 if (rover->sfxid == sfxid)
222 {
223 target = rover;
224 break;
225 }
226
227 rover = rover->next;
228 }
229 }
230
231 if (target == NULL)
232 {
233 SDL_AudioSpec sample;
234 void *sampledata;
235 Uint32 samplelen = (Uint32)len;
236
237 if (Load_SNDFile(data, &sample, &sampledata, &samplelen) == NULL)
238 {
239 lprintf(LO_WARN, "Can't open sfx file: %s\n", S_sfx[sfxid].name);
240 return NULL;
241 }
242
243 if (sample.channels != 1 || sample.freq != snd_samplerate
244 || SDL_AUDIO_ISFLOAT(sample.format))
245 {
246 if (ConvertAudioFormat(&sampledata, &sample, &samplelen) == NULL)
247 {
248 Z_Free(sampledata);
249 return NULL;
250 }
251 }
252
253 target = Z_Malloc(sizeof(*target));
254
255 target->sfxid = sfxid;
256 target->data = sampledata;
257 target->samplelen = samplelen;
258 target->samplerate = sample.freq;
259
260 // use head insertion
261 target->next = snd_data_hash[key];
262 snd_data_hash[key] = target;
263 }
264
265 return target;
266 }
267
268 #define FADETIME 1000 // microseconds
269
270 static void FadeInOutMono16(short *data, int len, int rate)
271 {
272 const int fadelen = rate * FADETIME / 1000000;
273 int i;
274
275 if (len < fadelen)
276 return;
277
278 if (data[0] != 0)
279 {
280 for (i = 0; i < fadelen; i++)
281 {
282 data[i] = data[i] * i / fadelen;
283 }
284 }
285
286 if (data[len - 1] != 0)
287 {
288 for (i = 0; i < fadelen; i++)
289 {
290 data[len - 1 - i] = data[len - 1 - i] * i / fadelen;
291 }
292 }
293 }
294
295 static void FadeInOutMono8(byte *data, int len, int rate)
296 {
297 const int fadelen = rate * FADETIME / 1000000;
298 int i;
299
300 if (len < fadelen)
301 return;
302
303 if (data[0] != 128)
304 {
305 for (i = 0; i < fadelen; i++)
306 {
307 data[i] = (data[i] - 128) * i / fadelen + 128;
308 }
309 }
310
311 if (data[len - 1] != 128)
312 {
313 for (i = 0; i < fadelen; i++)
314 {
315 data[len - 1 - i] = (data[len - 1 - i] - 128) * i / fadelen + 128;
316 }
317 }
318 }
319
320 #define DMXHDRSIZE 8
321 #define DMXPADSIZE 16
322
323 INLINE static int GetDMXSampleRate(const byte *data)
324 {
325 return ((data[3] << 8) | data[2]);
326 }
327
328 INLINE static dboolean IsValidDMXSound(int dmx_len, int len)
329 {
330 // Don't play DMX format sound lumps that think they're longer than they
331 // really are, only contain padding, or are shorter than the padding size.
332 return (dmx_len <= len - DMXHDRSIZE && dmx_len > DMXPADSIZE * 2);
333 }
334
335 INLINE static int GetDMXLength(const byte *data)
336 {
337 // Read the encoded number of samples. This value includes padding.
338 return ((data[7] << 24) | (data[6] << 16) | (data[5] << 8) | data[4]);
339 }
340
341 INLINE static dboolean IsDMXSound(const byte *data, int len)
342 {
343 return len > DMXHDRSIZE && data[0] == 0x03 && data[1] == 0x00;
344 }
345
346 void I_CacheSounds(void)
347 {
348 int id;
349 for (id = 1; id < num_sfx; id++)
350 {
351 int lump = I_GetSfxLumpNum(&S_sfx[id]);
352 if (lump >= 0)
353 {
354 const byte *data = W_LumpByNum(lump);
355 int len = W_LumpLength(lump);
356
357 if (IsDMXSound(data, len))
358 {
359 int dmx_len = GetDMXLength(data);
360
361 if (IsValidDMXSound(dmx_len, len) && !dsda_IsLoopingAmbientSFX(id))
362 {
363 const int dmx_rate = GetDMXSampleRate(data);
364 byte *dmx_data = W_GetModifiableLumpData(lump);
365 dmx_data = &dmx_data[DMXHDRSIZE + DMXPADSIZE];
366 dmx_len -= DMXPADSIZE * 2;
367 FadeInOutMono8(dmx_data, dmx_len, dmx_rate);
368 }
369 }
370 else
371 {
372 snd_data_t *snd_data = GetSndData(id, data, len);
373
374 if (snd_data && !dsda_IsLoopingAmbientSFX(id))
375 {
376 len = snd_data->samplelen / sizeof(short);
377 FadeInOutMono16((short *)snd_data->data, len, snd_data->samplerate);
378 }
379 }
380 }
381 }
382 }
383
384 //
385 // This function adds a sound to the
386 // list of currently active sounds,
387 // which is maintained as a given number
388 // (eight, usually) of internal channels.
389 // Returns a handle.
390 //
391
392 static int addsfx(int sfxid, int channel, const channel_info_t *cinfo)
393 {
394 channel_info_t *ci = channelinfo + channel;
395
396 stopchan(channel);
397
398 ci->data = cinfo->data;
399 ci->enddata = cinfo->enddata;
400 ci->samplerate = cinfo->samplerate;
401 ci->bits = cinfo->bits;
402
403 ci->stepremainder = 0;
404 // Should be gametic, I presume.
405 ci->starttime = gametic;
406
407 ci->startdata = ci->data;
408
409 // Preserve sound SFX id,
410 // e.g. for avoiding duplicates of chainsaw.
411 ci->id = sfxid;
412
413 return channel;
414 }
415
416 static int getSliceSize(void)
417 {
418 int limit, n;
419
420 if (snd_samplecount >= 32)
421 return snd_samplecount * snd_samplerate / 11025;
422
423 limit = snd_samplerate / TICRATE;
424
425 // Try all powers of two, not exceeding the limit.
426
427 for (n = 0; ; ++n)
428 {
429 // 2^n <= limit < 2^n+1 ?
430
431 if ((1 << (n + 1)) > limit)
432 {
433 return (1 << n);
434 }
435 }
436
437 // Should never happen?
438
439 return 1024;
440 }
441
442 static void updateSoundParams(int handle, sfx_params_t *params)
443 {
444 int slot = handle;
445 int rightvol;
446 int leftvol;
447
448 #ifdef RANGECHECK
449 if ((handle < 0) || (handle >= MAX_CHANNELS))
450 I_Error("I_UpdateSoundParams: handle out of range");
451 #endif
452
453 channelinfo[slot].loop = params->loop;
454
455 // Set stepping
456 // MWM 2000-12-24: Calculates proportion of channel samplerate
457 // to global samplerate for mixing purposes.
458 // Patched to shift left *then* divide, to minimize roundoff errors
459 // as well as to use SAMPLERATE as defined above, not to assume 11025 Hz
460 if (pitched_sounds)
461 channelinfo[slot].step = (unsigned int)(((uint64_t)channelinfo[slot].samplerate * steptable[params->pitch]) / snd_samplerate);
462 else
463 channelinfo[slot].step = ((channelinfo[slot].samplerate << 16) / snd_samplerate);
464
465 // Separation, that is, orientation/stereo.
466 // range is: 1 - 256
467 params->separation += 1;
468
469 // Per left/right channel.
470 // x^2 separation,
471 // adjust volume properly.
472 leftvol = params->volume - ((params->volume * params->separation * params->separation) >> 16);
473 params->separation = params->separation - 257;
474 rightvol = params->volume - ((params->volume * params->separation * params->separation) >> 16);
475
476 // Sanity check, clamp volume.
477 if (rightvol < 0 || rightvol > 127)
478 {
479 rightvol = rightvol < 0 ? 0 : 127;
480 lprintf(LO_WARN, "rightvol out of bounds\n");
481 }
482
483 if (leftvol < 0 || leftvol > 127)
484 {
485 leftvol = leftvol < 0 ? 0 : 127;
486 lprintf(LO_WARN, "leftvol out of bounds\n");
487 }
488
489 // Get the proper lookup table piece
490 // for this volume level???
491 channelinfo[slot].leftvol = leftvol;
492 channelinfo[slot].rightvol = rightvol;
493 }
494
495 void I_UpdateSoundParams(int handle, sfx_params_t *params)
496 {
497 SDL_LockMutex (sfxmutex);
498 updateSoundParams(handle, params);
499 SDL_UnlockMutex (sfxmutex);
500 }
501
502 //
503 // SFX API
504 // Note: this was called by S_Init.
505 // However, whatever they did in the
506 // old DPMS based DOS version, this
507 // were simply dummies in the Linux
508 // version.
509 // See soundserver initdata().
510 //
511 void I_SetChannels(void)
512 {
513 // Init internal lookups (raw data, mixing buffer, channels).
514 // This function sets up internal lookups used during
515 // the mixing process.
516 int i;
517 //int j;
518
519 int *steptablemid = steptable + 128;
520
521 // Okay, reset internal mixing channels to zero.
522 for (i = 0; i < MAX_CHANNELS; i++)
523 {
524 memset(&channelinfo[i], 0, sizeof(channel_info_t));
525 }
526
527 // This table provides step widths for pitch parameters.
528 for (i = -128 ; i < 128 ; i++)
529 steptablemid[i] = (int)(pow(1.2, (double)i / 64.0) * 65536.0);
530
531
532 // Generates volume lookup tables
533 // which also turn the unsigned samples
534 // into signed samples.
535 /*
536 for (i = 0 ; i < 128 ; i++)
537 for (j = 0 ; j < 256 ; j++)
538 {
539 // proff - made this a little bit softer, because with
540 // full volume the sound clipped badly
541 vol_lookup[i * 256 + j] = (i * (j - 128) * 256) / 191;
542 //vol_lookup[i*256+j] = (i*(j-128)*256)/127;
543 }
544 */
545 }
546
547 //
548 // Retrieve the raw data lump index
549 // for a given SFX name.
550 //
551 int I_GetSfxLumpNum(sfxinfo_t *sfx)
552 {
553 if (sfx->link)
554 sfx = sfx->link;
555
556 if (!sfx->name)
557 return LUMP_NOT_FOUND;
558
559 return W_CheckNumForName(sfx->name); //e6y: make missing sounds non-fatal
560 }
561
562 //
563 // Starting a sound means adding it
564 // to the current list of active sounds
565 // in the internal channels.
566 // As the SFX info struct contains
567 // e.g. a pointer to the raw data,
568 // it is ignored.
569 // As our sound handling does not handle
570 // priority, it is ignored.
571 // Pitching (that is, increased speed of playback)
572 // is set, but currently not used by mixing.
573 //
574 int I_StartSound(int id, int channel, sfx_params_t *params)
575 {
576 const unsigned char *data;
577 int lump;
578 size_t len;
579 snd_data_t *snd_data = NULL;
580 channel_info_t cinfo = {0};
581
582 if ((channel < 0) || (channel >= MAX_CHANNELS))
583 #ifdef RANGECHECK
584 I_Error("I_StartSound: handle out of range");
585 #else
586 return -1;
587 #endif
588
589 lump = S_sfx[id].lumpnum;
590
591 // We will handle the new SFX.
592 // Set pointer to raw data.
593 len = W_LumpLength(lump);
594
595 // e6y: Crash with zero-length sounds.
596 // Example wad: dakills (http://www.doomworld.com/idgames/index.php?id=2803)
597 // The entries DSBSPWLK, DSBSPACT, DSSWTCHN and DSSWTCHX are all zero-length sounds
598 if (len <= DMXHDRSIZE) return -1;
599
600 // do the lump caching outside the SDL_LockAudio/SDL_UnlockAudio pair
601 // use locking which makes sure the sound data is in a malloced area and
602 // not in a memory mapped one
603 data = (const unsigned char *)W_LockLumpNum(lump);
604
605 if (IsDMXSound(data, len))
606 {
607 const int dmx_len = GetDMXLength(data);
608
609 if (IsValidDMXSound(dmx_len, len))
610 {
611 cinfo.data = &data[DMXHDRSIZE + DMXPADSIZE];
612 cinfo.enddata = &cinfo.data[dmx_len - DMXPADSIZE * 2 - 1];
613 cinfo.samplerate = GetDMXSampleRate(data);
614 cinfo.bits = 8;
615 }
616 else
617 {
618 return -1;
619 }
620 }
621 else
622 {
623 snd_data = GetSndData(id, data, len);
624
625 if (snd_data)
626 {
627 cinfo.data = snd_data->data;
628 cinfo.enddata = &cinfo.data[snd_data->samplelen - 1];
629 cinfo.samplerate = snd_data->samplerate;
630 cinfo.bits = 16;
631 }
632 else
633 {
634 return -1;
635 }
636 }
637
638 SDL_LockMutex (sfxmutex);
639
640 // Returns a handle (not used).
641 addsfx(id, channel, &cinfo);
642 updateSoundParams(channel, params);
643
644 SDL_UnlockMutex (sfxmutex);
645
646
647 return channel;
648 }
649
650
651
652 void I_StopSound (int handle)
653 {
654 #ifdef RANGECHECK
655 if ((handle < 0) || (handle >= MAX_CHANNELS))
656 I_Error("I_StopSound: handle out of range");
657 #endif
658
659 SDL_LockMutex (sfxmutex);
660 stopchan(handle);
661 SDL_UnlockMutex (sfxmutex);
662 }
663
664
665 dboolean I_SoundIsPlaying(int handle)
666 {
667 #ifdef RANGECHECK
668 if ((handle < 0) || (handle >= MAX_CHANNELS))
669 I_Error("I_SoundIsPlaying: handle out of range");
670 #endif
671
672 return channelinfo[handle].data != NULL;
673 }
674
675
676 dboolean I_AnySoundStillPlaying(void)
677 {
678 dboolean result = false;
679 int i;
680
681 for (i = 0; i < MAX_CHANNELS; i++)
682 result |= channelinfo[i].data != NULL;
683
684 return result;
685 }
686
687
688 //
689 // This function loops all active (internal) sound
690 // channels, retrieves a given number of samples
691 // from the raw sound data, modifies it according
692 // to the current (internal) channel parameters,
693 // mixes the per channel samples into the given
694 // mixing buffer, and clamping it to the allowed
695 // range.
696 //
697 // This function currently supports only 16bit.
698 //
699
700 static void UpdateMusic (void *buff, unsigned nsamp);
701
702 static void I_UpdateSound(void *unused, Uint8 *stream, int len)
703 {
704 // Mix current sound data.
705 // Data, from raw sound, for right and left.
706 // register unsigned char sample;
707 register int dl;
708 register int dr;
709
710 // Pointers in audio stream, left, right, end.
711 signed short *leftout;
712 signed short *rightout;
713 signed short *leftend;
714 // Step in stream, left and right, thus two.
715 int step;
716
717 // Mixing channel index.
718 int chan;
719
720 if (snd_midiplayer == NULL) // This is but a temporary fix. Please do remove after a more definitive one!
721 memset(stream, 0, len);
722
723 // NSM: when dumping sound, ignore the callback calls and only
724 // service dumping calls
725 if (dumping_sound && unused != (void *) 0xdeadbeef)
726 return;
727
728 // do music update
729 if (registered_non_rw)
730 {
731 SDL_LockMutex (musmutex);
732 UpdateMusic (stream, len / 4);
733 SDL_UnlockMutex (musmutex);
734 }
735
736 SDL_LockMutex (sfxmutex);
737 // Left and right channel
738 // are in audio stream, alternating.
739 leftout = (signed short *)stream;
740 rightout = ((signed short *)stream) + 1;
741 step = 2;
742
743 // Determine end, for left channel only
744 // (right channel is implicit).
745 leftend = leftout + (len / 4) * step;
746
747 // Mix sounds into the mixing buffer.
748 // Loop over step*SAMPLECOUNT,
749 // that is 512 values for two channels.
750 while (leftout != leftend)
751 {
752 // Reset left/right value.
753 //dl = 0;
754 //dr = 0;
755 dl = *leftout;
756 dr = *rightout;
757
758 // Love thy L2 chache - made this a loop.
759 // Now more channels could be set at compile time
760 // as well. Thus loop those channels.
761 for ( chan = 0; chan < numChannels; chan++ )
762 {
763 channel_info_t *ci = channelinfo + chan;
764
765 // Check channel, if active.
766 if (ci->data)
767 {
768 int s;
769 // Get the raw data from the channel.
770 // no filtering
771 //int s = channelinfo[chan].data[0] * 0x10000 - 0x800000;
772
773 // linear filtering
774 // the old SRC did linear interpolation back into 8 bit, and then expanded to 16 bit.
775 // this does interpolation and 8->16 at same time, allowing slightly higher quality
776 if (ci->bits == 16)
777 {
778 s = (short)(ci->data[0] | (ci->data[1] << 8)) * (255 - (ci->stepremainder >> 8))
779 + (short)(ci->data[2] | (ci->data[3] << 8)) * (ci->stepremainder >> 8);
780 }
781 else
782 {
783 s = ((unsigned int)ci->data[0] * (0x10000 - ci->stepremainder))
784 + ((unsigned int)ci->data[1] * (ci->stepremainder))
785 - 0x800000; // convert to signed
786 }
787
788
789 // Add left and right part
790 // for this channel (sound)
791 // to the current data.
792 // Adjust volume accordingly.
793
794 // full loudness (vol=127) is actually 127/191
795
796 dl += ci->leftvol * s / 49152; // >> 15;
797 dr += ci->rightvol * s / 49152; // >> 15;
798
799 // Increment index ???
800 ci->stepremainder += ci->step;
801
802 // MSB is next sample???
803 if (ci->bits == 16)
804 ci->data += (ci->stepremainder >> 16) * 2;
805 else
806 ci->data += ci->stepremainder >> 16;
807
808 // Limit to LSB???
809 ci->stepremainder &= 0xffff;
810
811 // Check whether we are done.
812 if (ci->data >= ci->enddata)
813 {
814 if (ci->loop)
815 ci->data = ci->startdata;
816 else
817 stopchan(chan);
818 }
819 }
820 }
821
822 // Clamp to range. Left hardware channel.
823 // Has been char instead of short.
824 // if (dl > 127) *leftout = 127;
825 // else if (dl < -128) *leftout = -128;
826 // else *leftout = dl;
827
828 if (dl > SHRT_MAX)
829 *leftout = SHRT_MAX;
830 else if (dl < SHRT_MIN)
831 *leftout = SHRT_MIN;
832 else
833 *leftout = (signed short)dl;
834
835 // Same for right hardware channel.
836 if (dr > SHRT_MAX)
837 *rightout = SHRT_MAX;
838 else if (dr < SHRT_MIN)
839 *rightout = SHRT_MIN;
840 else
841 *rightout = (signed short)dr;
842
843 // Increment current pointers in stream
844 leftout += step;
845 rightout += step;
846 }
847 SDL_UnlockMutex (sfxmutex);
848 }
849
850 static dboolean sound_was_initialized;
851
852 void I_ShutdownSound(void)
853 {
854 if (sound_was_initialized)
855 {
856 Mix_CloseAudio();
857 SDL_CloseAudio();
858
859 sound_was_initialized = false;
860
861 if (sfxmutex)
862 {
863 SDL_DestroyMutex (sfxmutex);
864 sfxmutex = NULL;
865 }
866 }
867 }
868
869 void I_InitSound(void)
870 {
871 int audio_rate;
872 int audio_channels;
873 int audio_buffers;
874
875 I_InitSoundParams();
876
877 if (sound_was_initialized || (nomusicparm && nosfxparm))
878 return;
879
880 if (SDL_InitSubSystem(SDL_INIT_AUDIO))
881 {
882 lprintf(LO_WARN, "Couldn't initialize SDL audio (%s))\n", SDL_GetError());
883 nosfxparm = true;
884 nomusicparm = true;
885 return;
886 }
887
888 // Secure and configure sound device first.
889 lprintf(LO_DEBUG, "I_InitSound: ");
890
891 audio_rate = snd_samplerate;
892 audio_channels = 2;
893 audio_buffers = getSliceSize();
894
895 if (Mix_OpenAudioDevice(audio_rate, MIX_DEFAULT_FORMAT, audio_channels, audio_buffers,
896 NULL, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE) < 0)
897 {
898 lprintf(LO_DEBUG, "couldn't open audio with desired format (%s)\n", SDL_GetError());
899 nosfxparm = true;
900 nomusicparm = true;
901 return;
902 }
903
904 // [FG] feed actual sample frequency back into config variable
905 Mix_QuerySpec(&snd_samplerate, NULL, NULL);
906
907 sound_was_initialized = true;
908
909 Mix_SetPostMix(I_UpdateSound, NULL);
910
911 lprintf(LO_DEBUG, " configured audio device with %d samples/slice\n", audio_buffers);
912
913 I_AtExit(I_ShutdownSound, true, "I_ShutdownSound", exit_priority_normal);
914
915 sfxmutex = SDL_CreateMutex ();
916
917 if (!nomusicparm)
918 I_InitMusic();
919
920 lprintf(LO_DEBUG, "I_InitSound: sound module ready\n");
921 SDL_PauseAudio(0);
922 }
923
924
925 // NSM sound capture routines
926
927 // silences sound output, and instead allows sound capture to work
928 // call this before sound startup
929 void I_SetSoundCap (void)
930 {
931 dumping_sound = 1;
932 }
933
934 // grabs len samples of audio (16 bit interleaved)
935 unsigned char *I_GrabSound (int len)
936 {
937 static unsigned char *buffer = NULL;
938 static size_t buffer_size = 0;
939 size_t size;
940
941 if (!dumping_sound)
942 return NULL;
943
944 size = len * 4;
945 if (!buffer || size > buffer_size)
946 {
947 buffer_size = size * 4;
948 buffer = (unsigned char *)Z_Realloc (buffer, buffer_size);
949 }
950
951 if (buffer)
952 {
953 memset (buffer, 0, size);
954 I_UpdateSound ((void *) 0xdeadbeef, buffer, size);
955 }
956 return buffer;
957 }
958
959
960
961
962 // NSM helper routine for some of the streaming audio
963 void I_ResampleStream (void *dest, unsigned nsamp, void (*proc) (void *dest, unsigned nsamp), unsigned sratein, unsigned srateout)
964 { // assumes 16 bit signed interleaved stereo
965
966 unsigned i;
967 int j = 0;
968
969 short *sout = (short*)dest;
970
971 static short *sin = NULL;
972 static unsigned sinsamp = 0;
973
974 static unsigned remainder = 0;
975 unsigned step = (sratein << 16) / (unsigned) srateout;
976
977 unsigned nreq = (step * nsamp + remainder) >> 16;
978
979 if (nreq > sinsamp)
980 {
981 sin = (short*)Z_Realloc (sin, (nreq + 1) * 4);
982 if (!sinsamp) // avoid pop when first starting stream
983 sin[0] = sin[1] = 0;
984 sinsamp = nreq;
985 }
986
987 proc (sin + 2, nreq);
988
989 for (i = 0; i < nsamp; i++)
990 {
991 *sout++ = ((unsigned) sin[j + 0] * (0x10000 - remainder) +
992 (unsigned) sin[j + 2] * remainder) >> 16;
993 *sout++ = ((unsigned) sin[j + 1] * (0x10000 - remainder) +
994 (unsigned) sin[j + 3] * remainder) >> 16;
995 remainder += step;
996 j += remainder >> 16 << 1;
997 remainder &= 0xffff;
998 }
999 sin[0] = sin[nreq * 2];
1000 sin[1] = sin[nreq * 2 + 1];
1001 }
1002
1003 //
1004 // MUSIC API.
1005 //
1006
1007 static void UpdateMusic (void *buff, unsigned nsamp);
1008 static int RegisterSong (const void *data, size_t len);
1009 static int RegisterSongEx (const void *data, size_t len, int try_mus2mid);
1010 static void UnRegisterSong(int handle);
1011 static void StopSong(int handle);
1012 static void ResumeSong (int handle);
1013 static void PauseSong (int handle);
1014 static void PlaySong(int handle, int looping);
1015
1016 #include "mus2mid.h"
1017
1018 #include "MUSIC/musicplayer.h"
1019 #include "MUSIC/oplplayer.h"
1020 #include "MUSIC/madplayer.h"
1021 #include "MUSIC/xmpplayer.h"
1022 #include "MUSIC/flplayer.h"
1023 #include "MUSIC/vorbisplayer.h"
1024 #include "MUSIC/portmidiplayer.h"
1025
1026 static Mix_Music *music[2] = { NULL, NULL };
1027
1028 // Some tracks are directly streamed from the RWops;
1029 // we need to free them in the end
1030 static SDL_RWops *rwops_stream = NULL;
1031
1032 // note that the "handle" passed around by s_sound is ignored
1033 // however, a handle is maintained for the individual music players
1034
1035 static const music_player_t *music_players[] =
1036 { // until some ui work is done, the order these appear is the autodetect order.
1037 // of particular importance: things that play mus have to be last, because
1038 // mus2midi very often succeeds even on garbage input
1039 &vorb_player, // vorbisplayer.h
1040 &mp_player, // madplayer.h
1041 &xmp_player, // xmpplayer.h
1042 &fl_player, // flplayer.h
1043 &opl_synth_player, // oplplayer.h
1044 &pm_player, // portmidiplayer.h
1045 NULL
1046 };
1047 #define NUM_MUS_PLAYERS ((int)(sizeof (music_players) / sizeof (music_player_t *) - 1))
1048
1049 static int music_player_was_init[NUM_MUS_PLAYERS];
1050
1051 #define PLAYER_VORBIS "vorbis player"
1052 #define PLAYER_MAD "mad mp3 player"
1053 #define PLAYER_XMP "libxmp tracker player"
1054 #define PLAYER_FLUIDSYNTH "fluidsynth midi player"
1055 #define PLAYER_OPL "opl synth player"
1056 #define PLAYER_PORTMIDI "portmidi midi player"
1057
1058 // order in which players are to be tried
1059 char music_player_order[NUM_MUS_PLAYERS][200] =
1060 {
1061 PLAYER_VORBIS,
1062 PLAYER_MAD,
1063 PLAYER_XMP,
1064 PLAYER_FLUIDSYNTH,
1065 PLAYER_OPL,
1066 PLAYER_PORTMIDI,
1067 };
1068
1069 const char *midiplayers[midi_player_last + 1] = {
1070 "fluidsynth", "opl", "portmidi", NULL };
1071
1072 static int current_player = -1;
1073 static const void *music_handle = NULL;
1074
1075 static void *mus2mid_conversion_data = NULL;
1076
1077 void I_ShutdownMusic(void)
1078 {
1079 int i;
1080 S_StopMusic ();
1081
1082 for (i = 0; music_players[i]; i++)
1083 {
1084 if (music_player_was_init[i])
1085 music_players[i]->shutdown ();
1086 }
1087
1088 if (musmutex)
1089 {
1090 SDL_DestroyMutex (musmutex);
1091 musmutex = NULL;
1092 }
1093 }
1094
1095 void I_InitMusic(void)
1096 {
1097 int i;
1098 musmutex = SDL_CreateMutex ();
1099
1100 // todo not so greedy
1101 for (i = 0; music_players[i]; i++)
1102 music_player_was_init[i] = music_players[i]->init (snd_samplerate);
1103
1104 I_AtExit(I_ShutdownMusic, true, "I_ShutdownMusic", exit_priority_normal);
1105 }
1106
1107 // Derived value (not saved, accounts for muted music)
1108 static int music_volume;
1109
1110 void I_ResetMusicVolume(void)
1111 {
1112 snd_MusicVolume = dsda_IntConfig(dsda_config_music_volume);
1113
1114 if (nomusicparm)
1115 return;
1116
1117 if (dsda_MuteMusic())
1118 music_volume = 0;
1119 else
1120 music_volume = snd_MusicVolume;
1121
1122 Mix_VolumeMusic(music_volume * 8);
1123
1124 if (music_handle)
1125 {
1126 SDL_LockMutex(musmutex);
1127 music_players[current_player]->setvolume(music_volume);
1128 SDL_UnlockMutex(musmutex);
1129 }
1130 }
1131
1132 void I_PlaySong(int handle, int looping)
1133 {
1134 if (registered_non_rw)
1135 {
1136 PlaySong (handle, looping);
1137 return;
1138 }
1139
1140 if ( music[handle] ) {
1141 //Mix_FadeInMusic(music[handle], looping ? -1 : 0, 500);
1142 Mix_PlayMusic(music[handle], looping ? -1 : 0);
1143
1144 // haleyjd 10/28/05: make sure volume settings remain consistent
1145 I_ResetMusicVolume();
1146 }
1147 }
1148
1149 void I_PauseSong (int handle)
1150 {
1151 if (registered_non_rw)
1152 {
1153 PauseSong (handle);
1154 return;
1155 }
1156
1157 switch (dsda_IntConfig(dsda_config_mus_pause_opt))
1158 {
1159 case 0:
1160 I_StopSong(handle);
1161 break;
1162 case 1:
1163 switch (Mix_GetMusicType(NULL))
1164 {
1165 case MUS_NONE:
1166 break;
1167 default:
1168 Mix_PauseMusic();
1169 break;
1170 }
1171 break;
1172 }
1173 // Default - let music continue
1174 }
1175
1176 void I_ResumeSong (int handle)
1177 {
1178 if (registered_non_rw)
1179 {
1180 ResumeSong (handle);
1181 return;
1182 }
1183
1184 switch (dsda_IntConfig(dsda_config_mus_pause_opt)) {
1185 case 0:
1186 I_PlaySong(handle,1);
1187 break;
1188 case 1:
1189 switch (Mix_GetMusicType(NULL))
1190 {
1191 case MUS_NONE:
1192 break;
1193 default:
1194 Mix_ResumeMusic();
1195 break;
1196 }
1197 break;
1198 }
1199 /* Otherwise, music wasn't stopped */
1200 }
1201
1202 void I_StopSong(int handle)
1203 {
1204 if (registered_non_rw)
1205 {
1206 StopSong (handle);
1207 return;
1208 }
1209
1210 // halt music playback
1211 Mix_HaltMusic();
1212 }
1213
1214 void I_UnRegisterSong(int handle)
1215 {
1216 if (registered_non_rw)
1217 {
1218 UnRegisterSong (handle);
1219 return;
1220 }
1221
1222 if ( music[handle] ) {
1223 Mix_FreeMusic(music[handle]);
1224 music[handle] = NULL;
1225
1226 // Free RWops
1227 if (rwops_stream != NULL)
1228 {
1229 //SDL_FreeRW(rwops_stream);
1230 rwops_stream = NULL;
1231 }
1232 }
1233 }
1234
1235 int I_RegisterSong(const void *data, size_t len)
1236 {
1237 registered_non_rw = false;
1238
1239 if (RegisterSong(data, len))
1240 return 0;
1241
1242 // e6y: new logic by me
1243 // Now you can hear title music in deca.wad
1244 // http://www.doomworld.com/idgames/index.php?id=8808
1245 // Ability to use mp3 and ogg as inwad lump
1246
1247 music[0] = NULL;
1248
1249 rwops_stream = SDL_RWFromConstMem(data, len);
1250 if (rwops_stream)
1251 {
1252 music[0] = Mix_LoadMUS_RW(rwops_stream, SDL_FALSE);
1253 }
1254
1255 // Failed to load
1256 if (!music[0])
1257 {
1258 // Conversion failed, free everything
1259 if (rwops_stream != NULL)
1260 {
1261 //SDL_FreeRW(rwops_stream);
1262 rwops_stream = NULL;
1263 }
1264
1265 lprintf(LO_ERROR, "Error loading song: %s\n", Mix_GetError());
1266 }
1267
1268 return (0);
1269 }
1270
1271 static void PlaySong(int handle, int looping)
1272 {
1273 if (music_handle)
1274 {
1275 SDL_LockMutex (musmutex);
1276 music_players[current_player]->play (music_handle, looping);
1277 music_players[current_player]->setvolume (music_volume);
1278 SDL_UnlockMutex (musmutex);
1279 }
1280 }
1281
1282 static void PauseSong (int handle)
1283 {
1284 if (!music_handle)
1285 return;
1286
1287 SDL_LockMutex (musmutex);
1288 switch (dsda_IntConfig(dsda_config_mus_pause_opt))
1289 {
1290 case 0:
1291 music_players[current_player]->stop ();
1292 break;
1293 case 1:
1294 music_players[current_player]->pause ();
1295 break;
1296 default: // Default - let music continue
1297 break;
1298 }
1299 SDL_UnlockMutex (musmutex);
1300 }
1301
1302 static void ResumeSong (int handle)
1303 {
1304 if (!music_handle)
1305 return;
1306
1307 SDL_LockMutex (musmutex);
1308 switch (dsda_IntConfig(dsda_config_mus_pause_opt))
1309 {
1310 case 0: // i'm not sure why we can guarantee looping=true here,
1311 // but that's what the old code did
1312 music_players[current_player]->play (music_handle, 1);
1313 break;
1314 case 1:
1315 music_players[current_player]->resume ();
1316 break;
1317 default: // Default - music was never stopped
1318 break;
1319 }
1320 SDL_UnlockMutex (musmutex);
1321 }
1322
1323 static void StopSong(int handle)
1324 {
1325 if (music_handle)
1326 {
1327 SDL_LockMutex (musmutex);
1328 music_players[current_player]->stop ();
1329 SDL_UnlockMutex (musmutex);
1330 }
1331 }
1332
1333 static void UnRegisterSong(int handle)
1334 {
1335 if (music_handle)
1336 {
1337 SDL_LockMutex (musmutex);
1338 music_players[current_player]->unregistersong (music_handle);
1339 music_handle = NULL;
1340 if (mus2mid_conversion_data)
1341 {
1342 Z_Free (mus2mid_conversion_data);
1343 mus2mid_conversion_data = NULL;
1344 }
1345 SDL_UnlockMutex (musmutex);
1346 }
1347 }
1348
1349 // returns 1 on success, 0 on failure
1350 static int RegisterSongEx (const void *data, size_t len, int try_mus2mid)
1351 {
1352 int i, j;
1353
1354 MEMFILE *instream;
1355 MEMFILE *outstream;
1356 void *outbuf;
1357 size_t outbuf_len;
1358 int result;
1359
1360 if (music_handle)
1361 UnRegisterSong (0);
1362
1363 // e6y: new logic by me
1364 // Now you can hear title music in deca.wad
1365 // http://www.doomworld.com/idgames/index.php?id=8808
1366 // Ability to use mp3 and ogg as inwad lump
1367
1368 if (len > 4 && memcmp(data, "MUS", 3) != 0)
1369 {
1370 // The header has no MUS signature
1371 // Let's try to load this song directly
1372
1373 // go through music players in order
1374 int found = 0;
1375
1376 for (j = 0; j < NUM_MUS_PLAYERS; j++)
1377 {
1378 found = 0;
1379 for (i = 0; music_players[i]; i++)
1380 {
1381 if (strcmp (music_players[i]->name (), music_player_order[j]) == 0)
1382 {
1383 found = 1;
1384 if (music_player_was_init[i])
1385 {
1386 const void *temp_handle = music_players[i]->registersong (data, len);
1387 if (temp_handle)
1388 {
1389 SDL_LockMutex (musmutex);
1390 current_player = i;
1391 music_handle = temp_handle;
1392 SDL_UnlockMutex (musmutex);
1393 lprintf(LO_DEBUG, "RegisterSongEx: Using player %s\n", music_players[i]->name ());
1394 return 1;
1395 }
1396 }
1397 else
1398 lprintf(LO_DEBUG, "RegisterSongEx: Music player %s on preferred list but it failed to init\n", music_players[i]-> name ());
1399 }
1400 }
1401 if (!found)
1402 lprintf(LO_DEBUG, "RegisterSongEx: Couldn't find preferred music player %s in list\n (typo or support not included at compile time)\n", music_player_order[j]);
1403 }
1404 // load failed
1405 }
1406
1407 // load failed? try mus2mid
1408 if (len > 4 && try_mus2mid)
1409 {
1410
1411 instream = mem_fopen_read (data, len);
1412 outstream = mem_fopen_write ();
1413
1414 // e6y: from chocolate-doom
1415 // New mus -> mid conversion code thanks to Ben Ryves <[email protected]>
1416 // This plays back a lot of music closer to Vanilla Doom - eg. tnt.wad map02
1417 result = mus2mid(instream, outstream);
1418 if (result != 0)
1419 {
1420 size_t muslen = len;
1421 const unsigned char *musptr = (const unsigned char*)data;
1422
1423 // haleyjd 04/04/10: scan forward for a MUS header. Evidently DMX was
1424 // capable of doing this, and would skip over any intervening data. That,
1425 // or DMX doesn't use the MUS header at all somehow.
1426 while (musptr < (const unsigned char*)data + len - sizeof(musheader))
1427 {
1428 // if we found a likely header start, reset the mus pointer to that location,
1429 // otherwise just leave it alone and pray.
1430 if (!strncmp ((const char*) musptr, "MUS\x1a", 4))
1431 {
1432 mem_fclose (instream);
1433 instream = mem_fopen_read (musptr, muslen);
1434 result = mus2mid (instream, outstream);
1435 break;
1436 }
1437
1438 musptr++;
1439 muslen--;
1440 }
1441 }
1442 if (result == 0)
1443 {
1444 mem_get_buf(outstream, &outbuf, &outbuf_len);
1445
1446 // recopy so we can free the MEMFILE
1447 mus2mid_conversion_data = Z_Malloc (outbuf_len);
1448 if (mus2mid_conversion_data)
1449 memcpy (mus2mid_conversion_data, outbuf, outbuf_len);
1450
1451 mem_fclose(instream);
1452 mem_fclose(outstream);
1453
1454 if (mus2mid_conversion_data)
1455 {
1456 return RegisterSongEx (mus2mid_conversion_data, outbuf_len, 0);
1457 }
1458 }
1459 }
1460
1461 lprintf(LO_ERROR, "RegisterSongEx: Failed\n");
1462 return 0;
1463 }
1464
1465
1466 static int RegisterSong (const void *data, size_t len)
1467 {
1468 int result;
1469
1470 result = RegisterSongEx (data, len, 1);
1471
1472 if (result)
1473 registered_non_rw = true;
1474
1475 return result;
1476 }
1477
1478 static void UpdateMusic (void *buff, unsigned nsamp)
1479 {
1480 if (!music_handle)
1481 {
1482 memset (buff, 0, nsamp * 4);
1483 return;
1484 }
1485
1486 music_players[current_player]->render (buff, nsamp);
1487 }
1488
1489 void M_ChangeMIDIPlayer(void)
1490 {
1491 snd_midiplayer = dsda_StringConfig(dsda_config_snd_midiplayer);
1492
1493 if (!strcasecmp(snd_midiplayer, midiplayers[midi_player_fluidsynth]))
1494 {
1495 strcpy(music_player_order[3], PLAYER_FLUIDSYNTH);
1496 strcpy(music_player_order[4], PLAYER_OPL);
1497 strcpy(music_player_order[5], PLAYER_PORTMIDI);
1498 }
1499 else if (!strcasecmp(snd_midiplayer, midiplayers[midi_player_opl]))
1500 {
1501 strcpy(music_player_order[3], PLAYER_OPL);
1502 strcpy(music_player_order[4], PLAYER_FLUIDSYNTH);
1503 strcpy(music_player_order[5], PLAYER_PORTMIDI);
1504 }
1505 else if (!strcasecmp(snd_midiplayer, midiplayers[midi_player_portmidi]))
1506 {
1507 strcpy(music_player_order[3], PLAYER_PORTMIDI);
1508 strcpy(music_player_order[4], PLAYER_FLUIDSYNTH);
1509 strcpy(music_player_order[5], PLAYER_OPL);
1510 }
1511
1512 S_StopMusic();
1513 S_RestartMusic();
1514 }