aboutsummaryrefslogtreecommitdiff
path: root/audio/decoders/quicktime.cpp
blob: 4b0d5e078fa460d6862133891d6659efd8d3c198 (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
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
/* 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/util.h"
#include "common/memstream.h"
#include "common/stream.h"
#include "common/textconsole.h"

#include "audio/decoders/codec.h"
#include "audio/decoders/quicktime.h"
#include "audio/decoders/quicktime_intern.h"

// Codecs
#include "audio/decoders/aac.h"
#include "audio/decoders/adpcm.h"
#include "audio/decoders/qdm2.h"
#include "audio/decoders/raw.h"

namespace Audio {

/**
 * An AudioStream that just returns silent samples and runs infinitely.
 * Used to fill in the "empty edits" in the track queue which are just
 * supposed to be no sound playing.
 */
class SilentAudioStream : public AudioStream {
public:
	SilentAudioStream(int rate, bool stereo) : _rate(rate), _isStereo(stereo) {}

	int readBuffer(int16 *buffer, const int numSamples) {
		memset(buffer, 0, numSamples * 2);
		return numSamples;
	}

	bool endOfData() const { return false; } // it never ends!
	bool isStereo() const { return _isStereo; }
	int getRate() const { return _rate; }

private:
	int _rate;
	bool _isStereo;
};

/**
 * An AudioStream wrapper that forces audio to be played in mono.
 * It currently just ignores the right channel if stereo.
 */
class ForcedMonoAudioStream : public AudioStream {
public:
	ForcedMonoAudioStream(AudioStream *parentStream, DisposeAfterUse::Flag disposeAfterUse = DisposeAfterUse::YES) :
			_parentStream(parentStream), _disposeAfterUse(disposeAfterUse) {}

	~ForcedMonoAudioStream() {
		if (_disposeAfterUse == DisposeAfterUse::YES)
				delete _parentStream;
	}

	int readBuffer(int16 *buffer, const int numSamples) {
		if (!_parentStream->isStereo())
			return _parentStream->readBuffer(buffer, numSamples);

		int16 temp[2];
		int samples = 0;

		while (samples < numSamples && !endOfData()) {
			_parentStream->readBuffer(temp, 2);
			*buffer++ = temp[0];
			samples++;
		}

		return samples;
	}

	bool endOfData() const { return _parentStream->endOfData(); }
	bool isStereo() const { return false; }
	int getRate() const { return _parentStream->getRate(); }

private:
	AudioStream *_parentStream;
	DisposeAfterUse::Flag _disposeAfterUse;
};

QuickTimeAudioDecoder::QuickTimeAudioDecoder() : Common::QuickTimeParser() {
}

QuickTimeAudioDecoder::~QuickTimeAudioDecoder() {
	for (uint32 i = 0; i < _audioTracks.size(); i++)
		delete _audioTracks[i];
}

bool QuickTimeAudioDecoder::loadAudioFile(const Common::String &filename) {
	if (!Common::QuickTimeParser::parseFile(filename))
		return false;

	init();
	return true;
}

bool QuickTimeAudioDecoder::loadAudioStream(Common::SeekableReadStream *stream, DisposeAfterUse::Flag disposeFileHandle) {
	if (!Common::QuickTimeParser::parseStream(stream, disposeFileHandle))
		return false;

	init();
	return true;
}

void QuickTimeAudioDecoder::init() {
	Common::QuickTimeParser::init();

	// Initialize all the audio streams
	// But ignore any streams we don't support
	for (uint32 i = 0; i < _tracks.size(); i++)
		if (_tracks[i]->codecType == CODEC_TYPE_AUDIO && ((AudioSampleDesc *)_tracks[i]->sampleDescs[0])->isAudioCodecSupported())
			_audioTracks.push_back(new QuickTimeAudioTrack(this, _tracks[i]));
}

Common::QuickTimeParser::SampleDesc *QuickTimeAudioDecoder::readSampleDesc(Track *track, uint32 format, uint32 descSize) {
	if (track->codecType == CODEC_TYPE_AUDIO) {
		debug(0, "Audio Codec FourCC: \'%s\'", tag2str(format));

		AudioSampleDesc *entry = new AudioSampleDesc(track, format);

		uint16 stsdVersion = _fd->readUint16BE();
		_fd->readUint16BE(); // revision level
		_fd->readUint32BE(); // vendor

		entry->_channels = _fd->readUint16BE();			 // channel count
		entry->_bitsPerSample = _fd->readUint16BE();	  // sample size

		_fd->readUint16BE(); // compression id = 0
		_fd->readUint16BE(); // packet size = 0

		entry->_sampleRate = (_fd->readUint32BE() >> 16);

		debug(0, "stsd version =%d", stsdVersion);
		if (stsdVersion == 0) {
			// Not used, except in special cases. See below.
			entry->_samplesPerFrame = entry->_bytesPerFrame = 0;
		} else if (stsdVersion == 1) {
			// Read QT version 1 fields. In version 0 these dont exist.
			entry->_samplesPerFrame = _fd->readUint32BE();
			debug(0, "stsd samples_per_frame =%d",entry->_samplesPerFrame);
			_fd->readUint32BE(); // bytes per packet
			entry->_bytesPerFrame = _fd->readUint32BE();
			debug(0, "stsd bytes_per_frame =%d", entry->_bytesPerFrame);
			_fd->readUint32BE(); // bytes per sample
		} else {
			warning("Unsupported QuickTime STSD audio version %d", stsdVersion);
			delete entry;
			return 0;
		}

		// Version 0 files don't have some variables set, so we'll do that here
		if (format == MKTAG('i', 'm', 'a', '4')) {
			entry->_samplesPerFrame = 64;
			entry->_bytesPerFrame = 34 * entry->_channels;
		}

		if (entry->_sampleRate == 0 && track->timeScale > 1)
			entry->_sampleRate = track->timeScale;

		return entry;
	}

	return 0;
}

QuickTimeAudioDecoder::QuickTimeAudioTrack::QuickTimeAudioTrack(QuickTimeAudioDecoder *decoder, Common::QuickTimeParser::Track *parentTrack) {
	_decoder = decoder;
	_parentTrack = parentTrack;
	_queue = createStream();
	_samplesQueued = 0;

	AudioSampleDesc *entry = (AudioSampleDesc *)_parentTrack->sampleDescs[0];

	if (entry->getCodecTag() == MKTAG('r', 'a', 'w', ' ') || entry->getCodecTag() == MKTAG('t', 'w', 'o', 's'))
		_parentTrack->sampleSize = (entry->_bitsPerSample / 8) * entry->_channels;

	// Initialize our edit parser too
	_curEdit = 0;
	enterNewEdit(Timestamp());

	// If the edit doesn't start on a nice boundary, set us up to skip some samples
	Timestamp editStartTime(0, _parentTrack->editList[_curEdit].mediaTime, _parentTrack->timeScale);
	Timestamp trackPosition = getCurrentTrackTime();
	if (_parentTrack->editList[_curEdit].mediaTime != -1 && trackPosition != editStartTime)
		_skipSamples = editStartTime.convertToFramerate(getRate()) - trackPosition;
}

QuickTimeAudioDecoder::QuickTimeAudioTrack::~QuickTimeAudioTrack() {
	delete _queue;
}

void QuickTimeAudioDecoder::QuickTimeAudioTrack::queueAudio(const Timestamp &length) {
	if (allDataRead() || (length.totalNumberOfFrames() != 0 && Timestamp(0, _samplesQueued, getRate()) >= length))
		return;

	do {
		Timestamp nextEditTime(0, _parentTrack->editList[_curEdit].timeOffset + _parentTrack->editList[_curEdit].trackDuration, _decoder->_timeScale);

		if (_parentTrack->editList[_curEdit].mediaTime == -1) {
			// We've got an empty edit, so fill it with silence
			Timestamp editLength(0, _parentTrack->editList[_curEdit].trackDuration, _decoder->_timeScale);

			// If we seek into the middle of an empty edit, we need to adjust
			if (_skipSamples != Timestamp()) {
				editLength = editLength - _skipSamples;
				_skipSamples = Timestamp();
			}

			queueStream(makeLimitingAudioStream(new SilentAudioStream(getRate(), isStereo()), editLength), editLength);
			_curEdit++;
			enterNewEdit(nextEditTime);
		} else {
			// Normal audio
			AudioStream *stream = readAudioChunk(_curChunk);
			Timestamp chunkLength = getChunkLength(_curChunk, _skipAACPrimer);
			_skipAACPrimer = false;
			_curChunk++;

			// If we have any samples that we need to skip (ie. we seeked into
			// the middle of a chunk), skip them here.
			if (_skipSamples != Timestamp()) {
				if (_skipSamples > chunkLength) {
					// If the amount we need to skip is greater than the size
					// of the chunk, just skip it altogether.
					_curMediaPos = _curMediaPos + chunkLength;
					_skipSamples = _skipSamples - chunkLength;
					delete stream;
					continue;
				}

				skipSamples(_skipSamples, stream);
				_curMediaPos = _curMediaPos + _skipSamples;
				chunkLength = chunkLength - _skipSamples;
				_skipSamples = Timestamp();
			}

			// Calculate our overall position within the media
			Timestamp trackPosition = getCurrentTrackTime() + chunkLength;

			// If we have reached the end of this edit (or have no more media to read),
			// we move on to the next edit
			if (trackPosition >= nextEditTime || _curChunk >= _parentTrack->chunkCount) {
				chunkLength = nextEditTime.convertToFramerate(getRate()) - getCurrentTrackTime();
				stream = makeLimitingAudioStream(stream, chunkLength);
				_curEdit++;
				enterNewEdit(nextEditTime);

				// Next time around, we'll know how much to skip
				trackPosition = getCurrentTrackTime();
				if (!allDataRead() && _parentTrack->editList[_curEdit].mediaTime != -1 && nextEditTime != trackPosition)
					_skipSamples = nextEditTime.convertToFramerate(getRate()) - trackPosition;
			} else {
				_curMediaPos = _curMediaPos + chunkLength.convertToFramerate(_curMediaPos.framerate());
			}

			queueStream(stream, chunkLength);
		}
	} while (!allDataRead() && Timestamp(0, _samplesQueued, getRate()) < length);
}

Timestamp QuickTimeAudioDecoder::QuickTimeAudioTrack::getCurrentTrackTime() const {
	if (allDataRead())
		return getLength().convertToFramerate(getRate());

	return Timestamp(0, _parentTrack->editList[_curEdit].timeOffset, _decoder->_timeScale).convertToFramerate(getRate())
			+ _curMediaPos - Timestamp(0, _parentTrack->editList[_curEdit].mediaTime, _parentTrack->timeScale).convertToFramerate(getRate());
}

void QuickTimeAudioDecoder::QuickTimeAudioTrack::queueRemainingAudio() {
	queueAudio(getLength());
}

int QuickTimeAudioDecoder::QuickTimeAudioTrack::readBuffer(int16 *buffer, const int numSamples) {
	int samplesRead = _queue->readBuffer(buffer, numSamples);
	_samplesQueued -= samplesRead / (isStereo() ? 2 : 1);
	return samplesRead;
}

bool QuickTimeAudioDecoder::QuickTimeAudioTrack::allDataRead() const {
	return _curEdit == _parentTrack->editList.size();
}

bool QuickTimeAudioDecoder::QuickTimeAudioTrack::endOfData() const {
	return allDataRead() && _queue->endOfData();
}

bool QuickTimeAudioDecoder::QuickTimeAudioTrack::seek(const Timestamp &where) {
	// Recreate the queue
	delete _queue;
	_queue = createStream();
	_samplesQueued = 0;

	if (where >= getLength()) {
		// We're done
		_curEdit = _parentTrack->editList.size();
		return true;
	}

	// Find where we are in the stream
	findEdit(where);

	// Now queue up some audio and skip whatever we need to skip
	Timestamp samplesToSkip = where.convertToFramerate(getRate()) - getCurrentTrackTime();
	queueAudio();
	skipSamples(samplesToSkip, _queue);

	return true;
}

Timestamp QuickTimeAudioDecoder::QuickTimeAudioTrack::getLength() const {
	return Timestamp(0, _parentTrack->duration, _decoder->_timeScale);
}

QueuingAudioStream *QuickTimeAudioDecoder::QuickTimeAudioTrack::createStream() const {
	AudioSampleDesc *entry = (AudioSampleDesc *)_parentTrack->sampleDescs[0];
	return makeQueuingAudioStream(entry->_sampleRate, entry->_channels == 2);
}

bool QuickTimeAudioDecoder::QuickTimeAudioTrack::isOldDemuxing() const {
	return _parentTrack->timeToSampleCount == 1 && _parentTrack->timeToSample[0].duration == 1;
}

AudioStream *QuickTimeAudioDecoder::QuickTimeAudioTrack::readAudioChunk(uint chunk) {
	AudioSampleDesc *entry = (AudioSampleDesc *)_parentTrack->sampleDescs[0];
	Common::MemoryWriteStreamDynamic *wStream = new Common::MemoryWriteStreamDynamic(DisposeAfterUse::NO);

	_decoder->_fd->seek(_parentTrack->chunkOffsets[chunk]);

	// First, we have to get the sample count
	uint32 sampleCount = getAudioChunkSampleCount(chunk);
	assert(sampleCount != 0);

	if (isOldDemuxing()) {
		// Old-style audio demuxing

		// Then calculate the right sizes
		while (sampleCount > 0) {
			uint32 samples = 0, size = 0;

			if (entry->_samplesPerFrame >= 160) {
				samples = entry->_samplesPerFrame;
				size = entry->_bytesPerFrame;
			} else if (entry->_samplesPerFrame > 1) {
				samples = MIN<uint32>((1024 / entry->_samplesPerFrame) * entry->_samplesPerFrame, sampleCount);
				size = (samples / entry->_samplesPerFrame) * entry->_bytesPerFrame;
			} else {
				samples = MIN<uint32>(1024, sampleCount);
				size = samples * _parentTrack->sampleSize;
			}

			// Now, we read in the data for this data and output it
			byte *data = (byte *)malloc(size);
			_decoder->_fd->read(data, size);
			wStream->write(data, size);
			free(data);
			sampleCount -= samples;
		}
	} else {
		// New-style audio demuxing

		// Find our starting sample
		uint32 startSample = 0;
		for (uint32 i = 0; i < chunk; i++)
			startSample += getAudioChunkSampleCount(i);

		for (uint32 i = 0; i < sampleCount; i++) {
			uint32 size = (_parentTrack->sampleSize != 0) ? _parentTrack->sampleSize : _parentTrack->sampleSizes[i + startSample];

			// Now, we read in the data for this data and output it
			byte *data = (byte *)malloc(size);
			_decoder->_fd->read(data, size);
			wStream->write(data, size);
			free(data);
		}
	}

	AudioStream *audioStream = entry->createAudioStream(new Common::MemoryReadStream(wStream->getData(), wStream->size(), DisposeAfterUse::YES));
	delete wStream;

	return audioStream;
}

void QuickTimeAudioDecoder::QuickTimeAudioTrack::skipSamples(const Timestamp &length, AudioStream *stream) {
	int32 sampleCount = length.convertToFramerate(getRate()).totalNumberOfFrames();

	if (sampleCount <= 0)
		return;

	if (isStereo())
		sampleCount *= 2;

	int16 *tempBuffer = new int16[sampleCount];
	uint32 result = stream->readBuffer(tempBuffer, sampleCount);
	delete[] tempBuffer;

	// If this is the queue, make sure we subtract this number from the
	// amount queued
	if (stream == _queue)
		_samplesQueued -= result / (isStereo() ? 2 : 1);
}

void QuickTimeAudioDecoder::QuickTimeAudioTrack::findEdit(const Timestamp &position) {
	// Go through the edits look for where we find out we need to be. As long
	// as the position is >= to the edit's start time, it is considered to be in that
	// edit. seek() already figured out if we reached the last edit, so we don't need
	// to handle that case here.
	for (_curEdit = 0; _curEdit < _parentTrack->editList.size() - 1; _curEdit++) {
		Timestamp nextEditTime(0, _parentTrack->editList[_curEdit + 1].timeOffset, _decoder->_timeScale);
		if (position < nextEditTime)
			break;
	}

	enterNewEdit(position);
}

void QuickTimeAudioDecoder::QuickTimeAudioTrack::enterNewEdit(const Timestamp &position) {
	_skipSamples = Timestamp(); // make sure our skip variable doesn't remain around

	// If we're at the end of the edit list, there's nothing else for us to do here
	if (allDataRead())
		return;

	// For an empty edit, we may need to adjust the start time
	if (_parentTrack->editList[_curEdit].mediaTime == -1) {
		// Just invalidate the current media position (and make sure the scale
		// is in terms of our rate so it simplifies things later)
		_curMediaPos = Timestamp(0, 0, getRate());

		// Also handle shortening of the empty edit if needed
		if (position != Timestamp())
			_skipSamples = position.convertToFramerate(_decoder->_timeScale) - Timestamp(0, _parentTrack->editList[_curEdit].timeOffset, _decoder->_timeScale);
		return;
	}

	// I really hope I never need to implement this :P
	// But, I'll throw in this error just to make sure I catch anything with this...
	if (_parentTrack->editList[_curEdit].mediaRate != 1)
		error("Unhandled QuickTime audio rate change");

	// Reinitialize the codec
	((AudioSampleDesc *)_parentTrack->sampleDescs[0])->initCodec();
	_skipAACPrimer = true;

	// First, we need to track down what audio sample we need
	// Convert our variables from the media time (position) and the edit time (based on position)
	// and the media time
	Timestamp curAudioTime = Timestamp(0, _parentTrack->editList[_curEdit].mediaTime, _parentTrack->timeScale)
		+ position.convertToFramerate(_parentTrack->timeScale)
		- Timestamp(0, _parentTrack->editList[_curEdit].timeOffset, _decoder->_timeScale).convertToFramerate(_parentTrack->timeScale);

	uint32 sample = curAudioTime.totalNumberOfFrames();
	uint32 seekSample = sample;

	if (!isOldDemuxing()) {
		// For MPEG-4 style demuxing, we need to track down the sample based on the time
		// The old style demuxing doesn't require this because each "sample"'s duration
		// is just 1
		uint32 curSample = 0;
		seekSample = 0;

		for (int32 i = 0; i < _parentTrack->timeToSampleCount; i++) {
			uint32 sampleCount = _parentTrack->timeToSample[i].count * _parentTrack->timeToSample[i].duration;

			if (sample < curSample + sampleCount) {
				seekSample += (sample - curSample) / _parentTrack->timeToSample[i].duration;
				break;
			}

			seekSample += _parentTrack->timeToSample[i].count;
			curSample += sampleCount;
		}
	}

	// Now to track down what chunk it's in
	uint32 totalSamples = 0;
	_curChunk = 0;
	for (uint32 i = 0; i < _parentTrack->chunkCount; i++, _curChunk++) {
		uint32 chunkSampleCount = getAudioChunkSampleCount(i);

		if (seekSample < totalSamples + chunkSampleCount)
			break;

		totalSamples += chunkSampleCount;
	}

	// Now we get to have fun and convert *back* to an actual time
	// We don't want the sample count to be modified at this point, though
	if (!isOldDemuxing())
		totalSamples = getAACSampleTime(totalSamples);

	_curMediaPos = Timestamp(0, totalSamples, getRate());
}

void QuickTimeAudioDecoder::QuickTimeAudioTrack::queueStream(AudioStream *stream, const Timestamp &length) {
	// If the samples are stereo and the container is mono, force the samples
	// to be mono.
	if (stream->isStereo() && !isStereo())
		_queue->queueAudioStream(new ForcedMonoAudioStream(stream, DisposeAfterUse::YES), DisposeAfterUse::YES);
	else
		_queue->queueAudioStream(stream, DisposeAfterUse::YES);

	_samplesQueued += length.convertToFramerate(getRate()).totalNumberOfFrames();
}

uint32 QuickTimeAudioDecoder::QuickTimeAudioTrack::getAudioChunkSampleCount(uint chunk) const {
	uint32 sampleCount = 0;

	for (uint32 i = 0; i < _parentTrack->sampleToChunkCount; i++)
		if (chunk >= _parentTrack->sampleToChunk[i].first)
			sampleCount = _parentTrack->sampleToChunk[i].count;

	return sampleCount;
}

Timestamp QuickTimeAudioDecoder::QuickTimeAudioTrack::getChunkLength(uint chunk, bool skipAACPrimer) const {
	uint32 chunkSampleCount = getAudioChunkSampleCount(chunk);

	if (isOldDemuxing())
		return Timestamp(0, chunkSampleCount, getRate());

	// AAC needs some extra handling, of course
	return Timestamp(0, getAACSampleTime(chunkSampleCount, skipAACPrimer), getRate());
}

uint32 QuickTimeAudioDecoder::QuickTimeAudioTrack::getAACSampleTime(uint32 totalSampleCount, bool skipAACPrimer) const{
	uint32 curSample = 0;
	uint32 time = 0;

	for (int32 i = 0; i < _parentTrack->timeToSampleCount; i++) {
		uint32 sampleCount = _parentTrack->timeToSample[i].count;

		if (totalSampleCount < curSample + sampleCount) {
			time += (totalSampleCount - curSample) * _parentTrack->timeToSample[i].duration;
			break;
		}

		time += _parentTrack->timeToSample[i].count * _parentTrack->timeToSample[i].duration;
		curSample += sampleCount;
	}

	// The first chunk of AAC contains "duration" samples that are used as a primer
	// We need to subtract that number from the duration for the first chunk. See:
	// http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFAppenG/QTFFAppenG.html#//apple_ref/doc/uid/TP40000939-CH2-SW1
	// The skipping of both the primer and the remainder are handled by the AAC code,
	// whereas the timing of the remainder are handled by this time-to-sample chunk
	// code already.
	// We have to do this after each time we reinitialize the codec
	if (skipAACPrimer) {
		assert(_parentTrack->timeToSampleCount > 0);
		time -= _parentTrack->timeToSample[0].duration;
	}

	return time;
}

QuickTimeAudioDecoder::AudioSampleDesc::AudioSampleDesc(Common::QuickTimeParser::Track *parentTrack, uint32 codecTag) : Common::QuickTimeParser::SampleDesc(parentTrack, codecTag) {
	_channels = 0;
	_sampleRate = 0;
	_samplesPerFrame = 0;
	_bytesPerFrame = 0;
	_bitsPerSample = 0;
	_codec = 0;
}

QuickTimeAudioDecoder::AudioSampleDesc::~AudioSampleDesc() {
	delete _codec;
}

bool QuickTimeAudioDecoder::AudioSampleDesc::isAudioCodecSupported() const {
	// Check if the codec is a supported codec
	if (_codecTag == MKTAG('t', 'w', 'o', 's') || _codecTag == MKTAG('r', 'a', 'w', ' ') || _codecTag == MKTAG('i', 'm', 'a', '4'))
		return true;

#ifdef AUDIO_QDM2_H
	if (_codecTag == MKTAG('Q', 'D', 'M', '2'))
		return true;
#endif

	if (_codecTag == MKTAG('m', 'p', '4', 'a')) {
		Common::String audioType;
		switch (_objectTypeMP4) {
		case 0x40: // AAC
#ifdef USE_FAAD
			return true;
#else
			audioType = "AAC";
			break;
#endif
		default:
			audioType = "Unknown";
			break;
		}
		warning("No MPEG-4 audio (%s) support", audioType.c_str());
	} else {
		warning("Audio Codec Not Supported: \'%s\'", tag2str(_codecTag));
	}

	return false;
}

AudioStream *QuickTimeAudioDecoder::AudioSampleDesc::createAudioStream(Common::SeekableReadStream *stream) const {
	if (!stream)
		return 0;

	if (_codec) {
		// If we've loaded a codec, make sure we use first
		AudioStream *audioStream = _codec->decodeFrame(*stream);
		delete stream;
		return audioStream;
	} else if (_codecTag == MKTAG('t', 'w', 'o', 's') || _codecTag == MKTAG('r', 'a', 'w', ' ')) {
		// Fortunately, most of the audio used in Myst videos is raw...
		uint16 flags = 0;
		if (_codecTag == MKTAG('r', 'a', 'w', ' '))
			flags |= FLAG_UNSIGNED;
		if (_channels == 2)
			flags |= FLAG_STEREO;
		if (_bitsPerSample == 16)
			flags |= FLAG_16BITS;
		uint32 dataSize = stream->size();
		byte *data = (byte *)malloc(dataSize);
		stream->read(data, dataSize);
		delete stream;
		return makeRawStream(data, dataSize, _sampleRate, flags);
	} else if (_codecTag == MKTAG('i', 'm', 'a', '4')) {
		// Riven uses this codec (as do some Myst ME videos)
		return makeADPCMStream(stream, DisposeAfterUse::YES, stream->size(), kADPCMApple, _sampleRate, _channels, 34);
	}

	error("Unsupported audio codec");
	return NULL;
}

void QuickTimeAudioDecoder::AudioSampleDesc::initCodec() {
	delete _codec; _codec = 0;

	switch (_codecTag) {
	case MKTAG('Q', 'D', 'M', '2'):
#ifdef AUDIO_QDM2_H
		_codec = makeQDM2Decoder(_extraData);
#endif
		break;
	case MKTAG('m', 'p', '4', 'a'):
#ifdef USE_FAAD
		if (_objectTypeMP4 == 0x40)
			_codec = makeAACDecoder(_extraData);
#endif
		break;
	default:
		break;
	}
}

/**
 * A wrapper around QuickTimeAudioDecoder that implements the SeekableAudioStream API
 */
class QuickTimeAudioStream : public SeekableAudioStream, public QuickTimeAudioDecoder {
public:
	QuickTimeAudioStream() {}
	~QuickTimeAudioStream() {}

	bool openFromFile(const Common::String &filename) {
		return QuickTimeAudioDecoder::loadAudioFile(filename) && !_audioTracks.empty();
	}

	bool openFromStream(Common::SeekableReadStream *stream, DisposeAfterUse::Flag disposeFileHandle) {
		return QuickTimeAudioDecoder::loadAudioStream(stream, disposeFileHandle) && !_audioTracks.empty();
	}

	// AudioStream API
	int readBuffer(int16 *buffer, const int numSamples) {
		int samples = 0;

		while (samples < numSamples && !endOfData()) {
			if (!_audioTracks[0]->hasDataInQueue())
				_audioTracks[0]->queueAudio();
			samples += _audioTracks[0]->readBuffer(buffer + samples, numSamples - samples);
		}

		return samples;
	}

	bool isStereo() const { return _audioTracks[0]->isStereo(); }
	int getRate() const { return _audioTracks[0]->getRate(); }
	bool endOfData() const { return _audioTracks[0]->endOfData(); }

	// SeekableAudioStream API
	bool seek(const Timestamp &where) { return _audioTracks[0]->seek(where); }
	Timestamp getLength() const { return _audioTracks[0]->getLength(); }
};

SeekableAudioStream *makeQuickTimeStream(const Common::String &filename) {
	QuickTimeAudioStream *audioStream = new QuickTimeAudioStream();

	if (!audioStream->openFromFile(filename)) {
		delete audioStream;
		return 0;
	}

	return audioStream;
}

SeekableAudioStream *makeQuickTimeStream(Common::SeekableReadStream *stream, DisposeAfterUse::Flag disposeAfterUse) {
	QuickTimeAudioStream *audioStream = new QuickTimeAudioStream();

	if (!audioStream->openFromStream(stream, disposeAfterUse)) {
		delete audioStream;
		return 0;
	}

	return audioStream;
}

} // End of namespace Audio