Debian Codegraph @

engine/sound/sound_server.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name sound_server.cpp - The sound server (hardware layer and so on) */
11 //
12 // (c) Copyright 1998-2008 by Lutz Sammer, Fabrice Rossi, and
13 // Jimmy Salmon
14 //
15 // This program is free software; you can redistribute it and/or modify
16 // it under the terms of the GNU General Public License as published by
17 // the Free Software Foundation; only version 2 of the License.
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
30
31 //@{
32
33 /*----------------------------------------------------------------------------
34 -- Includes
35 ----------------------------------------------------------------------------*/
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40
41 #include "stratagus.h"
42
43 #include "SDL.h"
44
45 #include "sound_server.h"
46 #include "iolib.h"
47 #include "iocompat.h"
48
49
50 /*----------------------------------------------------------------------------
51 -- Variables
52 ----------------------------------------------------------------------------*/
53
54 static bool SoundInitialized; /// is sound initialized
55 static bool MusicPlaying; /// flag true if playing music
56
57 static int EffectsVolume = 128; /// effects sound volume
58 static int MusicVolume = 128; /// music volume
59
60 static bool MusicEnabled = true;
61 static bool EffectsEnabled = true;
62
63 /// Channels for sound effects and unit speach
64 struct SoundChannel {
65 CSample *Sample; /// sample to play
66 unsigned char Volume; /// Volume of this channel
67 signed char Stereo; /// stereo location of sound (-128 left, 0 center, 127 right)
68
69 bool Playing; /// channel is currently playing
70 int Point; /// point in sample if playing or next free channel
71
72 void (*FinishedCallback)(int channel); /// Callback for when a sample finishes playing
73 };
74
75 #define MaxChannels 32 /// How many channels are supported
76
77 static SoundChannel Channels[MaxChannels];
78 static int NextFreeChannel;
79
80 static struct {
81 CSample *Sample; /// Music sample
82 void (*FinishedCallback)(); /// Callback for when music finishes playing
83 } MusicChannel;
84
85 static void ChannelFinished(int channel);
86
87 static int *MixerBuffer;
88 static int MixerBufferSize;
89
90
91 /*----------------------------------------------------------------------------
92 -- Mixers
93 ----------------------------------------------------------------------------*/
94
95 /**
96 ** Convert RAW sound data to 44100 hz, Stereo, 16 bits per channel
97 **
98 ** @param src Source buffer
99 ** @param dest Destination buffer
100 ** @param frequency Frequency of source
101 ** @param chansize Bitrate in bytes per channel of source
102 ** @param channels Number of channels of source
103 ** @param bytes Number of compressed bytes to read
104 **
105 ** @return Number of bytes written in 'dest'
106 */
107 static int ConvertToStereo32(const char *src, char *dest, int frequency,
108 int chansize, int channels, int bytes)
109 {
110 SDL_AudioCVT acvt;
111 Uint16 format;
112
113 if (chansize == 1) {
114 format = AUDIO_U8;
115 } else {
116 format = AUDIO_S16SYS;
117 }
118 SDL_BuildAudioCVT(&acvt, format, channels, frequency, AUDIO_S16SYS, 2, 44100);
119
120 acvt.buf = (Uint8 *)dest;
121 memcpy(dest, src, bytes);
122 acvt.len = bytes;
123
124 SDL_ConvertAudio(&acvt);
125
126 return acvt.len_cvt;
127 }
128
129 /**
130 ** Mix music to stereo 32 bit.
131 **
132 ** @param buffer Buffer for mixed samples.
133 ** @param size Number of samples that fits into buffer.
134 **
135 ** @todo this functions can be called from inside the SDL audio callback,
136 ** which is bad, the buffer should be precalculated.
137 */
138 static void MixMusicToStereo32(int *buffer, int size)
139 {
140 int i;
141 int n;
142 int len;
143 short *buf;
144 char *tmp;
145 int div;
146
147 if (MusicPlaying) {
148 Assert(MusicChannel.Sample);
149
150 len = size * sizeof(*buf);
151 tmp = new char[len];
152 buf = new short[len];
153
154 div = 176400 / (MusicChannel.Sample->Frequency * (MusicChannel.Sample->SampleSize / 8)
155 * MusicChannel.Sample->Channels);
156
157 size = MusicChannel.Sample->Read(tmp, len / div);
158
159 n = ConvertToStereo32((char *)(tmp), (char *)buf, MusicChannel.Sample->Frequency,
160 MusicChannel.Sample->SampleSize / 8, MusicChannel.Sample->Channels, size);
161
162 for (i = 0; i < n / (int)sizeof(*buf); ++i) {
163 // Add to our samples
164 // FIXME: why taking out '/ 2' leads to distortion
165 buffer[i] += buf[i] * MusicVolume / MaxVolume / 2;
166 }
167
168 delete[] tmp;
169 delete[] buf;
170
171 if (n < len) { // End reached
172 MusicPlaying = false;
173 delete MusicChannel.Sample;
174 MusicChannel.Sample = NULL;
175
176 if (MusicChannel.FinishedCallback) {
177 MusicChannel.FinishedCallback();
178 }
179 }
180 }
181 }
182
183 /**
184 ** Mix sample to buffer.
185 **
186 ** The input samples are adjusted by the local volume and resampled
187 ** to the output frequence.
188 **
189 ** @param sample Input sample
190 ** @param index Position into input sample
191 ** @param volume Volume of the input sample
192 ** @param stereo Stereo (left/right) position of sample
193 ** @param buffer Output buffer
194 ** @param size Size of output buffer (in samples per channel)
195 **
196 ** @return The number of bytes used to fill buffer
197 **
198 ** @todo Can mix faster if signed 8 bit buffers are used.
199 */
200 static int MixSampleToStereo32(CSample *sample, int index, unsigned char volume,
201 char stereo, int *buffer, int size)
202 {
203 int local_volume;
204 unsigned char left;
205 unsigned char right;
206 int i;
207 static int buf[SOUND_BUFFER_SIZE / 2];
208 int div;
209
210 div = 176400 / (sample->Frequency * (sample->SampleSize / 8)
211 * sample->Channels);
212
213 local_volume = (int)volume * EffectsVolume / MaxVolume;
214
215 if (stereo < 0) {
216 left = 128;
217 right = 128 + stereo;
218 } else {
219 left = 128 - stereo;
220 right = 128;
221 }
222
223 Assert(!(index & 1));
224
225 if (size >= (sample->Len - index) * div / 2) {
226 size = (sample->Len - index) * div / 2;
227 }
228
229 size = ConvertToStereo32((char *)(sample->Buffer + index), (char *)buf, sample->Frequency,
230 sample->SampleSize / 8, sample->Channels,
231 size * 2 / div);
232
233 size /= 2;
234 for (i = 0; i < size; i += 2) {
235 // FIXME: why taking out '/ 2' leads to distortion
236 buffer[i] += ((short *)buf)[i] * local_volume * left / 128 / MaxVolume / 2;
237 buffer[i + 1] += ((short *)buf)[i + 1] * local_volume * right / 128 / MaxVolume / 2;
238 }
239
240 return 2 * size / div;
241 }
242
243 /**
244 ** Mix channels to stereo 32 bit.
245 **
246 ** @param buffer Buffer for mixed samples.
247 ** @param size Number of samples that fits into buffer.
248 **
249 ** @return How many channels become free after mixing them.
250 */
251 static int MixChannelsToStereo32(int *buffer, int size)
252 {
253 int channel;
254 int i;
255 int new_free_channels;
256
257 new_free_channels = 0;
258 for (channel = 0; channel < MaxChannels; ++channel) {
259 if (Channels[channel].Playing && Channels[channel].Sample) {
260 i = MixSampleToStereo32(Channels[channel].Sample,
261 Channels[channel].Point, Channels[channel].Volume,
262 Channels[channel].Stereo, buffer, size);
263 Channels[channel].Point += i;
264 Assert(Channels[channel].Point <= Channels[channel].Sample->Len);
265
266 if (Channels[channel].Point == Channels[channel].Sample->Len) {
267 ChannelFinished(channel);
268 ++new_free_channels;
269 }
270 }
271 }
272
273 return new_free_channels;
274 }
275
276 /**
277 ** Clip mix to output stereo 16 signed bit.
278 **
279 ** @param mix signed 32 bit input.
280 ** @param size number of samples in input.
281 ** @param output clipped 16 signed bit output buffer.
282 */
283 static void ClipMixToStereo16(const int *mix, int size, short *output)
284 {
285 int s;
286 const int *end;
287
288 end = mix + size;
289 while (mix < end) {
290 s = (*mix++);
291 if (s > SHRT_MAX) {
292 *output++ = SHRT_MAX;
293 } else if (s < SHRT_MIN) {
294 *output++ = SHRT_MIN;
295 } else {
296 *output++ = s;
297 }
298 }
299 }
300
301 /**
302 ** Mix into buffer.
303 **
304 ** @param buffer Buffer to be filled with samples. Buffer must be big enough.
305 ** @param samples Number of samples.
306 */
307 static void MixIntoBuffer(void *buffer, int samples)
308 {
309 if (samples > MixerBufferSize) {
310 delete[] MixerBuffer;
311 MixerBuffer = new int[samples];
312 MixerBufferSize = samples;
313 }
314
315 // FIXME: can save the memset here, if first channel sets the values
316 memset(MixerBuffer, 0, samples * sizeof(*MixerBuffer));
317
318 if (EffectsEnabled) {
319 // Add channels to mixer buffer
320 MixChannelsToStereo32(MixerBuffer, samples);
321 }
322 if (MusicEnabled) {
323 // Add music to mixer buffer
324 MixMusicToStereo32(MixerBuffer, samples);
325 }
326
327 ClipMixToStereo16(MixerBuffer, samples, (short *)buffer);
328 }
329
330 /**
331 ** Fill buffer for the sound card.
332 **
333 ** @see SDL_OpenAudio
334 **
335 ** @param udata the pointer stored in userdata field of SDL_AudioSpec.
336 ** @param stream pointer to buffer you want to fill with information.
337 ** @param len is length of audio buffer in bytes.
338 */
339 static void FillAudio(void *udata, Uint8 *stream, int len)
340 {
341 len >>= 1;
342 MixIntoBuffer(stream, len);
343 }
344
345 /*----------------------------------------------------------------------------
346 -- Effects
347 ----------------------------------------------------------------------------*/
348
349 /**
350 ** A channel is finished playing
351 */
352 static void ChannelFinished(int channel)
353 {
354 if (Channels[channel].FinishedCallback) {
355 Channels[channel].FinishedCallback(channel);
356 }
357
358 Channels[channel].Playing = false;
359 Channels[channel].Point = NextFreeChannel;
360 NextFreeChannel = channel;
361 }
362
363 /**
364 ** Put a sound request in the next free channel.
365 */
366 static int FillChannel(CSample *sample, unsigned char volume, char stereo)
367 {
368 Assert(NextFreeChannel < MaxChannels);
369
370 int old_free = NextFreeChannel;
371 int next_free = Channels[NextFreeChannel].Point;
372
373 Channels[NextFreeChannel].Volume = volume;
374 Channels[NextFreeChannel].Point = 0;
375 Channels[NextFreeChannel].Playing = true;
376 Channels[NextFreeChannel].Sample = sample;
377 Channels[NextFreeChannel].Stereo = stereo;
378 Channels[NextFreeChannel].FinishedCallback = NULL;
379
380 NextFreeChannel = next_free;
381
382 return old_free;
383 }
384
385 /**
386 ** Set the channel volume
387 **
388 ** @param channel Channel to set
389 ** @param volume New volume, <0 will not set the volume
390 **
391 ** @return Current volume of the channel, -1 for error
392 */
393 int SetChannelVolume(int channel, int volume)
394 {
395 if (channel < 0 || channel >= MaxChannels) {
396 return -1;
397 }
398
399 if (volume < 0) {
400 volume = Channels[channel].Volume;
401 } else {
402 SDL_LockAudio();
403
404 if (volume > MaxVolume) {
405 volume = MaxVolume;
406 }
407 Channels[channel].Volume = volume;
408
409 SDL_UnlockAudio();
410 }
411
412 return volume;
413 }
414
415 /**
416 ** Set the channel stereo
417 **
418 ** @param channel Channel to set
419 ** @param stereo -128 to 127, out of range will not set the stereo
420 **
421 ** @return Current stereo of the channel, -1 for error
422 */
423 int SetChannelStereo(int channel, int stereo)
424 {
425 if (channel < 0 || channel >= MaxChannels) {
426 return -1;
427 }
428
429 if (stereo < -128 || stereo > 127) {
430 stereo = Channels[channel].Stereo;
431 } else {
432 SDL_LockAudio();
433
434 if (stereo > 127) {
435 stereo = 127;
436 } else if (stereo < -128) {
437 stereo = -128;
438 }
439 Channels[channel].Stereo = stereo;
440
441 SDL_UnlockAudio();
442 }
443
444 return stereo;
445 }
446
447 /**
448 ** Set the channel's callback for when a sound finishes playing
449 **
450 ** @param channel Channel to set
451 ** @param callback Callback to call when the sound finishes
452 */
453 void SetChannelFinishedCallback(int channel, void (*callback)(int channel))
454 {
455 if (channel < 0 || channel >= MaxChannels) {
456 return;
457 }
458
459 Channels[channel].FinishedCallback = callback;
460 }
461
462 /**
463 ** Get the sample playing on a channel
464 */
465 CSample *GetChannelSample(int channel)
466 {
467 if (channel < 0 || channel >= MaxChannels) {
468 return NULL;
469 }
470
471 return Channels[channel].Sample;
472 }
473
474 /**
475 ** Stop a channel
476 **
477 ** @param channel Channel to stop
478 */
479 void StopChannel(int channel)
480 {
481 SDL_LockAudio();
482
483 if (channel >= 0 && channel < MaxChannels) {
484 if (Channels[channel].Playing) {
485 ChannelFinished(channel);
486 }
487 }
488
489 SDL_UnlockAudio();
490 }
491
492 /**
493 ** Stop all channels
494 */
495 void StopAllChannels()
496 {
497 SDL_LockAudio();
498
499 for (int i = 0; i < MaxChannels; ++i) {
500 if (Channels[i].Playing) {
501 ChannelFinished(i);
502 }
503 }
504
505 SDL_UnlockAudio();
506 }
507
508 /**
509 ** Load a sample
510 **
511 ** @param name File name of sample (short version).
512 **
513 ** @return General sample loaded from file into memory.
514 **
515 ** @todo Add streaming, caching support.
516 */
517 CSample *LoadSample(const std::string &name)
518 {
519 CSample *sample;
520 char buf[PATH_MAX];
521
522 LibraryFileName(name.c_str(), buf, sizeof(buf));
523
524 if ((sample = LoadWav(buf, PlayAudioLoadInMemory))) {
525 return sample;
526 }
527 #ifdef USE_VORBIS
528 if ((sample = LoadVorbis(buf, PlayAudioLoadInMemory))) {
529 return sample;
530 }
531 #endif
532
533 fprintf(stderr, "Can't load the sound `%s'\n", name.c_str());
534
535 return sample;
536 }
537
538 /**
539 ** Play a sound sample
540 **
541 ** @param sample Sample to play
542 **
543 ** @return Channel number, -1 for error
544 */
545 int PlaySample(CSample *sample)
546 {
547 int channel = -1;
548
549 SDL_LockAudio();
550
551 if (SoundEnabled() && EffectsEnabled && sample &&
552 NextFreeChannel != MaxChannels) {
553 channel = FillChannel(sample, EffectsVolume, 0);
554 }
555
556 SDL_UnlockAudio();
557
558 return channel;
559 }
560
561 /**
562 ** Play a sound file
563 **
564 ** @param name Filename of a sound to play
565 **
566 ** @return Channel number the sound is playing on, -1 for error
567 */
568 int PlaySoundFile(const std::string &name)
569 {
570 CSample *sample = LoadSample(name);
571 if (sample) {
572 return PlaySample(sample);
573 }
574 return -1;
575 }
576
577 /**
578 ** Set the global sound volume.
579 **
580 ** @param volume the sound volume 0-255
581 */
582 void SetEffectsVolume(int volume)
583 {
584 if (volume < 0) {
585 EffectsVolume = 0;
586 } else if (volume > MaxVolume) {
587 EffectsVolume = MaxVolume;
588 } else {
589 EffectsVolume = volume;
590 }
591 }
592
593 /**
594 ** Get effects volume
595 */
596 int GetEffectsVolume(void)
597 {
598 return EffectsVolume;
599 }
600
601 /**
602 ** Set effects enabled
603 */
604 void SetEffectsEnabled(bool enabled)
605 {
606 EffectsEnabled = enabled;
607 }
608
609 /**
610 ** Check if effects are enabled
611 */
612 bool IsEffectsEnabled(void)
613 {
614 return EffectsEnabled;
615 }
616
617 /*----------------------------------------------------------------------------
618 -- Music
619 ----------------------------------------------------------------------------*/
620
621 /**
622 ** Set the music finished callback
623 */
624 void SetMusicFinishedCallback(void (*callback)(void))
625 {
626 MusicChannel.FinishedCallback = callback;
627 }
628
629 /**
630 ** Play a music file.
631 **
632 ** @param sample Music sample.
633 **
634 ** @return 0 if music is playing, -1 if not.
635 */
636 int PlayMusic(CSample *sample)
637 {
638 if (sample) {
639 StopMusic();
640 MusicChannel.Sample = sample;
641 MusicPlaying = true;
642 return 0;
643 } else {
644 DebugPrint("Could not play sample\n");
645 return -1;
646 }
647 }
648
649 /**
650 ** Play a music file.
651 **
652 ** @param file Name of music file, format is automatically detected.
653 **
654 ** @return 0 if music is playing, -1 if not.
655 */
656 int PlayMusic(const std::string &file)
657 {
658 char name[PATH_MAX];
659 CSample *sample;
660
661 if (!SoundEnabled() || !IsMusicEnabled()) {
662 return -1;
663 }
664
665 LibraryFileName(file.c_str(), name, sizeof(name));
666
667 DebugPrint("play music %s\n" _C_ name);
668
669 sample = LoadWav(name, PlayAudioStream);
670
671 #ifdef USE_VORBIS
672 if (!sample) {
673 sample = LoadVorbis(name, PlayAudioStream);
674 }
675 #endif
676
677 if (sample) {
678 StopMusic();
679 MusicChannel.Sample = sample;
680 MusicPlaying = true;
681 return 0;
682 } else {
683 DebugPrint("Could not play %s\n" _C_ file.c_str());
684 return -1;
685 }
686 }
687
688 /**
689 ** Stop the current playing music.
690 */
691 void StopMusic(void)
692 {
693 if (MusicPlaying) {
694 MusicPlaying = false;
695 if (MusicChannel.Sample) {
696 SDL_LockAudio();
697 delete MusicChannel.Sample;
698 MusicChannel.Sample = NULL;
699 SDL_UnlockAudio();
700 }
701 }
702 }
703
704 /**
705 ** Set the music volume.
706 **
707 ** @param volume the music volume 0-255
708 */
709 void SetMusicVolume(int volume)
710 {
711 if (volume < 0) {
712 MusicVolume = 0;
713 } else if (volume > MaxVolume) {
714 MusicVolume = MaxVolume;
715 } else {
716 MusicVolume = volume;
717 }
718 }
719
720 /**
721 ** Get music volume
722 */
723 int GetMusicVolume(void)
724 {
725 return MusicVolume;
726 }
727
728 /**
729 ** Set music enabled
730 */
731 void SetMusicEnabled(bool enabled)
732 {
733 if (enabled) {
734 MusicEnabled = true;
735 } else {
736 MusicEnabled = false;
737 StopMusic();
738 }
739 }
740
741 /**
742 ** Check if music is enabled
743 */
744 bool IsMusicEnabled(void)
745 {
746 return MusicEnabled;
747 }
748
749 /**
750 ** Check if music is playing
751 */
752 bool IsMusicPlaying(void)
753 {
754 return MusicPlaying;
755 }
756
757 /*----------------------------------------------------------------------------
758 -- Init
759 ----------------------------------------------------------------------------*/
760
761 /**
762 ** Check if sound is enabled
763 */
764 bool SoundEnabled(void)
765 {
766 return SoundInitialized;
767 }
768
769 /**
770 ** Initialize sound card hardware part with SDL.
771 **
772 ** @param freq Sample frequency (44100,22050,11025 hz).
773 ** @param size Sample size (8bit, 16bit)
774 **
775 ** @return True if failure, false if everything ok.
776 */
777 static int InitSdlSound(int freq, int size)
778 {
779 SDL_AudioSpec wanted;
780
781 wanted.freq = freq;
782 if (size == 8) {
783 wanted.format = AUDIO_U8;
784 } else if (size == 16) {
785 wanted.format = AUDIO_S16SYS;
786 } else {
787 DebugPrint("Unexpected sample size %d\n" _C_ size);
788 wanted.format = AUDIO_S16SYS;
789 }
790 wanted.channels = 2;
791 wanted.samples = 4096;
792 wanted.callback = FillAudio;
793 wanted.userdata = NULL;
794
795 // Open the audio device, forcing the desired format
796 if (SDL_OpenAudio(&wanted, NULL) < 0) {
797 fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
798 return -1;
799 }
800 SDL_PauseAudio(0);
801
802 return 0;
803 }
804
805 /**
806 ** Initialize sound card.
807 **
808 ** @return True if failure, false if everything ok.
809 */
810 int InitSound(void)
811 {
812 //
813 // Open sound device, 8bit samples, stereo.
814 //
815 if (InitSdlSound(44100, 16)) {
816 SoundInitialized = false;
817 return 1;
818 }
819 SoundInitialized = true;
820
821 // ARI: The following must be done here to allow sound to work in
822 // pre-start menus!
823 // initialize channels
824 for (int i = 0; i < MaxChannels; ++i) {
825 Channels[i].Point = i + 1;
826 }
827
828 return 0;
829 }
830
831 /**
832 ** Cleanup sound server.
833 */
834 void QuitSound(void)
835 {
836 SDL_CloseAudio();
837 SoundInitialized = false;
838 delete[] MixerBuffer;
839 MixerBuffer = NULL;
840 }
841
842 //@}