aboutsummaryrefslogtreecommitdiff
path: root/engines/gob/sound/musplayer.cpp
blob: 3e41dc6ed1d5c380126aeab3155566f5c0471d83 (plain)
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
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * 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; either version 2
 * of the License, or (at your option) any later version.

 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "common/stream.h"
#include "common/textconsole.h"

#include "gob/sound/musplayer.h"

namespace Gob {

MUSPlayer::MUSPlayer(Audio::Mixer &mixer) : AdLib(mixer),
	_songData(0), _songDataSize(0), _playPos(0), _songID(0) {

}

MUSPlayer::~MUSPlayer() {
	unload();
}

void MUSPlayer::unload() {
	stopPlay();

	unloadSND();
	unloadMUS();
}

uint32 MUSPlayer::getSampleDelay(uint16 delay) const {
	if (delay == 0)
		return 0;

	uint32 freq = (_ticksPerBeat * _tempo) / 60;

	return ((uint32)delay * getSamplesPerSecond()) / freq;
}

void MUSPlayer::skipToTiming() {
	while (*_playPos < 0x80)
		_playPos++;

	if (*_playPos != 0xF8)
		_playPos--;
}

uint32 MUSPlayer::pollMusic(bool first) {
	if (_timbres.empty() || !_songData || !_playPos || (_playPos >= (_songData + _songDataSize))) {
		end();
		return 0;
	}

	if (first)
		return getSampleDelay(*_playPos++);

	uint16 delay = 0;
	while (delay == 0) {
		byte cmd = *_playPos;

		// Delay overflow
		if (cmd == 0xF8) {
			_playPos++;
			delay = 0xF8;
			break;
		}

		// Song end marker
		if (cmd == 0xFC) {
			end();
			return 0;
		}

		// Global command
		if (cmd == 0xF0) {
			_playPos++;

			byte type1 = *_playPos++;
			byte type2 = *_playPos++;

			if ((type1 == 0x7F) && (type2 == 0)) {
				// Tempo change, as a fraction of the base tempo

				uint32 num   = *_playPos++;
				uint32 denom = *_playPos++;

				_tempo = _baseTempo * num + ((_baseTempo * denom) >> 7);

				_playPos++;
			} else {

				// Unsupported global command, skip it
				_playPos -= 2;
				while(*_playPos++ != 0xF7)
					;
			}

			delay = *_playPos++;
			break;
		}

		// Voice command

		if (cmd >= 0x80) {
			_playPos++;

			_lastCommand = cmd;
		} else
			cmd = _lastCommand;

		uint8 voice = cmd & 0x0F;
		uint8 note, volume;
		uint16 pitch;

		switch (cmd & 0xF0) {
		case 0x80: // Note off
			_playPos += 2;
			noteOff(voice);
			break;

		case 0x90: // Note on
			note   = *_playPos++;
			volume = *_playPos++;

			if (volume) {
				setVoiceVolume(voice, volume);
				noteOn(voice, note);
			} else
				noteOff(voice);
			break;

		case 0xA0: // Set volume
			setVoiceVolume(voice, *_playPos++);
			break;

		case 0xB0:
			_playPos += 2;
			break;

		case 0xC0: // Set instrument
			setInstrument(voice, *_playPos++);
			break;

		case 0xD0:
			_playPos++;
			break;

		case 0xE0: // Pitch bend
			pitch  = *_playPos++;
			pitch += *_playPos++ << 7;
			bendVoicePitch(voice, pitch);
			break;

		default:
			warning("MUSPlayer: Unsupported command: 0x%02X", cmd);
			skipToTiming();
			break;
		}

		delay = *_playPos++;
	}

	if (delay == 0xF8) {
		delay = 240;

		if (*_playPos != 0xF8)
			delay += *_playPos++;
	}

	return getSampleDelay(delay);
}

void MUSPlayer::rewind() {
	_playPos = _songData;
	_tempo   = _baseTempo;

	_lastCommand = 0;

	setPercussionMode(_soundMode != 0);
	setPitchRange(_pitchBendRange);
}

bool MUSPlayer::loadSND(Common::SeekableReadStream &snd) {
	unloadSND();

	int timbreCount, timbrePos;
	if (!readSNDHeader(snd, timbreCount, timbrePos))
		return false;

	if (!readSNDTimbres(snd, timbreCount, timbrePos) || snd.err()) {
		unloadSND();
		return false;
	}

	return true;
}

bool MUSPlayer::readString(Common::SeekableReadStream &stream, Common::String &string, byte *buffer, uint size) {
	if (stream.read(buffer, size) != size)
		return false;

	buffer[size] = '\0';

	string = (char *) buffer;

	return true;
}

bool MUSPlayer::readSNDHeader(Common::SeekableReadStream &snd, int &timbreCount, int &timbrePos) {
	// Sanity check
	if (snd.size() <= 6) {
		warning("MUSPlayer::readSNDHeader(): File too small (%d)", snd.size());
		return false;
	}

	// Version
	const uint8 versionMajor = snd.readByte();
	const uint8 versionMinor = snd.readByte();

	if ((versionMajor != 1) && (versionMinor != 0)) {
		warning("MUSPlayer::readSNDHeader(): Unsupported version %d.%d", versionMajor, versionMinor);
		return false;
	}

	// Number of timbres and where they start
	timbreCount = snd.readUint16LE();
	timbrePos   = snd.readUint16LE();

	const uint16 minTimbrePos = 6 + timbreCount * 9;

	// Sanity check
	if (timbrePos < minTimbrePos) {
		warning("MUSPlayer::readSNDHeader(): Timbre offset too small: %d < %d", timbrePos, minTimbrePos);
		return false;
	}

	const uint32 timbreParametersSize = snd.size() - timbrePos;
	const uint32 paramSize            = kOperatorsPerVoice * kParamCount * sizeof(uint16);

	// Sanity check
	if (timbreParametersSize != (timbreCount * paramSize)) {
		warning("MUSPlayer::loadSND(): Timbre parameters size mismatch: %d != %d",
		        timbreParametersSize, timbreCount * paramSize);
		return false;
	}

	return true;
}

bool MUSPlayer::readSNDTimbres(Common::SeekableReadStream &snd, int timbreCount, int timbrePos) {
	_timbres.resize(timbreCount);

	// Read names
	byte nameBuffer[10];
	for (Common::Array<Timbre>::iterator t = _timbres.begin(); t != _timbres.end(); ++t) {
		if (!readString(snd, t->name, nameBuffer, 9)) {
			warning("MUSPlayer::readMUSTimbres(): Failed to read timbre name");
			return false;
		}
	}

	if (!snd.seek(timbrePos)) {
		warning("MUSPlayer::readMUSTimbres(): Failed to seek to timbres");
		return false;
	}

	// Read parameters
	for (Common::Array<Timbre>::iterator t = _timbres.begin(); t != _timbres.end(); ++t) {
		for (int i = 0; i < (kOperatorsPerVoice * kParamCount); i++)
			t->params[i] = snd.readUint16LE();
	}

	return true;
}

bool MUSPlayer::loadMUS(Common::SeekableReadStream &mus) {
	unloadMUS();

	if (!readMUSHeader(mus) || !readMUSSong(mus) || mus.err()) {
		unloadMUS();
		return false;
	}

	rewind();

	return true;
}

bool MUSPlayer::readMUSHeader(Common::SeekableReadStream &mus) {
	// Sanity check
	if (mus.size() <= 6)
		return false;

	// Version
	const uint8 versionMajor = mus.readByte();
	const uint8 versionMinor = mus.readByte();

	if ((versionMajor != 1) && (versionMinor != 0)) {
		warning("MUSPlayer::readMUSHeader(): Unsupported version %d.%d", versionMajor, versionMinor);
		return false;
	}

	_songID = mus.readUint32LE();

	byte nameBuffer[31];
	if (!readString(mus, _songName, nameBuffer, 30)) {
		warning("MUSPlayer::readMUSHeader(): Failed to read the song name");
		return false;
	}

	_ticksPerBeat    = mus.readByte();
	_beatsPerMeasure = mus.readByte();

	mus.skip(4); // Length of song in ticks

	_songDataSize = mus.readUint32LE();

	mus.skip(4); // Number of commands
	mus.skip(8); // Unused

	_soundMode      = mus.readByte();
	_pitchBendRange = mus.readByte();
	_baseTempo      = mus.readUint16LE();

	mus.skip(8); // Unused

	return true;
}

bool MUSPlayer::readMUSSong(Common::SeekableReadStream &mus) {
	const uint32 realSongDataSize = mus.size() - mus.pos();

	if (realSongDataSize < _songDataSize) {
		warning("MUSPlayer::readMUSSong(): File too small for the song data: %d < %d", realSongDataSize, _songDataSize);
		return false;
	}

	_songData = new byte[_songDataSize];

	if (mus.read(_songData, _songDataSize) != _songDataSize) {
		warning("MUSPlayer::readMUSSong(): Read failed");
		return false;
	}

	return true;
}

void MUSPlayer::unloadSND() {
	_timbres.clear();
}

void MUSPlayer::unloadMUS() {
	delete[] _songData;

	_songData     = 0;
	_songDataSize = 0;

	_playPos = 0;
}

uint32 MUSPlayer::getSongID() const {
	return _songID;
}

const Common::String &MUSPlayer::getSongName() const {
	return _songName;
}

void MUSPlayer::setInstrument(uint8 voice, uint8 instrument) {
	if (instrument >= _timbres.size())
		return;

	setVoiceTimbre(voice, _timbres[instrument].params);
}

} // End of namespace Gob