File: sound_server.cpp

package info (click to toggle)
boswars 2.7%2Bsvn160110-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 96,880 kB
  • sloc: cpp: 57,441; python: 1,759; makefile: 34; sh: 26
file content (842 lines) | stat: -rw-r--r-- 18,434 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//     ____                _       __               
//    / __ )____  _____   | |     / /___ ___________
//   / __  / __ \/ ___/   | | /| / / __ `/ ___/ ___/
//  / /_/ / /_/ (__  )    | |/ |/ / /_/ / /  (__  ) 
// /_____/\____/____/     |__/|__/\__,_/_/  /____/  
//                                              
//       A futuristic real-time strategy game.
//          This file is part of Bos Wars.
//
/**@name sound_server.cpp - The sound server (hardware layer and so on) */
//
//      (c) Copyright 1998-2008 by Lutz Sammer, Fabrice Rossi, and
//                                 Jimmy Salmon
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; only version 2 of the License.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//      02111-1307, USA.
//


//@{

/*----------------------------------------------------------------------------
--  Includes
----------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "stratagus.h"

#include "SDL.h"

#include "sound_server.h"
#include "iolib.h"
#include "iocompat.h"


/*----------------------------------------------------------------------------
--  Variables
----------------------------------------------------------------------------*/

static bool SoundInitialized;    /// is sound initialized
static bool MusicPlaying;        /// flag true if playing music

static int EffectsVolume = 128;  /// effects sound volume
static int MusicVolume = 128;    /// music volume

static bool MusicEnabled = true;
static bool EffectsEnabled = true;

	/// Channels for sound effects and unit speach
struct SoundChannel {
	CSample *Sample;       /// sample to play
	unsigned char Volume;  /// Volume of this channel
	signed char Stereo;    /// stereo location of sound (-128 left, 0 center, 127 right)

	bool Playing;          /// channel is currently playing
	int Point;             /// point in sample if playing or next free channel

	void (*FinishedCallback)(int channel); /// Callback for when a sample finishes playing
};

#define MaxChannels 32     /// How many channels are supported

static SoundChannel Channels[MaxChannels];
static int NextFreeChannel;

static struct {
	CSample *Sample;       /// Music sample
	void (*FinishedCallback)(); /// Callback for when music finishes playing
} MusicChannel;

static void ChannelFinished(int channel);

static int *MixerBuffer;
static int MixerBufferSize;


/*----------------------------------------------------------------------------
--  Mixers
----------------------------------------------------------------------------*/

/**
**  Convert RAW sound data to 44100 hz, Stereo, 16 bits per channel
**
**  @param src        Source buffer
**  @param dest       Destination buffer
**  @param frequency  Frequency of source
**  @param chansize   Bitrate in bytes per channel of source
**  @param channels   Number of channels of source
**  @param bytes      Number of compressed bytes to read
**
**  @return           Number of bytes written in 'dest'
*/
static int ConvertToStereo32(const char *src, char *dest, int frequency,
	int chansize, int channels, int bytes)
{
	SDL_AudioCVT acvt;
	Uint16 format;

	if (chansize == 1) {
		format = AUDIO_U8;
	} else {
		format = AUDIO_S16SYS;
	}
	SDL_BuildAudioCVT(&acvt, format, channels, frequency, AUDIO_S16SYS, 2, 44100);

	acvt.buf = (Uint8 *)dest;
	memcpy(dest, src, bytes);
	acvt.len = bytes;

	SDL_ConvertAudio(&acvt);

	return acvt.len_mult * bytes;
}

/**
**  Mix music to stereo 32 bit.
**
**  @param buffer  Buffer for mixed samples.
**  @param size    Number of samples that fits into buffer.
**
**  @todo this functions can be called from inside the SDL audio callback,
**  which is bad, the buffer should be precalculated.
*/
static void MixMusicToStereo32(int *buffer, int size)
{
	int i;
	int n;
	int len;
	short *buf;
	char *tmp;
	int div;

	if (MusicPlaying) {
		Assert(MusicChannel.Sample);

		len = size * sizeof(*buf);
		tmp = new char[len];
		buf = new short[len];

		div = 176400 / (MusicChannel.Sample->Frequency * (MusicChannel.Sample->SampleSize / 8)
				* MusicChannel.Sample->Channels);

		size = MusicChannel.Sample->Read(tmp, len / div);

		n = ConvertToStereo32((char *)(tmp), (char *)buf, MusicChannel.Sample->Frequency,
			MusicChannel.Sample->SampleSize / 8, MusicChannel.Sample->Channels, size);

		for (i = 0; i < n / (int)sizeof(*buf); ++i) {
			// Add to our samples
			// FIXME: why taking out '/ 2' leads to distortion
			buffer[i] += buf[i] * MusicVolume / MaxVolume / 2;
		}

		delete[] tmp;
		delete[] buf;

		if (n < len) { // End reached
			MusicPlaying = false;
			delete MusicChannel.Sample;
			MusicChannel.Sample = NULL;

			if (MusicChannel.FinishedCallback) {
				MusicChannel.FinishedCallback();
			}
		}
	}
}

/**
**  Mix sample to buffer.
**
**  The input samples are adjusted by the local volume and resampled
**  to the output frequence.
**
**  @param sample  Input sample
**  @param index   Position into input sample
**  @param volume  Volume of the input sample
**  @param stereo  Stereo (left/right) position of sample
**  @param buffer  Output buffer
**  @param size    Size of output buffer (in samples per channel)
**
**  @return        The number of bytes used to fill buffer
**
**  @todo          Can mix faster if signed 8 bit buffers are used.
*/
static int MixSampleToStereo32(CSample *sample, int index, unsigned char volume,
	char stereo, int *buffer, int size)
{
	int local_volume;
	unsigned char left;
	unsigned char right;
	int i;
	static int buf[SOUND_BUFFER_SIZE / 2];
	int div;

	div = 176400 / (sample->Frequency * (sample->SampleSize / 8)
			* sample->Channels);

	local_volume = (int)volume * EffectsVolume / MaxVolume;

	if (stereo < 0) {
		left = 128;
		right = 128 + stereo;
	} else {
		left = 128 - stereo;
		right = 128;
	}

	Assert(!(index & 1));

	if (size >= (sample->Len - index) * div / 2) {
		size = (sample->Len - index) * div / 2;
	}

	size = ConvertToStereo32((char *)(sample->Buffer + index), (char *)buf, sample->Frequency,
			sample->SampleSize / 8, sample->Channels,
			size * 2 / div);

	size /= 2;
	for (i = 0; i < size; i += 2) {
		// FIXME: why taking out '/ 2' leads to distortion
		buffer[i] += ((short *)buf)[i] * local_volume * left / 128 / MaxVolume / 2;
		buffer[i + 1] += ((short *)buf)[i + 1] * local_volume * right / 128 / MaxVolume / 2;
	}

	return 2 * size / div;
}

/**
**  Mix channels to stereo 32 bit.
**
**  @param buffer  Buffer for mixed samples.
**  @param size    Number of samples that fits into buffer.
**
**  @return        How many channels become free after mixing them.
*/
static int MixChannelsToStereo32(int *buffer, int size)
{
	int channel;
	int i;
	int new_free_channels;

	new_free_channels = 0;
	for (channel = 0; channel < MaxChannels; ++channel) {
		if (Channels[channel].Playing && Channels[channel].Sample) {
			i = MixSampleToStereo32(Channels[channel].Sample,
				Channels[channel].Point, Channels[channel].Volume,
				Channels[channel].Stereo, buffer, size);
			Channels[channel].Point += i;
			Assert(Channels[channel].Point <= Channels[channel].Sample->Len);

			if (Channels[channel].Point == Channels[channel].Sample->Len) {
				ChannelFinished(channel);
				++new_free_channels;
			}
		}
	}

	return new_free_channels;
}

/**
**  Clip mix to output stereo 16 signed bit.
**
**  @param mix     signed 32 bit input.
**  @param size    number of samples in input.
**  @param output  clipped 16 signed bit output buffer.
*/
static void ClipMixToStereo16(const int *mix, int size, short *output)
{
	int s;
	const int *end;

	end = mix + size;
	while (mix < end) {
		s = (*mix++);
		if (s > SHRT_MAX) {
			*output++ = SHRT_MAX;
		} else if (s < SHRT_MIN) {
			*output++ = SHRT_MIN;
		} else {
			*output++ = s;
		}
	}
}

/**
**  Mix into buffer.
**
**  @param buffer   Buffer to be filled with samples. Buffer must be big enough.
**  @param samples  Number of samples.
*/
static void MixIntoBuffer(void *buffer, int samples)
{
	if (samples > MixerBufferSize) {
		delete[] MixerBuffer;
		MixerBuffer = new int[samples];
		MixerBufferSize = samples;
	}

	// FIXME: can save the memset here, if first channel sets the values
	memset(MixerBuffer, 0, samples * sizeof(*MixerBuffer));

	if (EffectsEnabled) {
		// Add channels to mixer buffer
		MixChannelsToStereo32(MixerBuffer, samples);
	}
	if (MusicEnabled) {
		// Add music to mixer buffer
		MixMusicToStereo32(MixerBuffer, samples);
	}

	ClipMixToStereo16(MixerBuffer, samples, (short *)buffer);
}

/**
**  Fill buffer for the sound card.
**
**  @see SDL_OpenAudio
**
**  @param udata   the pointer stored in userdata field of SDL_AudioSpec.
**  @param stream  pointer to buffer you want to fill with information.
**  @param len     is length of audio buffer in bytes.
*/
static void FillAudio(void *udata, Uint8 *stream, int len)
{
	len >>= 1;
	MixIntoBuffer(stream, len);
}

/*----------------------------------------------------------------------------
--  Effects
----------------------------------------------------------------------------*/

/**
**  A channel is finished playing
*/
static void ChannelFinished(int channel)
{
	if (Channels[channel].FinishedCallback) {
		Channels[channel].FinishedCallback(channel);
	}

	Channels[channel].Playing = false;
	Channels[channel].Point = NextFreeChannel;
	NextFreeChannel = channel;
}

/**
**  Put a sound request in the next free channel.
*/
static int FillChannel(CSample *sample, unsigned char volume, char stereo)
{
	Assert(NextFreeChannel < MaxChannels);

	int old_free = NextFreeChannel;
	int next_free = Channels[NextFreeChannel].Point;

	Channels[NextFreeChannel].Volume = volume;
	Channels[NextFreeChannel].Point = 0;
	Channels[NextFreeChannel].Playing = true;
	Channels[NextFreeChannel].Sample = sample;
	Channels[NextFreeChannel].Stereo = stereo;
	Channels[NextFreeChannel].FinishedCallback = NULL;

	NextFreeChannel = next_free;

	return old_free;
}

/**
**  Set the channel volume
**
**  @param channel  Channel to set
**  @param volume   New volume, <0 will not set the volume
**
**  @return         Current volume of the channel, -1 for error
*/
int SetChannelVolume(int channel, int volume)
{
	if (channel < 0 || channel >= MaxChannels) {
		return -1;
	}

	if (volume < 0) {
		volume = Channels[channel].Volume;
	} else {
		SDL_LockAudio();

		if (volume > MaxVolume) {
			volume = MaxVolume;
		}
		Channels[channel].Volume = volume;

		SDL_UnlockAudio();
	}

	return volume;
}

/**
**  Set the channel stereo
**
**  @param channel  Channel to set
**  @param stereo   -128 to 127, out of range will not set the stereo
**
**  @return         Current stereo of the channel, -1 for error
*/
int SetChannelStereo(int channel, int stereo)
{
	if (channel < 0 || channel >= MaxChannels) {
		return -1;
	}

	if (stereo < -128 || stereo > 127) {
		stereo = Channels[channel].Stereo;
	} else {
		SDL_LockAudio();

		if (stereo > 127) {
			stereo = 127;
		} else if (stereo < -128) {
			stereo = -128;
		}
		Channels[channel].Stereo = stereo;

		SDL_UnlockAudio();
	}

	return stereo;
}

/**
**  Set the channel's callback for when a sound finishes playing
**
**  @param channel   Channel to set
**  @param callback  Callback to call when the sound finishes
*/
void SetChannelFinishedCallback(int channel, void (*callback)(int channel))
{
	if (channel < 0 || channel >= MaxChannels) {
		return;
	}

	Channels[channel].FinishedCallback = callback;
}

/**
**  Get the sample playing on a channel
*/
CSample *GetChannelSample(int channel)
{
	if (channel < 0 || channel >= MaxChannels) {
		return NULL;
	}

	return Channels[channel].Sample;
}

/**
**  Stop a channel
**
**  @param channel  Channel to stop
*/
void StopChannel(int channel)
{
	SDL_LockAudio();

	if (channel >= 0 && channel < MaxChannels) {
		if (Channels[channel].Playing) {
			ChannelFinished(channel);
		}
	}

	SDL_UnlockAudio();
}

/**
**  Stop all channels
*/
void StopAllChannels()
{
	SDL_LockAudio();

	for (int i = 0; i < MaxChannels; ++i) {
		if (Channels[i].Playing) {
			ChannelFinished(i);
		}
	}

	SDL_UnlockAudio();
}

/**
**  Load a sample
**
**  @param name  File name of sample (short version).
**
**  @return      General sample loaded from file into memory.
**
**  @todo  Add streaming, caching support.
*/
CSample *LoadSample(const std::string &name)
{
	CSample *sample;
	char buf[PATH_MAX];

	LibraryFileName(name.c_str(), buf, sizeof(buf));

	if ((sample = LoadWav(buf, PlayAudioLoadInMemory))) {
		return sample;
	}
#ifdef USE_VORBIS
	if ((sample = LoadVorbis(buf, PlayAudioLoadInMemory))) {
		return sample;
	}
#endif

	fprintf(stderr, "Can't load the sound `%s'\n", name.c_str());

	return sample;
}

/**
**  Play a sound sample
**
**  @param sample  Sample to play
**
**  @return        Channel number, -1 for error
*/
int PlaySample(CSample *sample)
{
	int channel = -1;

	SDL_LockAudio();

	if (SoundEnabled() && EffectsEnabled && sample &&
			NextFreeChannel != MaxChannels) {
		channel = FillChannel(sample, EffectsVolume, 0);
	}

	SDL_UnlockAudio();

	return channel;
}

/**
**  Play a sound file
**
**  @param name  Filename of a sound to play
**
**  @return      Channel number the sound is playing on, -1 for error
*/
int PlaySoundFile(const std::string &name)
{
	CSample *sample = LoadSample(name);
	if (sample) {
		return PlaySample(sample);
	}
	return -1;
}

/**
**  Set the global sound volume.
**
**  @param volume  the sound volume 0-255
*/
void SetEffectsVolume(int volume)
{
	if (volume < 0) {
		EffectsVolume = 0;
	} else if (volume > MaxVolume) {
		EffectsVolume = MaxVolume;
	} else {
		EffectsVolume = volume;
	}
}

/**
**  Get effects volume
*/
int GetEffectsVolume(void)
{
	return EffectsVolume;
}

/**
**  Set effects enabled
*/
void SetEffectsEnabled(bool enabled)
{
	EffectsEnabled = enabled;
}

/**
**  Check if effects are enabled
*/
bool IsEffectsEnabled(void)
{
	return EffectsEnabled;
}

/*----------------------------------------------------------------------------
--  Music
----------------------------------------------------------------------------*/

/**
**  Set the music finished callback
*/
void SetMusicFinishedCallback(void (*callback)(void))
{
	MusicChannel.FinishedCallback = callback;
}

/**
**  Play a music file.
**
**  @param sample  Music sample.
**
**  @return        0 if music is playing, -1 if not.
*/
int PlayMusic(CSample *sample)
{
	if (sample) {
		StopMusic();
		MusicChannel.Sample = sample;
		MusicPlaying = true;
		return 0;
	} else {
		DebugPrint("Could not play sample\n");
		return -1;
	}
}

/**
**  Play a music file.
**
**  @param file  Name of music file, format is automatically detected.
**
**  @return      0 if music is playing, -1 if not.
*/
int PlayMusic(const std::string &file)
{
	char name[PATH_MAX];
	CSample *sample;

	if (!SoundEnabled() || !IsMusicEnabled()) {
		return -1;
	}

	LibraryFileName(file.c_str(), name, sizeof(name));

	DebugPrint("play music %s\n" _C_ name);

	sample = LoadWav(name, PlayAudioStream);

#ifdef USE_VORBIS
	if (!sample) {
		sample = LoadVorbis(name, PlayAudioStream);
	}
#endif

	if (sample) {
		StopMusic();
		MusicChannel.Sample = sample;
		MusicPlaying = true;
		return 0;
	} else {
		DebugPrint("Could not play %s\n" _C_ file.c_str());
		return -1;
	}
}

/**
**  Stop the current playing music.
*/
void StopMusic(void)
{
	if (MusicPlaying) {
		MusicPlaying = false;
		if (MusicChannel.Sample) {
			SDL_LockAudio();
			delete MusicChannel.Sample;
			MusicChannel.Sample = NULL;
			SDL_UnlockAudio();
		}
	}
}

/**
**  Set the music volume.
**
**  @param volume  the music volume 0-255
*/
void SetMusicVolume(int volume)
{
	if (volume < 0) {
		MusicVolume = 0;
	} else if (volume > MaxVolume) {
		MusicVolume = MaxVolume;
	} else {
		MusicVolume = volume;
	}
}

/**
**  Get music volume
*/
int GetMusicVolume(void)
{
	return MusicVolume;
}

/**
**  Set music enabled
*/
void SetMusicEnabled(bool enabled)
{
	if (enabled) {
		MusicEnabled = true;
	} else {
		MusicEnabled = false;
		StopMusic();
	}
}

/**
**  Check if music is enabled
*/
bool IsMusicEnabled(void)
{
	return MusicEnabled;
}

/**
**  Check if music is playing
*/
bool IsMusicPlaying(void)
{
	return MusicPlaying;
}

/*----------------------------------------------------------------------------
--  Init
----------------------------------------------------------------------------*/

/**
**  Check if sound is enabled
*/
bool SoundEnabled(void)
{
	return SoundInitialized;
}

/**
**  Initialize sound card hardware part with SDL.
**
**  @param freq  Sample frequency (44100,22050,11025 hz).
**  @param size  Sample size (8bit, 16bit)
**
**  @return      True if failure, false if everything ok.
*/
static int InitSdlSound(int freq, int size)
{
	SDL_AudioSpec wanted;

	wanted.freq = freq;
	if (size == 8) {
		wanted.format = AUDIO_U8;
	} else if (size == 16) {
		wanted.format = AUDIO_S16SYS;
	} else {
		DebugPrint("Unexpected sample size %d\n" _C_ size);
		wanted.format = AUDIO_S16SYS;
	}
	wanted.channels = 2;
	wanted.samples = 4096;
	wanted.callback = FillAudio;
	wanted.userdata = NULL;

	//  Open the audio device, forcing the desired format
	if (SDL_OpenAudio(&wanted, NULL) < 0) {
		fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
		return -1;
	}
	SDL_PauseAudio(0);

	return 0;
}

/**
**  Initialize sound card.
**
**  @return  True if failure, false if everything ok.
*/
int InitSound(void)
{
	//
	// Open sound device, 8bit samples, stereo.
	//
	if (InitSdlSound(44100, 16)) {
		SoundInitialized = false;
		return 1;
	}
	SoundInitialized = true;

	// ARI: The following must be done here to allow sound to work in
	// pre-start menus!
	// initialize channels
	for (int i = 0; i < MaxChannels; ++i) {
		Channels[i].Point = i + 1;
	}

	return 0;
}

/**
**  Cleanup sound server.
*/
void QuitSound(void)
{
	SDL_CloseAudio();
	SoundInitialized = false;
	delete[] MixerBuffer;
	MixerBuffer = NULL;
}

//@}