aboutsummaryrefslogtreecommitdiff
path: root/audio/decoders/voc.cpp
blob: c7ba7a26245c9dbd0c870ff175bf1fc876d0c958 (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
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
/* 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/debug.h"
#include "common/endian.h"
#include "common/util.h"
#include "common/stream.h"
#include "common/textconsole.h"
#include "common/list.h"

#include "audio/audiostream.h"
#include "audio/decoders/raw.h"
#include "audio/decoders/voc.h"

namespace Audio {

namespace {

bool checkVOCHeader(Common::ReadStream &stream) {
	VocFileHeader fileHeader;

	if (stream.read(&fileHeader, 8) != 8)
		return false;

	if (!memcmp(&fileHeader, "VTLK", 4)) {
		if (stream.read(&fileHeader, sizeof(VocFileHeader)) != sizeof(VocFileHeader))
			return false;
	} else if (!memcmp(&fileHeader, "Creative", 8)) {
		if (stream.read(((byte *)&fileHeader) + 8, sizeof(VocFileHeader) - 8) != sizeof(VocFileHeader) - 8)
			return false;
	} else {
		return false;
	}

	if (memcmp(fileHeader.desc, "Creative Voice File", 19) != 0)
		return false;
	//if (fileHeader.desc[19] != 0x1A)
	//	debug(3, "checkVOCHeader: Partially invalid header");

	int32 offset = FROM_LE_16(fileHeader.datablock_offset);
	int16 version = FROM_LE_16(fileHeader.version);
	int16 code = FROM_LE_16(fileHeader.id);

	if (offset != sizeof(VocFileHeader))
		return false;

	// 0x100 is an invalid VOC version used by German version of DOTT (Disk) and
	// French version of Simon the Sorcerer 2 (CD)
	if (version != 0x010A && version != 0x0114 && version != 0x0100)
		return false;

	if (code != ~version + 0x1234)
		return false;

	return true;
}

class VocStream : public SeekableAudioStream {
public:
	VocStream(Common::SeekableReadStream *stream, bool isUnsigned, DisposeAfterUse::Flag disposeAfterUse);
	~VocStream();

	virtual int readBuffer(int16 *buffer, const int numSamples);

	virtual bool isStereo() const { return false; }

	virtual int getRate() const { return _rate; }

	virtual bool endOfData() const { return (_curBlock == _blocks.end()) && (_blockLeft == 0); }

	virtual bool seek(const Timestamp &where);

	virtual Timestamp getLength() const { return _length; }
private:
	void preProcess();

	Common::SeekableReadStream *const _stream;
	const DisposeAfterUse::Flag _disposeAfterUse;

	const bool _isUnsigned;

	int _rate;
	Timestamp _length;

	struct Block {
		uint8 code;
		uint32 length;

		union {
			struct {
				uint32 offset;
				int rate;
				int samples;
			} sampleBlock;

			struct {
				int count;
			} loopBlock;
		};
	};

	typedef Common::List<Block> BlockList;
	BlockList _blocks;

	BlockList::const_iterator _curBlock;
	uint32 _blockLeft;

	/**
	 * Advance one block in the stream in case
	 * the current one is empty.
	 */
	void updateBlockIfNeeded();

	// Do some internal buffering for systems with really slow slow disk i/o
	enum {
		/**
		 * How many samples we can buffer at once.
		 *
		 * TODO: Check whether this size suffices
		 * for systems with slow disk I/O.
		 */
		kSampleBufferLength = 2048
	};
	byte _buffer[kSampleBufferLength];

	/**
	 * Fill the temporary sample buffer used in readBuffer.
	 *
	 * @param maxSamples Maximum samples to read.
	 * @return actual count of samples read.
	 */
	int fillBuffer(int maxSamples);
};

VocStream::VocStream(Common::SeekableReadStream *stream, bool isUnsigned, DisposeAfterUse::Flag disposeAfterUse)
	: _stream(stream), _disposeAfterUse(disposeAfterUse), _isUnsigned(isUnsigned), _rate(0),
	  _length(), _blocks(), _curBlock(_blocks.end()), _blockLeft(0), _buffer() {
	preProcess();
}

VocStream::~VocStream() {
	if (_disposeAfterUse == DisposeAfterUse::YES)
		delete _stream;
}

int VocStream::readBuffer(int16 *buffer, const int numSamples) {
	int samplesLeft = numSamples;
	while (samplesLeft > 0) {
		// Try to read up to "samplesLeft" samples.
		int len = fillBuffer(samplesLeft);

		// In case we were not able to read any samples
		// we will stop reading here.
		if (!len)
			break;

		// Adjust the samples left to read.
		samplesLeft -= len;

		// Copy the data to the caller's buffer.
		const byte *src = _buffer;
		while (len-- > 0)
			*buffer++ = (*src++ << 8) ^ (_isUnsigned ? 0x8000 : 0);
	}

	return numSamples - samplesLeft;
}

void VocStream::updateBlockIfNeeded() {
	// Have we now finished this block? If so, read the next block
	if (_blockLeft == 0 && _curBlock != _blocks.end()) {
		// Find the next sample block
		while (true) {
			// Next block
			++_curBlock;

			// Check whether we reached the end of the stream
			// yet.
			if (_curBlock == _blocks.end())
				return;

			// Skip all none sample blocks for now
			if (_curBlock->code != 1 && _curBlock->code != 9)
				continue;

			_stream->seek(_curBlock->sampleBlock.offset, SEEK_SET);

			// In case of an error we will stop
			// stream playback.
			if (_stream->err()) {
				_blockLeft = 0;
				_curBlock = _blocks.end();
			} else {
				_blockLeft = _curBlock->sampleBlock.samples;
			}

			return;
		}
	}
}

int VocStream::fillBuffer(int maxSamples) {
	int bufferedSamples = 0;
	byte *dst = _buffer;

	// We can only read up to "kSampleBufferLength" samples
	// so we take this into consideration, when trying to
	// read up to maxSamples.
	maxSamples = MIN<int>(kSampleBufferLength, maxSamples);

	// We will only read up to maxSamples
	while (maxSamples > 0 && !endOfData()) {
		// Calculate how many samples we can safely read
		// from the current block.
		const int len = MIN<int>(maxSamples, _blockLeft);

		// Try to read all the sample data and update the
		// destination pointer.
		const int bytesRead = _stream->read(dst, len);
		dst += bytesRead;

		// Calculate how many samples we actually read.
		const int samplesRead = bytesRead;

		// Update all status variables
		bufferedSamples += samplesRead;
		maxSamples -= samplesRead;
		_blockLeft -= samplesRead;

		// In case of an error we will stop
		// stream playback.
		if (_stream->err()) {
			_blockLeft = 0;
			_curBlock = _blocks.end();
			break;
		}

		// Advance to the next block in case the current
		// one is already finished.
		updateBlockIfNeeded();
	}

	return bufferedSamples;
}

bool VocStream::seek(const Timestamp &where) {
	// Invalidate stream
	_blockLeft = 0;
	_curBlock = _blocks.end();

	if (where > _length)
		return false;

	// Search for the block containing the requested sample
	const uint32 seekSample = convertTimeToStreamPos(where, getRate(), isStereo()).totalNumberOfFrames();
	uint32 curSample = 0;

	for (_curBlock = _blocks.begin(); _curBlock != _blocks.end(); ++_curBlock) {
		// Skip all none sample blocks for now
		if (_curBlock->code != 1 && _curBlock->code != 9)
			continue;

		uint32 nextBlockSample = curSample + _curBlock->sampleBlock.samples;

		if (nextBlockSample > seekSample)
			break;

		curSample = nextBlockSample;
	}

	if (_curBlock == _blocks.end()) {
		return ((seekSample - curSample) == 0);
	} else {
		const uint32 offset = seekSample - curSample;

		_stream->seek(_curBlock->sampleBlock.offset + offset, SEEK_SET);

		// In case of an error we will stop
		// stream playback.
		if (_stream->err()) {
			_blockLeft = 0;
			_curBlock = _blocks.end();
		} else {
			_blockLeft = _curBlock->sampleBlock.samples - offset;
		}

		return true;
	}
}

void VocStream::preProcess() {
	Block block;

	// Scan through the file and collect all blocks
	while (true) {
		block.code = _stream->readByte();
		block.length = 0;

		// If we hit EOS here we found the end of the VOC file.
		// According to http://wiki.multimedia.cx/index.php?title=Creative_Voice
		// there is no need for an "Terminator" block to be present.
		// In case we hit a "Terminator" block we also break here.
		if (_stream->eos() || block.code == 0)
			break;
		// We will allow invalid block numbers as terminators. This is needed,
		// since some games ship broken VOC files. The following occasions are
		// known:
		// - 128 is used as terminator in Simon 1 Amiga CD32
		// - Full Throttle contains a VOC file with an incorrect block length
		//   resulting in a sample (127) to be read as block code.
		if (block.code > 9) {
			warning("VocStream::preProcess: Caught %d as terminator", block.code);
			break;
		}

		block.length = _stream->readByte();
		block.length |= _stream->readByte() << 8;
		block.length |= _stream->readByte() << 16;

		// Premature end of stream => error!
		if (_stream->eos() || _stream->err()) {
			warning("VocStream::preProcess: Reading failed");
			return;
		}

		uint32 skip = 0;

		switch (block.code) {
		// Sound data
		case 1:
		// Sound data (New format)
		case 9:
			if (block.code == 1) {
				if (block.length < 2) {
					warning("Invalid sound data block length %d in VOC file", block.length);
					return;
				}

				// Read header data
				int freqDiv = _stream->readByte();
				// Prevent division through 0
				if (freqDiv == 256) {
					warning("Invalid frequency divisor 256 in VOC file");
					return;
				}
				block.sampleBlock.rate = getSampleRateFromVOCRate(freqDiv);

				int codec = _stream->readByte();
				// We only support 8bit PCM
				if (codec != 0) {
					warning("Unhandled codec %d in VOC file", codec);
					return;
				}

				block.sampleBlock.samples = skip = block.length - 2;
				block.sampleBlock.offset = _stream->pos();

				// Check the last block if there is any
				if (_blocks.size() > 0) {
					BlockList::iterator lastBlock = _blocks.end();
					--lastBlock;
					// When we have found a block 8 as predecessor
					// we need to use its settings
					if (lastBlock->code == 8) {
						block.sampleBlock.rate = lastBlock->sampleBlock.rate;
						// Remove the block since we don't need it anymore
						_blocks.erase(lastBlock);
					}
				}
			} else {
				if (block.length < 12) {
					warning("Invalid sound data (wew format) block length %d in VOC file", block.length);
					return;
				}

				block.sampleBlock.rate = _stream->readUint32LE();
				int bitsPerSample = _stream->readByte();
				// We only support 8bit PCM
				if (bitsPerSample != 8) {
					warning("Unhandled bits per sample %d in VOC file", bitsPerSample);
					return;
				}
				int channels = _stream->readByte();
				// We only support mono
				if (channels != 1) {
					warning("Unhandled channel count %d in VOC file", channels);
					return;
				}
				int codec = _stream->readUint16LE();
				// We only support 8bit PCM
				if (codec != 0) {
					warning("Unhandled codec %d in VOC file", codec);
					return;
				}
				/*uint32 reserved = */_stream->readUint32LE();
				block.sampleBlock.offset = _stream->pos();
				block.sampleBlock.samples = skip = block.length - 12;
			}

			// Check whether we found a new highest rate
			if (_rate < block.sampleBlock.rate)
				_rate = block.sampleBlock.rate;
			break;

		// Silence
		case 3: {
			if (block.length != 3) {
				warning("Invalid silence block length %d in VOC file", block.length);
				return;
			}

			block.sampleBlock.offset = 0;

			block.sampleBlock.samples = _stream->readUint16LE() + 1;
			int freqDiv = _stream->readByte();
			// Prevent division through 0
			if (freqDiv == 256) {
				warning("Invalid frequency divisor 256 in VOC file");
				return;
			}
			block.sampleBlock.rate = getSampleRateFromVOCRate(freqDiv);
			} break;

		// Repeat start
		case 6:
			if (block.length != 2) {
				warning("Invalid repeat start block length %d in VOC file", block.length);
				return;
			}

			block.loopBlock.count = _stream->readUint16LE() + 1;
			break;

		// Repeat end
		case 7:
			break;

		// Extra info
		case 8: {
			if (block.length != 4)
				return;

			int freqDiv = _stream->readUint16LE();
			// Prevent division through 0
			if (freqDiv == 65536) {
				warning("Invalid frequency divisor 65536 in VOC file");
				return;
			}

			int codec = _stream->readByte();
			// We only support RAW 8bit PCM.
			if (codec != 0) {
				warning("Unhandled codec %d in VOC file", codec);
				return;
			}

			int channels = _stream->readByte() + 1;
			// We only support mono sound right now
			if (channels != 1) {
				warning("Unhandled channel count %d in VOC file", channels);
				return;
			}

			block.sampleBlock.offset = 0;
			block.sampleBlock.samples = 0;
			block.sampleBlock.rate = 256000000L / (65536L - freqDiv);
			} break;

		default:
			warning("Unhandled code %d in VOC file (len %d)", block.code, block.length);
			// Skip the whole block and try to use the next one.
			skip = block.length;
		}

		// Premature end of stream => error!
		if (_stream->eos() || _stream->err()) {
			warning("VocStream::preProcess: Reading failed");
			return;
		}

		// Skip the rest of the block
		if (skip)
			_stream->skip(skip);

		_blocks.push_back(block);
	}

	// Since we determined the sample rate we need for playback now, we will
	// initialize the play length.
	_length = Timestamp(0, _rate);

	// Calculate the total play time and do some more sanity checks
	for (BlockList::const_iterator i = _blocks.begin(), end = _blocks.end(); i != end; ++i) {
		// Check whether we found a block 8 which survived, this is not
		// allowed to happen!
		if (i->code == 8) {
			warning("VOC file contains unused block 8");
			return;
		}

		// For now only use blocks with actual samples
		if (i->code != 1 && i->code != 9)
			continue;

		// Check the sample rate
		if (i->sampleBlock.rate != _rate) {
			warning("VOC file contains chunks with different sample rates (%d != %d)", _rate, i->sampleBlock.rate);
			return;
		}

		_length = _length.addFrames(i->sampleBlock.samples);
	}

	// Set the current block to the first block in the stream
	rewind();
}

} // End of anonymous namespace

int getSampleRateFromVOCRate(int vocSR) {
	if (vocSR == 0xa5 || vocSR == 0xa6) {
		return 11025;
	} else if (vocSR == 0xd2 || vocSR == 0xd3) {
		return 22050;
	} else {
		int sr = 1000000L / (256L - vocSR);
		// inexact sampling rates occur e.g. in the kitchen in Monkey Island,
		// very easy to reach right from the start of the game.
		//warning("inexact sample rate used: %i (0x%x)", sr, vocSR);
		return sr;
	}
}

SeekableAudioStream *makeVOCStream(Common::SeekableReadStream *stream, byte flags, DisposeAfterUse::Flag disposeAfterUse) {
	if (!checkVOCHeader(*stream)) {
		if (disposeAfterUse == DisposeAfterUse::YES)
			delete stream;
		return 0;
	}

	SeekableAudioStream *audioStream = new VocStream(stream, (flags & Audio::FLAG_UNSIGNED) != 0, disposeAfterUse);

	if (audioStream->endOfData()) {
		delete audioStream;
		return 0;
	} else {
		return audioStream;
	}
}

} // End of namespace Audio