aboutsummaryrefslogtreecommitdiff
path: root/video/video_decoder.cpp
blob: 6e408ba3d3e04e664bc2d545ef6307d83114ca6a (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
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
/* 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 "video/video_decoder.h"

#include "audio/audiostream.h"
#include "audio/mixer.h" // for kMaxChannelVolume

#include "common/rational.h"
#include "common/file.h"
#include "common/system.h"

#include "graphics/palette.h"

namespace Video {

VideoDecoder::VideoDecoder() {
	_startTime = 0;
	_dirtyPalette = false;
	_palette = 0;
	_playbackRate = 0;
	_audioVolume = Audio::Mixer::kMaxChannelVolume;
	_audioBalance = 0;
	_soundType = Audio::Mixer::kPlainSoundType;
	_pauseLevel = 0;
	_needsUpdate = false;
	_lastTimeChange = 0;
	_endTime = 0;
	_endTimeSet = false;
	_nextVideoTrack = 0;
	_mainAudioTrack = 0;
	_canSetDither = true;

	// Find the best format for output
	_defaultHighColorFormat = g_system->getScreenFormat();

	if (_defaultHighColorFormat.bytesPerPixel == 1)
		_defaultHighColorFormat = Graphics::PixelFormat(4, 8, 8, 8, 8, 8, 16, 24, 0);
}

void VideoDecoder::close() {
	if (isPlaying())
		stop();

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		delete *it;

	_tracks.clear();
	_internalTracks.clear();
	_externalTracks.clear();
	_dirtyPalette = false;
	_palette = 0;
	_startTime = 0;
	_audioVolume = Audio::Mixer::kMaxChannelVolume;
	_audioBalance = 0;
	_pauseLevel = 0;
	_needsUpdate = false;
	_lastTimeChange = 0;
	_endTime = 0;
	_endTimeSet = false;
	_nextVideoTrack = 0;
	_mainAudioTrack = 0;
	_canSetDither = true;
}

bool VideoDecoder::loadFile(const Common::String &filename) {
	Common::File *file = new Common::File();

	if (!file->open(filename)) {
		delete file;
		return false;
	}

	return loadStream(file);
}

bool VideoDecoder::needsUpdate() const {
	return hasFramesLeft() && getTimeToNextFrame() == 0;
}

void VideoDecoder::pauseVideo(bool pause) {
	if (pause) {
		_pauseLevel++;

	// We can't go negative
	} else if (_pauseLevel) {
		_pauseLevel--;

	// Do nothing
	} else {
		return;
	}

	if (_pauseLevel == 1 && pause) {
		_pauseStartTime = g_system->getMillis(); // Store the starting time from pausing to keep it for later

		for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
			(*it)->pause(true);
	} else if (_pauseLevel == 0) {
		for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
			(*it)->pause(false);

		_startTime += (g_system->getMillis() - _pauseStartTime);
	}
}

void VideoDecoder::resetPauseStartTime() {
	if (isPaused())
		_pauseStartTime = g_system->getMillis();
}

void VideoDecoder::setVolume(byte volume) {
	_audioVolume = volume;

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			((AudioTrack *)*it)->setVolume(_audioVolume);
}

void VideoDecoder::setBalance(int8 balance) {
	_audioBalance = balance;

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			((AudioTrack *)*it)->setBalance(_audioBalance);
}

Audio::Mixer::SoundType VideoDecoder::getSoundType() const {
	return _soundType;
}

void VideoDecoder::setSoundType(Audio::Mixer::SoundType soundType) {
	assert(!isVideoLoaded());
	_soundType = soundType;
}

bool VideoDecoder::isVideoLoaded() const {
	return !_tracks.empty();
}

uint16 VideoDecoder::getWidth() const {
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeVideo)
			return ((VideoTrack *)*it)->getWidth();

	return 0;
}

uint16 VideoDecoder::getHeight() const {
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeVideo)
			return ((VideoTrack *)*it)->getHeight();

	return 0;
}

Graphics::PixelFormat VideoDecoder::getPixelFormat() const {
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeVideo)
			return ((VideoTrack *)*it)->getPixelFormat();

	return Graphics::PixelFormat();
}

const Graphics::Surface *VideoDecoder::decodeNextFrame() {
	_needsUpdate = false;
	_canSetDither = false;

	readNextPacket();

	// If we have no next video track at this point, there shouldn't be
	// any frame available for us to display.
	if (!_nextVideoTrack)
		return 0;

	const Graphics::Surface *frame = _nextVideoTrack->decodeNextFrame();

	if (_nextVideoTrack->hasDirtyPalette()) {
		_palette = _nextVideoTrack->getPalette();
		_dirtyPalette = true;
	}

	// Look for the next video track here for the next decode.
	findNextVideoTrack();

	return frame;
}

bool VideoDecoder::setReverse(bool reverse) {
	// Can only reverse video-only videos
	if (reverse && hasAudio())
		return false;

	// Attempt to make sure all the tracks are in the requested direction
	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		if ((*it)->getTrackType() == Track::kTrackTypeVideo && ((VideoTrack *)*it)->isReversed() != reverse) {
			if (!((VideoTrack *)*it)->setReverse(reverse))
				return false;

			_needsUpdate = true; // force an update
		}
	}

	findNextVideoTrack();
	return true;
}

const byte *VideoDecoder::getPalette() {
	_dirtyPalette = false;
	return _palette;
}

int VideoDecoder::getCurFrame() const {
	int32 frame = -1;

	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeVideo)
			frame += ((VideoTrack *)*it)->getCurFrame() + 1;

	return frame;
}

uint32 VideoDecoder::getFrameCount() const {
	int count = 0;

	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeVideo)
			count += ((VideoTrack *)*it)->getFrameCount();

	return count;
}

uint32 VideoDecoder::getTime() const {
	if (!isPlaying())
		return _lastTimeChange.msecs();

	if (isPaused())
		return MAX<int>((_playbackRate * (_pauseStartTime - _startTime)).toInt(), 0);

	if (useAudioSync()) {
		for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++) {
			if ((*it)->getTrackType() == Track::kTrackTypeAudio && !(*it)->endOfTrack()) {
				uint32 time = ((const AudioTrack *)*it)->getRunningTime();

				if (time != 0)
					return time + _lastTimeChange.msecs();
			}
		}
	}

	return MAX<int>((_playbackRate * (g_system->getMillis() - _startTime)).toInt(), 0);
}

uint32 VideoDecoder::getTimeToNextFrame() const {
	if (endOfVideo() || _needsUpdate || !_nextVideoTrack)
		return 0;

	uint32 currentTime = getTime();
	uint32 nextFrameStartTime = _nextVideoTrack->getNextFrameStartTime();

	if (_nextVideoTrack->isReversed()) {
		// For reversed videos, we need to handle the time difference the opposite way.
		if (nextFrameStartTime >= currentTime)
			return 0;

		return currentTime - nextFrameStartTime;
	}

	// Otherwise, handle it normally.
	if (nextFrameStartTime <= currentTime)
		return 0;

	return nextFrameStartTime - currentTime;
}

bool VideoDecoder::endOfVideo() const {
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		const Track *track = *it;

		bool videoEndTimeReached = _endTimeSet && track->getTrackType() == Track::kTrackTypeVideo && ((const VideoTrack *)track)->getNextFrameStartTime() >= (uint)_endTime.msecs();
		bool endReached = track->endOfTrack() || (isPlaying() && videoEndTimeReached);
		if (!endReached)
			return false;
	}

	return true;
}

bool VideoDecoder::isRewindable() const {
	if (!isVideoLoaded())
		return false;

	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if (!(*it)->isRewindable())
			return false;

	return true;
}

bool VideoDecoder::rewind() {
	if (!isRewindable())
		return false;

	// Stop all tracks so they can be rewound
	if (isPlaying())
		stopAudio();

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if (!(*it)->rewind())
			return false;

	// Now that we've rewound, start all tracks again
	if (isPlaying())
		startAudio();

	_lastTimeChange = 0;
	_startTime = g_system->getMillis();
	resetPauseStartTime();
	findNextVideoTrack();
	return true;
}

bool VideoDecoder::isSeekable() const {
	if (!isVideoLoaded())
		return false;

	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if (!(*it)->isSeekable())
			return false;

	return true;
}

bool VideoDecoder::seek(const Audio::Timestamp &time) {
	if (!isSeekable())
		return false;

	// Stop all tracks so they can be seeked
	if (isPlaying())
		stopAudio();

	// Do the actual seeking
	if (!seekIntern(time))
		return false;

	// Seek any external track too
	for (TrackListIterator it = _externalTracks.begin(); it != _externalTracks.end(); it++)
		if (!(*it)->seek(time))
			return false;

	_lastTimeChange = time;

	// Now that we've seeked, start all tracks again
	// Also reset our start time
	if (isPlaying()) {
		startAudio();
		_startTime = g_system->getMillis() - (time.msecs() / _playbackRate).toInt();
	}

	resetPauseStartTime();
	findNextVideoTrack();
	_needsUpdate = true;
	return true;
}

bool VideoDecoder::seekToFrame(uint frame) {
	if (!isSeekable())
		return false;

	VideoTrack *track = 0;

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		if ((*it)->getTrackType() == Track::kTrackTypeVideo) {
			// We only allow seeking by frame when one video track
			// is present
			if (track)
				return false;

			track = (VideoTrack *)*it;
		}
	}

	// If we didn't find a video track, we can't seek by frame (of course)
	if (!track)
		return false;

	Audio::Timestamp time = track->getFrameTime(frame);

	if (time < 0)
		return false;

	return seek(time);
}

void VideoDecoder::start() {
	if (!isPlaying())
		setRate(1);
}

void VideoDecoder::stop() {
	if (!isPlaying())
		return;

	// Stop audio here so we don't have it affect getTime()
	stopAudio();

	// Keep the time marked down in case we start up again
	// We do this before _playbackRate is set so we don't get
	// _lastTimeChange returned, but before _pauseLevel is
	// reset.
	_lastTimeChange = getTime();

	_playbackRate = 0;
	_startTime = 0;
	_palette = 0;
	_dirtyPalette = false;
	_needsUpdate = false;

	// Also reset the pause state.
	_pauseLevel = 0;

	// Reset the pause state of the tracks too
	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		(*it)->pause(false);
}

void VideoDecoder::setRate(const Common::Rational &rate) {
	if (!isVideoLoaded() || _playbackRate == rate)
		return;

	if (rate == 0) {
		stop();
		return;
	} else if (rate != 1 && hasAudio()) {
		warning("Cannot set custom rate in videos with audio");
		return;
	}

	Common::Rational targetRate = rate;

	// Attempt to set the reverse
	if (!setReverse(rate < 0)) {
		assert(rate < 0); // We shouldn't fail for forward.
		warning("Cannot set custom rate to backwards");
		setReverse(false);
		targetRate = 1;

		if (_playbackRate == targetRate)
			return;
	}

	if (_playbackRate != 0)
		_lastTimeChange = getTime();

	_playbackRate = targetRate;
	_startTime = g_system->getMillis();

	// Adjust start time if we've seeked to something besides zero time
	if (_lastTimeChange != 0)
		_startTime -= (_lastTimeChange.msecs() / _playbackRate).toInt();

	startAudio();
}

bool VideoDecoder::isPlaying() const {
	return _playbackRate != 0;
}

Audio::Timestamp VideoDecoder::getDuration() const {
	Audio::Timestamp maxDuration(0, 1000);

	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		Audio::Timestamp duration = (*it)->getDuration();

		if (duration > maxDuration)
			maxDuration = duration;
	}

	return maxDuration;
}

bool VideoDecoder::seekIntern(const Audio::Timestamp &time) {
	for (TrackList::iterator it = _internalTracks.begin(); it != _internalTracks.end(); it++)
		if (!(*it)->seek(time))
			return false;

	return true;
}

bool VideoDecoder::setDitheringPalette(const byte *palette) {
	// If a frame was already decoded, we can't set it now.
	if (!_canSetDither)
		return false;

	bool result = false;

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		if ((*it)->getTrackType() == Track::kTrackTypeVideo && ((VideoTrack *)*it)->canDither()) {
			((VideoTrack *)*it)->setDither(palette);
			result = true;
		}
	}

	return result;
}

VideoDecoder::Track::Track() {
	_paused = false;
}

bool VideoDecoder::Track::isRewindable() const {
	return isSeekable();
}

bool VideoDecoder::Track::rewind() {
	return seek(Audio::Timestamp(0, 1000));
}

void VideoDecoder::Track::pause(bool shouldPause) {
	_paused = shouldPause;
	pauseIntern(shouldPause);
}

Audio::Timestamp VideoDecoder::Track::getDuration() const {
	return Audio::Timestamp(0, 1000);
}

bool VideoDecoder::VideoTrack::endOfTrack() const {
	return getCurFrame() >= (getFrameCount() - 1);
}

Audio::Timestamp VideoDecoder::VideoTrack::getFrameTime(uint frame) const {
	// Default implementation: Return an invalid (negative) number
	return Audio::Timestamp().addFrames(-1);
}

uint32 VideoDecoder::FixedRateVideoTrack::getNextFrameStartTime() const {
	if (endOfTrack() || getCurFrame() < 0)
		return 0;

	return getFrameTime(getCurFrame() + 1).msecs();
}

Audio::Timestamp VideoDecoder::FixedRateVideoTrack::getFrameTime(uint frame) const {
	// Try to get as accurate as possible, considering we have a fractional frame rate
	// (which Audio::Timestamp doesn't support).
	Common::Rational frameRate = getFrameRate();

	// Try to keep it in terms of the frame rate, if the frame rate is a whole
	// number.
	if (frameRate.getDenominator() == 1)
		return Audio::Timestamp(0, frame, frameRate.toInt());

	// Convert as best as possible
	Common::Rational time = frameRate.getInverse() * frame;
	return Audio::Timestamp(0, time.getNumerator(), time.getDenominator());
}

uint VideoDecoder::FixedRateVideoTrack::getFrameAtTime(const Audio::Timestamp &time) const {
	Common::Rational frameRate = getFrameRate();

	// Easy conversion
	if (frameRate == time.framerate())
		return time.totalNumberOfFrames();

	// Create the rational based on the time first to hopefully cancel out
	// *something* when multiplying by the frameRate (which can be large in
	// some AVI videos).
	return (Common::Rational(time.totalNumberOfFrames(), time.framerate()) * frameRate).toInt();
}

Audio::Timestamp VideoDecoder::FixedRateVideoTrack::getDuration() const {
	return getFrameTime(getFrameCount());
}

VideoDecoder::AudioTrack::AudioTrack(Audio::Mixer::SoundType soundType) :
		_volume(Audio::Mixer::kMaxChannelVolume),
		_soundType(soundType),
		_balance(0),
		_muted(false) {
}

bool VideoDecoder::AudioTrack::endOfTrack() const {
	Audio::AudioStream *stream = getAudioStream();
	return !stream || !g_system->getMixer()->isSoundHandleActive(_handle) || stream->endOfData();
}

void VideoDecoder::AudioTrack::setVolume(byte volume) {
	_volume = volume;

	if (g_system->getMixer()->isSoundHandleActive(_handle))
		g_system->getMixer()->setChannelVolume(_handle, _muted ? 0 : _volume);
}

void VideoDecoder::AudioTrack::setBalance(int8 balance) {
	_balance = balance;

	if (g_system->getMixer()->isSoundHandleActive(_handle))
		g_system->getMixer()->setChannelBalance(_handle, _balance);
}

void VideoDecoder::AudioTrack::start() {
	stop();

	Audio::AudioStream *stream = getAudioStream();
	assert(stream);

	g_system->getMixer()->playStream(_soundType, &_handle, stream, -1, _muted ? 0 : getVolume(), getBalance(), DisposeAfterUse::NO);

	// Pause the audio again if we're still paused
	if (isPaused())
		g_system->getMixer()->pauseHandle(_handle, true);
}

void VideoDecoder::AudioTrack::stop() {
	g_system->getMixer()->stopHandle(_handle);
}

void VideoDecoder::AudioTrack::start(const Audio::Timestamp &limit) {
	stop();

	Audio::AudioStream *stream = getAudioStream();
	assert(stream);

	stream = Audio::makeLimitingAudioStream(stream, limit, DisposeAfterUse::NO);

	g_system->getMixer()->playStream(_soundType, &_handle, stream, -1, _muted ? 0 : getVolume(), getBalance(), DisposeAfterUse::YES);

	// Pause the audio again if we're still paused
	if (isPaused())
		g_system->getMixer()->pauseHandle(_handle, true);
}

uint32 VideoDecoder::AudioTrack::getRunningTime() const {
	if (g_system->getMixer()->isSoundHandleActive(_handle))
		return g_system->getMixer()->getSoundElapsedTime(_handle);

	return 0;
}

void VideoDecoder::AudioTrack::setMute(bool mute) {
	// Update the mute settings, if required
	if (_muted != mute) {
		_muted = mute;

		if (g_system->getMixer()->isSoundHandleActive(_handle))
			g_system->getMixer()->setChannelVolume(_handle, mute ? 0 : _volume);
	}
}

void VideoDecoder::AudioTrack::pauseIntern(bool shouldPause) {
	if (g_system->getMixer()->isSoundHandleActive(_handle))
		g_system->getMixer()->pauseHandle(_handle, shouldPause);
}

Audio::AudioStream *VideoDecoder::RewindableAudioTrack::getAudioStream() const {
	return getRewindableAudioStream();
}

bool VideoDecoder::RewindableAudioTrack::rewind() {
	Audio::RewindableAudioStream *stream = getRewindableAudioStream();
	assert(stream);
	return stream->rewind();
}

Audio::Timestamp VideoDecoder::SeekableAudioTrack::getDuration() const {
	Audio::SeekableAudioStream *stream = getSeekableAudioStream();
	assert(stream);
	return stream->getLength();
}

Audio::AudioStream *VideoDecoder::SeekableAudioTrack::getAudioStream() const {
	return getSeekableAudioStream();
}

bool VideoDecoder::SeekableAudioTrack::seek(const Audio::Timestamp &time) {
	Audio::SeekableAudioStream *stream = getSeekableAudioStream();
	assert(stream);
	return stream->seek(time);
}

VideoDecoder::StreamFileAudioTrack::StreamFileAudioTrack(Audio::Mixer::SoundType soundType) :
		SeekableAudioTrack(soundType) {
	_stream = 0;
}

VideoDecoder::StreamFileAudioTrack::~StreamFileAudioTrack() {
	delete _stream;
}

bool VideoDecoder::StreamFileAudioTrack::loadFromFile(const Common::String &baseName) {
	// TODO: Make sure the stream isn't being played
	delete _stream;
	_stream = Audio::SeekableAudioStream::openStreamFile(baseName);
	return _stream != 0;
}

void VideoDecoder::addTrack(Track *track, bool isExternal) {
	_tracks.push_back(track);

	if (isExternal)
		_externalTracks.push_back(track);
	else
		_internalTracks.push_back(track);

	if (track->getTrackType() == Track::kTrackTypeAudio) {
		// Update volume settings if it's an audio track
		((AudioTrack *)track)->setVolume(_audioVolume);
		((AudioTrack *)track)->setBalance(_audioBalance);

		if (!isExternal && supportsAudioTrackSwitching()) {
			if (_mainAudioTrack) {
				// The main audio track has already been found
				((AudioTrack *)track)->setMute(true);
			} else {
				// First audio track found -> now the main one
				_mainAudioTrack = (AudioTrack *)track;
				_mainAudioTrack->setMute(false);
			}
		}
	} else if (track->getTrackType() == Track::kTrackTypeVideo) {
		// If this track has a better time, update _nextVideoTrack
		if (!_nextVideoTrack || ((VideoTrack *)track)->getNextFrameStartTime() < _nextVideoTrack->getNextFrameStartTime())
			_nextVideoTrack = (VideoTrack *)track;
	}

	// Keep the track paused if we're paused
	if (isPaused())
		track->pause(true);

	// Start the track if we're playing
	if (isPlaying() && track->getTrackType() == Track::kTrackTypeAudio)
		((AudioTrack *)track)->start();
}

bool VideoDecoder::addStreamFileTrack(const Common::String &baseName) {
	// Only allow adding external tracks if a video is already loaded
	if (!isVideoLoaded())
		return false;

	StreamFileAudioTrack *track = new StreamFileAudioTrack(getSoundType());

	bool result = track->loadFromFile(baseName);

	if (result)
		addTrack(track, true);
	else
		delete track;

	return result;
}

bool VideoDecoder::setAudioTrack(int index) {
	if (!supportsAudioTrackSwitching())
		return false;

	AudioTrack *audioTrack = getAudioTrack(index);

	if (!audioTrack)
		return false;

	if (_mainAudioTrack == audioTrack)
		return true;

	_mainAudioTrack->setMute(true);
	audioTrack->setMute(false);
	_mainAudioTrack = audioTrack;
	return true;
}

uint VideoDecoder::getAudioTrackCount() const {
	uint count = 0;

	for (TrackList::const_iterator it = _internalTracks.begin(); it != _internalTracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			count++;

	return count;
}

void VideoDecoder::setEndTime(const Audio::Timestamp &endTime) {
	Audio::Timestamp startTime = 0;

	if (isPlaying()) {
		startTime = getTime();
		stopAudio();
	}

	_endTime = endTime;
	_endTimeSet = true;

	if (startTime > endTime)
		return;

	if (isPlaying()) {
		// We'll assume the audio track is going to start up at the same time it just was
		// and therefore not do any seeking.
		// Might want to set it anyway if we're seekable.
		startAudioLimit(_endTime.msecs() - startTime.msecs());
		_lastTimeChange = startTime;
	}
}

void VideoDecoder::setEndFrame(uint frame) {
	VideoTrack *track = 0;

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		if ((*it)->getTrackType() == Track::kTrackTypeVideo) {
			// We only allow this when one video track is present
			if (track)
				return;

			track = (VideoTrack *)*it;
		}
	}

	// If we didn't find a video track, we can't set the final frame (of course)
	if (!track)
		return;

	Audio::Timestamp time = track->getFrameTime(frame + 1);

	if (time < 0)
		return;

	setEndTime(time);
}

VideoDecoder::Track *VideoDecoder::getTrack(uint track) {
	if (track >= _internalTracks.size())
		return 0;

	return _internalTracks[track];
}

const VideoDecoder::Track *VideoDecoder::getTrack(uint track) const {
	if (track >= _internalTracks.size())
		return 0;

	return _internalTracks[track];
}

bool VideoDecoder::endOfVideoTracks() const {
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeVideo && !(*it)->endOfTrack())
			return false;

	return true;
}

VideoDecoder::VideoTrack *VideoDecoder::findNextVideoTrack() {
	_nextVideoTrack = 0;
	uint32 bestTime = 0xFFFFFFFF;

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		if ((*it)->getTrackType() == Track::kTrackTypeVideo && !(*it)->endOfTrack()) {
			VideoTrack *track = (VideoTrack *)*it;
			uint32 time = track->getNextFrameStartTime();

			if (time < bestTime) {
				bestTime = time;
				_nextVideoTrack = track;
			}
		}
	}

	return _nextVideoTrack;
}

void VideoDecoder::startAudio() {
	if (_endTimeSet) {
		// HACK: Timestamp's subtraction asserts out when subtracting two times
		// with different rates.
		startAudioLimit(_endTime - _lastTimeChange.convertToFramerate(_endTime.framerate()));
		return;
	}

	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			((AudioTrack *)*it)->start();
}

void VideoDecoder::stopAudio() {
	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			((AudioTrack *)*it)->stop();
}

void VideoDecoder::startAudioLimit(const Audio::Timestamp &limit) {
	for (TrackList::iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			((AudioTrack *)*it)->start(limit);
}

bool VideoDecoder::hasFramesLeft() const {
	// This is similar to endOfVideo(), except it doesn't take Audio into account (and returns true if not the end of the video)
	// This is only used for needsUpdate() atm so that setEndTime() works properly
	// And unlike endOfVideoTracks(), this takes into account _endTime
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++) {
		if ((*it)->getTrackType() != Track::kTrackTypeVideo)
			continue;

		const VideoTrack *track = (const VideoTrack *)*it;

		bool videoEndTimeReached = _endTimeSet && track->getNextFrameStartTime() >= (uint)_endTime.msecs();
		bool endReached = track->endOfTrack() || (isPlaying() && videoEndTimeReached);
		if (!endReached)
			return true;
	}

	return false;
}

bool VideoDecoder::hasAudio() const {
	for (TrackList::const_iterator it = _tracks.begin(); it != _tracks.end(); it++)
		if ((*it)->getTrackType() == Track::kTrackTypeAudio)
			return true;

	return false;
}

void VideoDecoder::eraseTrack(Track *track) {
	for (uint idx = 0; idx < _externalTracks.size(); ++idx) {
		if (_externalTracks[idx] == track)
			_externalTracks.remove_at(idx);
	}

	for (uint idx = 0; idx < _internalTracks.size(); ++idx) {
		if (_internalTracks[idx] == track)
			_internalTracks.remove_at(idx);
	}

	for (uint idx = 0; idx < _tracks.size(); ++idx) {
		if (_tracks[idx] == track)
			_tracks.remove_at(idx);
	}
}

} // End of namespace Video