Debian Codegraph @

src/sfx.cpp

raw
1 /**
2 * Sound effects (not music) management
3
4 * Copyright (C) 1997, 1998, 1999, 2002, 2003 Seth A. Robinson
5 * Copyright (C) 2003 Shawn Betts
6 * Copyright (C) 2005, 2007, 2008, 2009, 2014, 2015 Sylvain Beucler
7
8 * This file is part of GNU FreeDink
9
10 * GNU FreeDink is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License as
12 * published by the Free Software Foundation; either version 3 of the
13 * License, or (at your option) any later version.
14
15 * GNU FreeDink is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
19
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see
22 * <http://www.gnu.org/licenses/>.
23 */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <stdlib.h>
30 #include <string.h> /* memset, memcpy */
31 #include <errno.h>
32
33 #include "SDL.h"
34 #include "SDL_mixer.h"
35 #include "live_sprites_manager.h"
36 #include "io_util.h"
37 #include "paths.h"
38 #include "log.h"
39 #include "math.h"
40 #include "sfx.h"
41 #include "log.h"
42
43 /* Sound - BGM */
44 int sound_on = 1;
45
46 /* Channel metadata */
47 #define NUM_CHANNELS 20
48 static struct
49 {
50 /*bool*/int repeat;
51 int owner;
52 int survive;
53 int cur_sound; /* Sound currently played in that channel */
54 int looping;
55 int finished;
56 } channelinfo[NUM_CHANNELS];
57
58
59 /* Sound metadata */
60 #define MAX_SOUNDS 100
61 static struct
62 {
63 SDL_AudioSpec orig_spec;
64 Uint32 orig_len;
65 int pos_lastframe; /* index for the last frame */
66 int pos_end; /* upper bound (pre-calculated for efficiency&simplicity) */
67 SDL_AudioCVT cvt;
68 Uint32 cvt_buf_len;
69 } registered_sounds[MAX_SOUNDS];
70
71
72 /* Hardware soundcard information */
73 static int hw_freq, hw_channels;
74 static Uint16 hw_format;
75
76 /* Fake buffer */
77 static Uint8* fake_buf = NULL;
78 static Uint32 fake_buf_len = 0;
79
80 static int SetVolume(int channel, int dx_volume);
81 static int SetPan(int channel, int dx_panning);
82 static void CleanupChannel(int channel);
83 static void FreeRegisteredSound(int index);
84
85 int get_pan(int h);
86 int get_vol(int h);
87
88
89 /**
90 * Display a SDL audio-format in human-readable form
91 **/
92 static const char *format2string(Uint16 format) {
93 char *format_str = "Unknown";
94 switch (format)
95 {
96 case AUDIO_U8: format_str = "U8"; break;
97 case AUDIO_S8: format_str = "S8"; break;
98 case AUDIO_U16LSB: format_str = "U16LSB"; break;
99 case AUDIO_S16LSB: format_str = "S16LSB"; break;
100 case AUDIO_U16MSB: format_str = "U16MSB"; break;
101 case AUDIO_S16MSB: format_str = "S16MSB"; break;
102 case AUDIO_S32LSB: format_str = "S32LSB"; break;
103 case AUDIO_S32MSB: format_str = "S32MSB"; break;
104 case AUDIO_F32LSB: format_str = "F32LSB"; break;
105 case AUDIO_F32MSB: format_str = "F32MSB"; break;
106 }
107 return format_str;
108 }
109
110
111 /**
112 * Frequency shift with linear interpolation
113 *
114 * Techniques from Allegro's mixer.c
115 *
116 * We'll assume 8bit is unsigned and 16bit is signed for simplicity
117 * (common case)
118 *
119 * We'll also assume that the converted buffer is in the system's
120 * endianness (there's no reason it shouldn't be) - still the code
121 * portably handles LSB and MSB endianness alike.
122 */
123 struct callback_data
124 {
125 int pos; /* which sample (not frame) we're playing now, in 1/256th */
126 int shift; /* position advance for 1 frame, in 1/256th */
127 int sound; /* sound index */
128 int channel; /* channel index */
129 };
130 static void callback_samplerate_cleanup(int chan, void *udata)
131 {
132 free(udata);
133 }
134 static void callback_samplerate(int chan, void *stream, int len, void *udata)
135 {
136 struct callback_data* data = (struct callback_data*)udata;
137 if (channelinfo[data->channel].finished == 1)
138 return;
139
140 /* printf("%d - %d/%d\n", len, data->pos>>8, registered_sounds[data->sound].pos_end>>8); */
141 int pos_end = registered_sounds[data->sound].pos_end;
142 int pos_lastframe = registered_sounds[data->sound].pos_lastframe;
143
144 switch (registered_sounds[data->sound].cvt.dst_format)
145 {
146 case AUDIO_U8:
147 if (hw_channels == 1)
148 {
149 /* Unsigned 8bit mono */
150 Uint8 *buf = (Uint8*) registered_sounds[data->sound].cvt.buf;
151 Uint8 *pstream = (Uint8*)stream;
152 short silence = 128;
153 int bytesPerFrame = 1;
154 int i;
155 for (i = 0; i < len; i += bytesPerFrame)
156 {
157 int cur_index = data->pos >> 8;
158 Uint8 *pbuf = &buf[cur_index];
159 /* This frame (left and right channels)... */
160 Uint8 v1 = *(pbuf++);
161 /* and the next frame */
162 Uint8 v2;
163 if (data->pos < pos_lastframe)
164 v2 = *(pbuf++);
165 else
166 v2 = silence;
167
168 /* Compute interpolation based on progress (subpos) between v1
169 and v2 (measured between 0 and (1<<8)-1) */
170 int subpos = data->pos & ((1<<8) - 1); /* or: data->pos % 256 */
171 Uint8 v = (v1 * ((1<<8) - subpos) + v2 * subpos) >> 8;
172 *(pstream++) = v;
173
174 data->pos += data->shift;
175 if (data->pos >= pos_end)
176 {
177 if (!channelinfo[data->channel].looping)
178 {
179 channelinfo[data->channel].finished = 1;
180 break;
181 }
182 data->pos = 0;
183 }
184 }
185 }
186 else if (hw_channels == 2)
187 {
188 /* Unsigned 8bit stereo */
189 Uint8 *buf = (Uint8*) registered_sounds[data->sound].cvt.buf;
190 Uint8 *pstream = (Uint8*)stream;
191 short silence = 128;
192 int bytesPerFrame = 2;
193 int i;
194 for (i = 0; i < len; i += bytesPerFrame)
195 {
196 int cur_index = data->pos >> 8 << 1; /* x2 because stereo */
197 Uint8 *pbuf = &buf[cur_index];
198 /* This frame (left and right channels)... */
199 Uint8 v1l = *(pbuf++);
200 Uint8 v1r = *(pbuf++);
201 /* and the next frame */
202 Uint8 v2l, v2r;
203 if (data->pos < pos_lastframe)
204 {
205 v2l = *(pbuf++);
206 v2r = *(pbuf++);
207 }
208 else
209 {
210 v2l = v2r = silence;
211 }
212
213 /* Compute interpolation based on progress (subpos) between v1
214 and v2 (measured between 0 and (1<<8)-1) */
215 int subpos = data->pos & ((1<<8) - 1); /* or: data->pos % 256 */
216 Uint8 vl = (v1l * ((1<<8) - subpos) + v2l * subpos) >> 8;
217 Uint8 vr = (v1r * ((1<<8) - subpos) + v2r * subpos) >> 8;
218 *(pstream++) = vl;
219 *(pstream++) = vr;
220
221 data->pos += data->shift;
222 if (data->pos >= pos_end)
223 {
224 if (!channelinfo[data->channel].looping)
225 {
226 channelinfo[data->channel].finished = 1;
227 break;
228 }
229 data->pos = 0;
230 }
231 }
232 }
233 break;
234 case AUDIO_S16SYS:
235 if (hw_channels == 1)
236 {
237 /* Signed 16bit mono */
238 Sint16 *buf = (Sint16*) registered_sounds[data->sound].cvt.buf;
239 Sint16 *pstream = (Sint16*)stream;
240 short silence = 0;
241 int bytesPerFrame = 2;
242 int i;
243 for (i = 0; i < len; i += bytesPerFrame)
244 {
245 int cur_index = data->pos >> 8;
246 Sint16 *pbuf = &buf[cur_index];
247 /* This frame (left and right channels)... */
248 Sint16 v1 = *(pbuf++);
249 /* and the next frame */
250 Sint16 v2;
251 if (data->pos < pos_lastframe)
252 v2 = *(pbuf++);
253 else
254 v2 = silence;
255
256 /* Compute interpolation based on progress (subpos) between v1
257 and v2 (measured between 0 and (1<<8)-1) */
258 int subpos = data->pos & ((1<<8) - 1); /* or: data->pos % 256 */
259 Sint16 v = (v1 * ((1<<8) - subpos) + v2 * subpos) >> 8;
260 *(pstream++) = v;
261
262 data->pos += data->shift;
263 if (data->pos >= pos_end)
264 {
265 if (!channelinfo[data->channel].looping)
266 {
267 channelinfo[data->channel].finished = 1;
268 break;
269 }
270 data->pos = 0;
271 }
272 }
273 }
274 else if (hw_channels == 2)
275 {
276 /* Signed 16bit stereo */
277 Sint16 *buf = (Sint16*) registered_sounds[data->sound].cvt.buf;
278 Sint16 *pstream = (Sint16*)stream;
279 short silence = 0;
280 int bytesPerFrame = 4;
281 int i;
282 for (i = 0; i < len; i += bytesPerFrame)
283 {
284 int cur_index = (data->pos >> 8) << 1; /* x2 because stereo */
285 Sint16 *pbuf = &buf[cur_index];
286 /* This frame (left and right channels)... */
287 Sint16 v1l = *(pbuf++);
288 Sint16 v1r = *(pbuf++);
289 /* and the next frame */
290 Sint16 v2l, v2r;
291 if (data->pos < pos_lastframe)
292 {
293 v2l = *(pbuf++);
294 v2r = *(pbuf++);
295 }
296 else
297 {
298 v2l = v2r = silence;
299 }
300
301 /* Compute interpolation based on progress (subpos) between v1
302 and v2 (measured between 0 and (1<<8)-1) */
303 int subpos = data->pos & ((1<<8) - 1); /* or: data->pos % 256 */
304 Sint16 vl = (v1l * ((1<<8) - subpos) + v2l * subpos) >> 8;
305 Sint16 vr = (v1r * ((1<<8) - subpos) + v2r * subpos) >> 8;
306 *(pstream++) = vl;
307 *(pstream++) = vr;
308
309 data->pos += data->shift;
310 if (data->pos >= pos_end)
311 {
312 if (!channelinfo[data->channel].looping)
313 {
314 channelinfo[data->channel].finished = 1;
315 break;
316 }
317 data->pos = 0;
318 }
319 }
320 }
321 break;
322 }
323 }
324
325 /**
326 * Close channels that stopped playing
327 */
328 void sfx_cleanup_finished_channels()
329 {
330 int i = 0;
331 for (i = 0; i < NUM_CHANNELS; i++)
332 {
333 if (channelinfo[i].finished == 1)
334 Mix_HaltChannel(i);
335 }
336 }
337
338
339
340 /**
341 * Load sounds from the standard paths. Sound is converted to the
342 * current hardware (soundcard) format so that sound rate can be
343 * altered with minimal overhead when playing the sound.
344 */
345 int CreateBufferFromWaveFile(char* filename, int index)
346 {
347 /* Open the wave file */
348 char path[150];
349 FILE* in = NULL;
350
351 sprintf(path, "sound/%s", filename);
352 in = paths_dmodfile_fopen(path, "rb");
353 if (in == NULL)
354 in = paths_fallbackfile_fopen(path, "rb");
355 if (in == NULL)
356 {
357 log_debug("CreateBufferFromWaveFile: %s", strerror(errno));
358 return 0;
359 }
360
361 SDL_RWops* rwops = SDL_RWFromFP(in, /*autoclose=*/SDL_TRUE);
362 return CreateBufferFromWaveFile_RW(rwops, 1, index);
363 }
364 int CreateBufferFromWaveFile_RW(SDL_RWops* rwops, int rwfreesrc, int index)
365 {
366 SDL_AudioSpec wav_spec;
367 Uint8 *wav_buf;
368 Uint32 wav_len;
369
370 // Safety check
371 if (index >= MAX_SOUNDS)
372 {
373 log_error("SCRIPTING ERROR: sound index %d is too big.", index);
374 return 0;
375 }
376
377 // Free previous sound if necessary
378 FreeRegisteredSound(index);
379
380
381 if (SDL_LoadWAV_RW(rwops, rwfreesrc, &wav_spec, &wav_buf, &wav_len) == NULL)
382 {
383 log_error("Could not open sound file: %s", SDL_GetError());
384 return 0;
385 }
386 log_info("frequency=%dHz\tformat=%s\tchannels=%d\tlength=%d bytes",
387 wav_spec.freq, format2string(wav_spec.format),
388 wav_spec.channels, wav_len);
389
390
391 /* Converting some WAV data to hardware format - except for sample
392 rate, which we will do better after that. */
393 /* TODO: testing with a sine.wav, I saw that stereo->mono (2->1
394 channels) conversion works quite bad - maybe we should it
395 ourselves too. AFAICS this case is not handled by
396 SDL_audiocvt.c. */
397 SDL_AudioCVT cvt;
398 int ret;
399
400 /* Build AudioCVT */
401 ret = SDL_BuildAudioCVT(&cvt,
402 wav_spec.format, wav_spec.channels, wav_spec.freq,
403 hw_format, hw_channels, wav_spec.freq);
404
405 /* Check that the convert was built */
406 if (ret == -1) {
407 log_error("Couldn't build converter: %s", SDL_GetError());
408 SDL_FreeWAV(wav_buf);
409 }
410
411 /* Setup for conversion */
412 Uint32 cvt_buf_len = wav_len*cvt.len_mult;
413 cvt.buf = (Uint8 *)malloc(cvt_buf_len);
414 cvt.len = wav_len;
415 memcpy(cvt.buf, wav_buf, wav_len);
416
417 /* We can delete to original WAV data now */
418 SDL_FreeWAV(wav_buf);
419
420
421 /* And now we're ready to convert */
422 ret = SDL_ConvertAudio(&cvt);
423 if (ret == -1) {
424 log_error("Couldn't convert audiox: %s", SDL_GetError());
425 SDL_FreeWAV(wav_buf);
426 }
427
428 /* Work-around: if no conversion is needed, format is not specified: */
429 if (cvt.needed == 0)
430 cvt.dst_format = wav_spec.format;
431
432 /* Converted audio is now in cvt.buf */
433 /*printf("CVT\t\tinfo: frequency=?Hz\tformat=%s\tchannels=??\tlength=%d bytes\n",
434 format2string(cvt.dst_format), cvt.len_cvt);*/
435
436 /* Precompute the sound bounds */
437 /* Last byte in hw_format is the number of bits per sample: */
438 int wav_bytesPerSample = (wav_spec.format & 0xFF) / 8;
439 int pos_end = ((wav_len / wav_bytesPerSample) / wav_spec.channels) << 8; /* number of frames */
440 int pos_lastframe = (((wav_len / wav_bytesPerSample) / wav_spec.channels) - 1) << 8;
441
442 registered_sounds[index].orig_spec = wav_spec;
443 registered_sounds[index].orig_len = wav_len;
444 registered_sounds[index].cvt = cvt;
445 registered_sounds[index].cvt_buf_len = cvt_buf_len;
446 registered_sounds[index].pos_end = pos_end;
447 registered_sounds[index].pos_lastframe = pos_lastframe;
448
449 return 1;
450 }
451
452 /**
453 * Return the channel that plays the specified sound, or -1 if not
454 * found
455 */
456 int get_channel(int sound) {
457 int i;
458 /* Check all channels to see if it is playing the sound */
459 for (i = 0; i < NUM_CHANNELS; i++)
460 {
461 if (channelinfo[i].cur_sound == sound)
462 return i;
463 }
464 return -1;
465 }
466
467 /**
468 * Is the specified sound currently playing?
469 *
470 * Only used in pig_brain(), could be removed maybe.
471 */
472 int playing(int sound)
473 {
474 if (sound >= MAX_SOUNDS)
475 {
476 log_error("Attempting to get the status of sound %d (> MAX_SOUNDS=%d)",
477 sound, MAX_SOUNDS);
478 return 0;
479 }
480
481 return (get_channel(sound) != -1);
482 }
483
484
485 /**
486 * Kill repeating sounds except the ones that survive
487 */
488 void kill_repeat_sounds(void)
489 {
490 int i;
491 if (!sound_on)
492 return;
493
494 log_info("Killing repeating sound");
495
496 for (i = 0; i < NUM_CHANNELS; i++)
497 {
498 // Msg("Bank #%d: repeat=%d, owner=%d, survive=%d", i,
499 // soundinfo[i].repeat, soundinfo[i].owner, soundinfo[i].survive);
500 if (channelinfo[i].repeat && (channelinfo[i].owner == 0)
501 && (channelinfo[i].survive == 0))
502 {
503 Mix_HaltChannel(i);
504 log_info("Killed repeating sound %d", i);
505 channelinfo[i].repeat = 0;
506 }
507 }
508 }
509
510 /**
511 * Kill all repeating sounds, even the ones that survive (used from
512 * DinkC's restart_game() and load_game())
513 */
514 void kill_repeat_sounds_all(void)
515 {
516 int i;
517 if (!sound_on)
518 return;
519
520 for (i = 0; i < NUM_CHANNELS; i++)
521 {
522 if (channelinfo[i].repeat && (channelinfo[i].owner == 0))
523 {
524 Mix_HaltChannel(i);
525 channelinfo[i].repeat = 0;
526 }
527 }
528 }
529
530 /**
531 * Kill one sound
532 */
533 void kill_this_sound(int channel)
534 {
535 Mix_HaltChannel(channel);
536 }
537
538 /**
539 * Called by update_frame()
540 *
541 * If sound is active, refreshed pan&vol for 3D effect.
542 *
543 * If repeating and sprite.sound==0 and sprite.owner!=0 -> stop sound
544 * If sprite.active==0 and sprite.owner!=0 -> stop sound
545 */
546 void update_sound(void)
547 {
548 int i;
549
550 if (!sound_on)
551 return;
552
553 for (i = 0; i < NUM_CHANNELS; i++)
554 {
555 if (channelinfo[i].repeat && (channelinfo[i].owner != 0))
556 {
557 if ((spr[channelinfo[i].owner].sound == 0)
558 || (!spr[channelinfo[i].owner].active) )
559 {
560 Mix_HaltChannel(i);
561 channelinfo[i].owner = 0;
562 channelinfo[i].repeat = 0;
563 }
564 else
565 {
566 SetPan(i, get_pan(channelinfo[i].owner));
567 SetVolume(i, get_vol(channelinfo[i].owner));
568 }
569 }
570
571 if (Mix_Playing(i))
572 {
573 if (channelinfo[i].owner != 0)
574 {
575 if (!spr[channelinfo[i].owner].active)
576 {
577 Mix_HaltChannel(i);
578 }
579 else
580 {
581 SetPan(i, get_pan(channelinfo[i].owner));
582 SetVolume(i, get_vol(channelinfo[i].owner));
583 }
584 }
585 }
586 }
587 }
588
589
590 static int SoundPlayEffectChannel(int sound, int min, int plus, int sound3d, /*bool*/int repeat, int explicit_channel);
591
592 /**
593 * Just play a sound, do not try to update sprites info or apply
594 * effects
595 */
596 void EditorSoundPlayEffect(int sound)
597 {
598 /* Don't print warning if the sound isn't present - as sounds are
599 played continuously when arrow keys are pressed */
600 if (registered_sounds[sound].cvt.buf != NULL)
601 SoundPlayEffectChannel(sound, registered_sounds[sound].orig_spec.freq, 0, 0, 0, 0);
602 }
603
604 /**
605 * Play a sound previously loaded to memory (in registered_sounds)
606 * - sound: sound index
607 * - min: frequency (Hz)
608 * - plus: max random frequency, to add to min
609 * - sound3d: if != 0, sprite number whose location will be used for
610 * pseudo-3d effects (volume, panning)
611 * - repeat: is sound looping?
612 **/
613 int SoundPlayEffect(int sound, int min, int plus, int sound3d, /*bool*/int repeat)
614 {
615 return SoundPlayEffectChannel(sound, min, plus, sound3d, repeat, -1);
616 }
617 /**
618 * SoundPlayEffect_Channel_ allows to specify an explicit audio
619 * channel, which in turns allows the editor to only use one channel
620 * for everything (when you move the mouse with the keyboard, you'll
621 * hear a series of close 'ticks', but they won't overlap each
622 * others). The rest of the time, the game will just pass '-1' for the
623 * channel, so the first available channel (among NUM_CHANNELS useable
624 * simultaneously) will be selected.
625 */
626 static int SoundPlayEffectChannel(int sound, int min, int plus, int sound3d, /*bool*/int repeat, int explicit_channel)
627 {
628 int channel;
629
630 // Safety check
631 if (registered_sounds[sound].cvt.buf == NULL)
632 {
633 log_warn("Attempting to play empty sound %d.", sound);
634 return 0;
635 }
636
637 /* Sample rate / frequency */
638 {
639 /** Shift:
640 hw_adjust = wave_freq / hw_freq;
641 sample_rate_adjust = play_freq / wave_freq
642 shift = hw_adjust * sample_rate_adjust = wave_freq/hw_freq * play_freq/wave_freq
643 <<8 because we're using 1/256th units (poor man's double)
644 */
645 int play_freq;
646 if (plus == 0)
647 play_freq = min;
648 else
649 play_freq = (rand () % plus) + min;
650
651 /* Compute how much we should advance in the original sound when we
652 play one frame with hw_freq */
653 int shift = ((int)round((double)play_freq / hw_freq * (1<<8)));
654 /* printf("shift=%d (%d*64)\n", shift, shift>>8); */
655
656 /* Fake buffer: we give an empty buffer to SDL_mixer. We won't
657 actually play from that buffer though, as the audio buffer will
658 be generated in callback_samplerate(). That function will also
659 take care of updating the channelinfo when it's finished (and
660 should be cleaned from a non-callback function). */
661 Mix_Chunk *chunk = Mix_QuickLoad_RAW(fake_buf, fake_buf_len);
662
663 channel = Mix_PlayChannel(explicit_channel, chunk, -1);
664 if (channel < 0)
665 {
666 log_error("Mix_PlayChannel: Error playing sound %d - %s",
667 sound, Mix_GetError());
668 return 0;
669 }
670 Mix_Pause(channel);
671 channelinfo[channel].finished = 0;
672 channelinfo[channel].looping = repeat;
673
674 struct callback_data *data = (struct callback_data*)calloc(1, sizeof(struct callback_data));
675 data->pos = 0;
676 data->shift = shift;
677 data->sound = sound;
678 data->channel = channel;
679
680 Mix_RegisterEffect(channel, callback_samplerate, callback_samplerate_cleanup, data);
681 Mix_ChannelFinished(CleanupChannel);
682 Mix_Resume(channel);
683 }
684
685
686 if (sound3d > 0)
687 {
688 SetPan(channel, get_pan(sound3d));
689 SetVolume(channel, get_vol(sound3d));
690 }
691
692
693 channelinfo[channel].owner = sound3d;
694 channelinfo[channel].repeat = repeat;
695 channelinfo[channel].survive = 0;
696 channelinfo[channel].cur_sound = sound;
697
698 /* Return a non-zero channel */
699 return channel+1;
700 }
701
702 /**
703 * SoundStopEffect
704 *
705 * Stops the sound effect specified.
706 * Returns TRUE if succeeded.
707 */
708 int SoundStopEffect(int sound)
709 {
710 int channel;
711
712 if (sound >= MAX_SOUNDS)
713 {
714 log_error("Attempting to get stop sound %d (> MAX_SOUNDS=%d)",
715 sound, MAX_SOUNDS);
716 return 0;
717 }
718
719 channel = get_channel(sound);
720 if (channel < 0)
721 return 0;
722 else
723 return Mix_HaltChannel(channel); /* always returns 0 */
724 }
725
726
727 /**
728 * InitSound
729 *
730 * Sets up the DirectSound object and loads all sounds into secondary
731 * DirectSound buffers. Returns -1 on error, or 0 if successful
732 */
733 void sfx_init()
734 {
735 if (!sound_on)
736 return;
737
738 sound_on = 0;
739
740 log_info("Initting sound");
741
742 if (SDL_Init(SDL_INIT_AUDIO) == -1)
743 {
744 log_error("SDL_Init(SDL_INIT_AUDIO): %s", SDL_GetError());
745 return;
746 }
747
748 /* Work-around to disable fluidsynth and fallback to TiMidity++: */
749 /* TODO: allow user to set it at run-time */
750 /* SDL_setenv("SDL_SOUNDFONTS="); */
751 /* SDL_setenv("SDL_FORCE_SOUNDFONTS=1"); */
752
753 /* To specify an alternate timidity.cfg */
754 /* Cf. SDL2_mixer/timidity/config.h for defaults */
755 /* SDL_setenv("TIMIDITY_CFG", "somewhere/timidity.cfg", 0); */
756
757 /* MIX_DEFAULT_FREQUENCY is ~22kHz are considered a good default,
758 44kHz is considered too CPU-intensive on older computers */
759 /* MIX_DEFAULT_FORMAT is 16bit adapted to current architecture
760 (little/big endian) */
761 /* MIX_DEFAULT_CHANNELS is 2 => stereo, allowing panning effects */
762 /* 1024 (chunk on which effects are applied) seems a good default,
763 4096 is considered too big for SFX */
764 int buf_samples = 1024;
765 if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, buf_samples) == -1)
766 {
767 log_error("Mix_OpenAudio: %s", Mix_GetError());
768 return;
769 }
770
771 /* Allocate channels (not mono/stereo, but the simultaneous sounds
772 to be mixed, possibly with effects) */
773 Mix_AllocateChannels(NUM_CHANNELS);
774
775 /* Done with initialization */
776 /* Avoid calling SDL_PauseAudio when using SDL_Mixer */
777 /* SDL_PauseAudio(0); */
778
779 /* Dump audio info */
780 {
781 log_info("Audio driver: %s", SDL_GetCurrentAudioDriver());
782
783 int numtimesopened;
784 numtimesopened = Mix_QuerySpec(&hw_freq, &hw_format, &hw_channels);
785 if (!numtimesopened)
786 log_error("Mix_QuerySpec: %s", Mix_GetError());
787 else
788 log_info("Audio hardware info: frequency=%dHz\tformat=%s\tchannels=%d\topened=%d times",
789 hw_freq, format2string(hw_format), hw_channels, numtimesopened);
790 }
791
792 /* Test SDL_mixer capabilities */
793 {
794 int i, total;
795 total = Mix_GetNumChunkDecoders();
796 for (i = 0; i < total; i++)
797 log_info("Audio chunk decoder: %s", Mix_GetChunkDecoder(i));
798
799 total = Mix_GetNumMusicDecoders();
800 int ogg_available = 0;
801 for (i = 0; i < total; i++) {
802 if (strcmp(Mix_GetMusicDecoder(i), "OGG") == 0)
803 ogg_available = 1;
804 if (strcmp(Mix_GetMusicDecoder(i), "MP3") == 0)
805 log_info("Audio music decoder: MP3 (MP3 is patented, prefer Ogg Vorbis!)");
806 else
807 log_info("Audio music decoder: %s", Mix_GetMusicDecoder(i));
808 }
809 if (!ogg_available)
810 log_error("Audio music decoder: no Ogg support");
811
812 int available;
813 /* Don't mess with loading/unloading too much */
814 /*
815 available = Mix_Init(MIX_INIT_MOD); // libmikmod
816 log_info("Audio dynload: MOD %s", available ? "ok" : Mix_GetError());
817 available = Mix_Init(MIX_INIT_MODPLUG); // libmodplug
818 log_info("Audio dynload: MODPLUG %s", available ? "ok" : Mix_GetError());
819 available = Mix_Init(MIX_INIT_FLUIDSYNTH);
820 log_info("Audio dynload: FLUIDSYNTH %s", available ? "ok" : Mix_GetError());
821 available = Mix_Init(MIX_INIT_FLAC);
822 log_info("Audio dynload: FLAC %s", available ? "ok" : Mix_GetError());
823 available = Mix_Init(MIX_INIT_MP3);
824 log_info("Audio dynload: MP3 %s", available ? "ok" : Mix_GetError());
825 Mix_Quit();
826 */
827 available = Mix_Init(MIX_INIT_OGG);
828 log_info("Audio dynload: OGG: %s", available ? "ok" : Mix_GetError());
829 if (!available)
830 log_error("Audio dynload: no Ogg support");
831
832 // TODO: test MOD support (btw does mikmod and modplug conflict?)
833 }
834
835 /* Allocate fake buffer - use the same size as the audio buffer */
836 fake_buf_len = buf_samples;
837 fake_buf_len *= hw_channels;
838 if (hw_format != AUDIO_U8 && hw_format != AUDIO_S8)
839 /* 2 bytes per frame */
840 fake_buf_len *= 2;
841 fake_buf = (Uint8*)calloc(1, fake_buf_len);
842
843 /* No sound playing yet - initialize the lookup table: */
844 memset(channelinfo, 0, sizeof(channelinfo));
845 int i;
846 for (i = 0; i < NUM_CHANNELS; i++)
847 {
848 channelinfo[i].cur_sound = -1;
849 channelinfo[i].finished = 0;
850 channelinfo[i].looping = 0;
851 }
852
853 /* No sound loaded yet - initialise the registered sounds: */
854 memset(registered_sounds, 0, sizeof(registered_sounds));
855 /* Make sure they won't be used: */
856 for (i = 0; i < MAX_SOUNDS; i++)
857 registered_sounds[i].cvt.buf = NULL;
858
859 sound_on = 1;
860 }
861
862 /**
863 * Undoes everything that was done in a sfx_init call
864 */
865 void sfx_quit(void)
866 {
867 if (!sound_on)
868 return;
869
870 if (SDL_WasInit(SDL_INIT_AUDIO) == 0)
871 return;
872
873 /* Stops all SFX channels */
874 Mix_HaltChannel(-1);
875
876 /**
877 * Frees up resources associated with a sound effect
878 */
879 int idxKill = 0;
880 for (; idxKill < MAX_SOUNDS; idxKill++)
881 FreeRegisteredSound(idxKill);
882
883 free(fake_buf);
884
885 Mix_Quit();
886 Mix_CloseAudio();
887 SDL_QuitSubSystem(SDL_INIT_AUDIO);
888 }
889
890 /**
891 * Print SFX memory usage
892 */
893 void sfx_log_meminfo()
894 {
895 int sum = 0;
896 int i = 0;
897
898 sum = 0;
899 for (i = 0; i < MAX_SOUNDS; i++)
900 {
901 if (registered_sounds[i].cvt.buf != NULL)
902 sum += registered_sounds[i].cvt_buf_len;
903 }
904 log_debug("Sounds = %8d", sum);
905 }
906
907
908 /**
909 * Free memory used by sound #'sound'
910 */
911 static void FreeRegisteredSound(int sound)
912 {
913 if (registered_sounds[sound].cvt.buf != NULL)
914 /* cvt.buf was malloc'd by us before. It's used both as source and
915 destination by 'SDL_ConvertAudio', so it's not realloc'd in the
916 process, and we use 'free' (and not a SDL-specific func): */
917 free(registered_sounds[sound].cvt.buf);
918
919 memset(&registered_sounds[sound], 0, sizeof (registered_sounds[sound]));
920 /* Make sure it won't be reused: */
921 registered_sounds[sound].cvt.buf = NULL;
922 }
923
924 /**
925 * Free chunk once it's played (through Mix_ChannelFinished()
926 * callback)
927 */
928 static void CleanupChannel(int channel)
929 {
930 /* SDL_mixer won't try to free the actual audio buffer (fake_buf) if
931 the Chunk was loaded via Mix_QuickLoad_RAW() - which is a good
932 thing since fake_buf is shared by all Chunks. We still need to
933 free the Chunk when it's done playing. */
934 Mix_Chunk *chunk = Mix_GetChunk(channel);
935 if (chunk == NULL)
936 {
937 log_fatal("Internal error: cannot free channel %d's chunk (where did it disappear?)", channel);
938 exit(1);
939 }
940 Mix_FreeChunk(chunk);
941 channelinfo[channel].finished = 0;
942 channelinfo[channel].looping = 0;
943 channelinfo[channel].cur_sound = -1;
944
945 /* Revert SetVolume and SetPan effects */
946 Mix_UnregisterAllEffects(channel);
947 Mix_Volume(channel, MIX_MAX_VOLUME);
948 }
949
950
951 /**
952 * Set volume; dx_volume is [-10000;10000] in hundredth of dB
953 */
954 static int SetVolume(int channel, int dx_volume)
955 {
956 // SFX
957 /* See doc/sound.txt for details */
958 return Mix_Volume(channel, MIX_MAX_VOLUME * pow(10, ((double)dx_volume / 100) / 20));
959 }
960
961
962 /**
963 * Set left/right balance; dx_panning is [-10000;10000] in hundredth
964 * of dB, -ive is right channel attenuation, +ive is left channel
965 * attenuation
966 */
967 static int SetPan(int channel, int dx_panning)
968 {
969 // SFX
970 /* See doc/sound.txt for details */
971 if (dx_panning > 0)
972 return Mix_SetPanning(channel, 255 * pow(10, ((double)-dx_panning / 100) / 20), 255);
973 else
974 return Mix_SetPanning(channel, 255, 255 * pow(10, ((double)dx_panning / 100) / 20));
975 }
976
977
978 /** DinkC procedures **/
979 /* BIG FAT WARNING: in DinkC, soundbank is channel+1
980 (a.k.a. non-zero), and 0 means failure. */
981 int playsound(int sound, int min, int plus, int sound3d, int repeat)
982 {
983 int channel = SoundPlayEffect(sound, min, plus, sound3d, repeat);
984 int soundbank = channel + 1;
985 return soundbank;
986 }
987 void sound_set_kill(int soundbank)
988 {
989 int channel = soundbank - 1;
990 Mix_HaltChannel(channel);
991 }
992 void sound_set_survive(int soundbank, int survive)
993 {
994 int channel = soundbank - 1;
995 channelinfo[channel].survive = survive;
996 }
997 void sound_set_vol(int soundbank, int volume)
998 {
999 int channel = soundbank - 1;
1000 SetVolume(channel, volume);
1001 }
1002
1003
1004 /* Sound - SFX */
1005 int get_pan(int h)
1006 {
1007 int pan = 0;
1008 int x1 = 320;
1009
1010 //uncomment to allow math to be done from Dink's current location
1011 //x1 = spr[1].x;
1012
1013 if (spr[h].active)
1014 {
1015 if (spr[h].x > x1) pan += (spr[h].x - x1) * 6;
1016 if (x1 > spr[h].x) pan -= (x1 - spr[h].x) * 6;
1017 }
1018
1019 if (pan > 10000) pan = 10000;
1020 if (pan < -10000) pan = -10000;
1021
1022 return(pan);
1023 }
1024
1025 int get_vol(int h)
1026 {
1027 int pan = 0;
1028 int pan2 = 0;
1029
1030 if (spr[h].active)
1031 {
1032 if (spr[h].x > spr[1].x) pan -= (spr[h].x - spr[1].x) * 4;
1033 if (spr[1].x > spr[h].x) pan -= (spr[1].x - spr[h].x) * 4;
1034 if (spr[h].y > spr[1].y) pan2 -= (spr[h].y - spr[1].y) * 4;
1035 if (spr[1].y > spr[h].y) pan2 -= (spr[1].y - spr[h].y) * 4;
1036
1037 //Msg("pan %d, pan2 %d", pan, pan2);
1038 if (pan2 < pan) pan = pan2;
1039 }
1040
1041 if (pan > -100) pan = 0;
1042 if (pan < -10000) pan = -10000;
1043
1044 return(pan);
1045 }