1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 
24 #include "common/file.h"
25 #include "common/util.h"
26 #include "common/textconsole.h"
27 
28 #include "sword1/sword1.h"
29 #include "sword1/music.h"
30 
31 #include "audio/mixer.h"
32 #include "audio/audiostream.h"
33 #include "audio/decoders/aiff.h"
34 #include "audio/decoders/flac.h"
35 #include "audio/decoders/mp3.h"
36 #include "audio/decoders/vorbis.h"
37 #include "audio/decoders/wave.h"
38 #include "audio/decoders/xa.h"
39 
40 #define SMP_BUFSIZE 8192
41 
42 namespace Sword1 {
43 
44 // This means fading takes 3 seconds.
45 #define FADE_LENGTH 3
46 
47 // These functions are only called from Music, so I'm just going to
48 // assume that if locking is needed it has already been taken care of.
49 
play(const Common::String & filename,bool loop)50 bool MusicHandle::play(const Common::String &filename, bool loop) {
51 	stop();
52 
53 	// FIXME: How about using AudioStream::openStreamFile instead of the code below?
54 	// I.e.:
55 	//_audioSource = Audio::AudioStream::openStreamFile(fileBase, 0, 0, loop ? 0 : 1);
56 
57 	Audio::RewindableAudioStream *stream = 0;
58 
59 #ifdef USE_FLAC
60 	if (!stream) {
61 		if (_file.open(filename + ".flac")) {
62 			stream = Audio::makeFLACStream(&_file, DisposeAfterUse::NO);
63 			if (!stream)
64 				_file.close();
65 		}
66 	}
67 
68 	if (!stream) {
69 		if (_file.open(filename + ".fla")) {
70 			stream = Audio::makeFLACStream(&_file, DisposeAfterUse::NO);
71 			if (!stream)
72 				_file.close();
73 		}
74 	}
75 #endif
76 #ifdef USE_VORBIS
77 	if (!stream) {
78 		if (_file.open(filename + ".ogg")) {
79 			stream = Audio::makeVorbisStream(&_file, DisposeAfterUse::NO);
80 			if (!stream)
81 				_file.close();
82 		}
83 	}
84 #endif
85 #ifdef USE_MAD
86 	if (!stream) {
87 		if (_file.open(filename + ".mp3")) {
88 			stream = Audio::makeMP3Stream(&_file, DisposeAfterUse::NO);
89 			if (!stream)
90 				_file.close();
91 		}
92 	}
93 #endif
94 	if (!stream) {
95 		if (_file.open(filename + ".wav"))
96 			stream = Audio::makeWAVStream(&_file, DisposeAfterUse::NO);
97 	}
98 
99 	if (!stream) {
100 		if (_file.open(filename + ".aif"))
101 			stream = Audio::makeAIFFStream(&_file, DisposeAfterUse::NO);
102 	}
103 
104 	if (!stream)
105 		return false;
106 
107 	_audioSource = Audio::makeLoopingAudioStream(stream, loop ? 0 : 1);
108 
109 	fadeUp();
110 	return true;
111 }
112 
playPSX(uint16 id,bool loop)113 bool MusicHandle::playPSX(uint16 id, bool loop) {
114 	stop();
115 
116 	if (!_file.isOpen())
117 		if (!_file.open("tunes.dat"))
118 			return false;
119 
120 	Common::File tableFile;
121 	if (!tableFile.open("tunes.tab"))
122 		return false;
123 
124 	// The PSX demo has a broken/truncated tunes.tab. So we check here that the offset is not
125 	// beyond the end of the file.
126 	int32 tableOffset = (id - 1) * 8;
127 	if (tableOffset >= tableFile.size())
128 		return false;
129 	tableFile.seek(tableOffset, SEEK_SET);
130 	uint32 offset = tableFile.readUint32LE() * 0x800;
131 	uint32 size = tableFile.readUint32LE();
132 
133 	tableFile.close();
134 
135 	// Because of broken tunes.dat/tab in psx demo, also check that tune offset is
136 	// not over file size
137 	if ((size != 0) && (size != 0xffffffff) && ((int32)(offset + size) <= _file.size())) {
138 		_file.seek(offset, SEEK_SET);
139 		_audioSource = Audio::makeLoopingAudioStream(Audio::makeXAStream(_file.readStream(size), 11025), loop ? 0 : 1);
140 		fadeUp();
141 	} else {
142 		_audioSource = NULL;
143 		return false;
144 	}
145 
146 	return true;
147 }
148 
fadeDown()149 void MusicHandle::fadeDown() {
150 	if (streaming()) {
151 		if (_fading < 0)
152 			_fading = -_fading;
153 		else if (_fading == 0)
154 			_fading = FADE_LENGTH * getRate();
155 		_fadeSamples = FADE_LENGTH * getRate();
156 	}
157 }
158 
fadeUp()159 void MusicHandle::fadeUp() {
160 	if (streaming()) {
161 		if (_fading > 0)
162 			_fading = -_fading;
163 		else if (_fading == 0)
164 			_fading = -1;
165 		_fadeSamples = FADE_LENGTH * getRate();
166 	}
167 }
168 
endOfData() const169 bool MusicHandle::endOfData() const {
170 	return !streaming();
171 }
172 
173 // if we don't have an audiosource, return some dummy values.
streaming() const174 bool MusicHandle::streaming() const {
175 	return (_audioSource) ? (!_audioSource->endOfStream()) : false;
176 }
177 
isStereo() const178 bool MusicHandle::isStereo() const {
179 	return (_audioSource) ? _audioSource->isStereo() : false;
180 }
181 
getRate() const182 int MusicHandle::getRate() const {
183 	return (_audioSource) ? _audioSource->getRate() : 11025;
184 }
185 
readBuffer(int16 * buffer,const int numSamples)186 int MusicHandle::readBuffer(int16 *buffer, const int numSamples) {
187 	int totalSamples = 0;
188 	int16 *bufStart = buffer;
189 	if (!_audioSource)
190 		return 0;
191 	int expectedSamples = numSamples;
192 	while ((expectedSamples > 0) && _audioSource) { // _audioSource becomes NULL if we reach EOF and aren't looping
193 		int samplesReturned = _audioSource->readBuffer(buffer, expectedSamples);
194 		buffer += samplesReturned;
195 		totalSamples += samplesReturned;
196 		expectedSamples -= samplesReturned;
197 		if ((expectedSamples > 0) && _audioSource->endOfData()) {
198 			debug(2, "Music reached EOF");
199 			stop();
200 		}
201 	}
202 	// buffer was filled, now do the fading (if necessary)
203 	int samplePos = 0;
204 	while ((_fading > 0) && (samplePos < totalSamples)) { // fade down
205 		--_fading;
206 		bufStart[samplePos] = (bufStart[samplePos] * _fading) / _fadeSamples;
207 		samplePos++;
208 		if (_fading == 0) {
209 			stop();
210 			// clear the rest of the buffer
211 			memset(bufStart + samplePos, 0, (totalSamples - samplePos) * 2);
212 			return samplePos;
213 		}
214 	}
215 	while ((_fading < 0) && (samplePos < totalSamples)) { // fade up
216 		bufStart[samplePos] = -(bufStart[samplePos] * --_fading) / _fadeSamples;
217 		if (_fading <= -_fadeSamples)
218 			_fading = 0;
219 	}
220 	return totalSamples;
221 }
222 
stop()223 void MusicHandle::stop() {
224 	delete _audioSource;
225 	_audioSource = NULL;
226 	_file.close();
227 	_fading = 0;
228 }
229 
Music(Audio::Mixer * pMixer)230 Music::Music(Audio::Mixer *pMixer) {
231 	_mixer = pMixer;
232 	_sampleRate = pMixer->getOutputRate();
233 	_converter[0] = NULL;
234 	_converter[1] = NULL;
235 	_volumeL = _volumeR = 192;
236 	_mixer->playStream(Audio::Mixer::kPlainSoundType, &_soundHandle, this, -1, Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::NO, true);
237 }
238 
~Music()239 Music::~Music() {
240 	_mixer->stopHandle(_soundHandle);
241 	delete _converter[0];
242 	delete _converter[1];
243 }
244 
mixer(int16 * buf,uint32 len)245 void Music::mixer(int16 *buf, uint32 len) {
246 	Common::StackLock lock(_mutex);
247 	memset(buf, 0, 2 * len * sizeof(int16));
248 	for (int i = 0; i < ARRAYSIZE(_handles); i++)
249 		if (_handles[i].streaming() && _converter[i])
250 			_converter[i]->flow(_handles[i], buf, len, _volumeL, _volumeR);
251 }
252 
setVolume(uint8 volL,uint8 volR)253 void Music::setVolume(uint8 volL, uint8 volR) {
254 	_volumeL = (Audio::st_volume_t)volL;
255 	_volumeR = (Audio::st_volume_t)volR;
256 }
257 
giveVolume(uint8 * volL,uint8 * volR)258 void Music::giveVolume(uint8 *volL, uint8 *volR) {
259 	*volL = (uint8)_volumeL;
260 	*volR = (uint8)_volumeR;
261 }
262 
startMusic(int32 tuneId,int32 loopFlag)263 void Music::startMusic(int32 tuneId, int32 loopFlag) {
264 	if (strlen(_tuneList[tuneId]) > 0) {
265 		int newStream = 0;
266 		_mutex.lock();
267 		if (_handles[0].streaming() && _handles[1].streaming()) {
268 			int streamToStop;
269 			// Both streams playing - one must be forced to stop.
270 			if (!_handles[0].fading() && !_handles[1].fading()) {
271 				// None of them are fading. Shouldn't happen,
272 				// so it doesn't matter which one we pick.
273 				streamToStop = 0;
274 			} else if (_handles[0].fading() && !_handles[1].fading()) {
275 				// Stream 0 is fading, so pick that one.
276 				streamToStop = 0;
277 			} else if (!_handles[0].fading() && _handles[1].fading()) {
278 				// Stream 1 is fading, so pick that one.
279 				streamToStop = 1;
280 			} else {
281 				// Both streams are fading. Pick the one that
282 				// is closest to silent.
283 				if (ABS(_handles[0].fading()) < ABS(_handles[1].fading()))
284 					streamToStop = 0;
285 				else
286 					streamToStop = 1;
287 			}
288 			_handles[streamToStop].stop();
289 		}
290 		if (_handles[0].streaming()) {
291 			_handles[0].fadeDown();
292 			newStream = 1;
293 		} else if (_handles[1].streaming()) {
294 			_handles[1].fadeDown();
295 			newStream = 0;
296 		}
297 		delete _converter[newStream];
298 		_converter[newStream] = NULL;
299 		_mutex.unlock();
300 
301 		/* The handle will load the music file now. It can take a while, so unlock
302 		   the mutex before, to have the soundthread playing normally.
303 		   As the corresponding _converter is NULL, the handle will be ignored by the playing thread */
304 		if (SwordEngine::isPsx()) {
305 			if (_handles[newStream].playPSX(tuneId, loopFlag != 0)) {
306 				_mutex.lock();
307 				_converter[newStream] = Audio::makeRateConverter(_handles[newStream].getRate(), _mixer->getOutputRate(), _handles[newStream].isStereo(), false);
308 				_mutex.unlock();
309 			}
310 		} else if (_handles[newStream].play(_tuneList[tuneId], loopFlag != 0)) {
311 			_mutex.lock();
312 			_converter[newStream] = Audio::makeRateConverter(_handles[newStream].getRate(), _mixer->getOutputRate(), _handles[newStream].isStereo(), false);
313 			_mutex.unlock();
314 		} else {
315 			if (tuneId != 81) // file 81 was apparently removed from BS.
316 				warning("Can't find music file %s", _tuneList[tuneId]);
317 		}
318 	} else {
319 		_mutex.lock();
320 		if (_handles[0].streaming())
321 			_handles[0].fadeDown();
322 		if (_handles[1].streaming())
323 			_handles[1].fadeDown();
324 		_mutex.unlock();
325 	}
326 }
327 
fadeDown()328 void Music::fadeDown() {
329 	Common::StackLock lock(_mutex);
330 	for (int i = 0; i < ARRAYSIZE(_handles); i++)
331 		if (_handles[i].streaming())
332 			_handles[i].fadeDown();
333 }
334 
335 } // End of namespace Sword1
336