aboutsummaryrefslogtreecommitdiff
path: root/engines/sludge/movie.cpp
blob: 2c43c3cceba705cfa7379905f1fc372f19b34e6b (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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
/* 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 "sludge/movie.h"
#include "sludge/newfatal.h"
#include "sludge/sound.h"
#include "sludge/timing.h"

namespace Sludge {

// sound_openal.cpp
void playMovieStream(int a);
#if 0
int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
		ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes));
#endif

MovieStates movieIsPlaying = nothing;

int movieIsEnding = 0;

float movieAspect = 1.6;
#if 0
typedef struct audioBuffers {
	char *buffer;
	uint size;
	audioBuffers *next;
	Uint32 time_ms;
}audioBuffers;

typedef struct audioQueue {
	audioBuffers *first, *last;
	int size;
	SDL_mutex *mutex;
	SDL_cond *cond;
}audioQueue;

audioQueue audioQ;

Uint32 movieStartTick, movieCurrentTime;

long long audioNsPerByte;
long long audioNsPlayed;
long long audioNsBuffered;
long long audioBufferLen;
bool movieSoundPlaying = false;
int movieAudioIndex;
GLuint yTextureName = 0;
GLuint uTextureName = 0;
GLuint vTextureName = 0;

typedef struct videoBuffers {
	GLubyte *ytex;
	GLubyte *utex;
	GLubyte *vtex;
	videoBuffers *next;
	GLsizei w, h;
	Uint32 time_ms;
}videoBuffers;

typedef struct videoQueue {
	videoBuffers *first, *last;
	int size;
	SDL_mutex *mutex;
	SDL_cond *cond;
}videoQueue;

videoQueue videoQ;

void audio_queue_init(audioQueue *q) {
	memset(q, 0, sizeof(audioQueue));

	q->mutex = SDL_CreateMutex();
	q->cond = SDL_CreateCond();

}
int audio_queue_put(audioQueue *q, char *buffer, uint size, long long time_ms) {

	audioBuffers *audioBuf = new audioBuffers;
	if (!audioBuf)
	return -1;
	audioBuf->buffer = buffer;
	audioBuf->next = NULL;
	audioBuf->size = size;
	audioBuf->time_ms = time_ms;

	SDL_LockMutex(q->mutex);

	if (!q->last)
	q->first = audioBuf;
	else
	q->last->next = audioBuf;
	q->last = audioBuf;
	q->size ++;
	SDL_CondSignal(q->cond);

	SDL_UnlockMutex(q->mutex);

	return 0;
}
inline static int audio_queue_get(audioQueue *q, char **buffer) {
	int ret = 0;

	audioBuffers *audioBuf;

	SDL_LockMutex(q->mutex);

	audioBuf = q->first;
	if (audioBuf) {
		// Synch video timer to audio
		Uint32 tick = SDL_GetTicks() + 100;
		if (ABS((long int)((tick - movieStartTick) - (audioBuf->time_ms))) > 300) {
			movieStartTick = tick - audioBuf->time_ms;
		}

		q->first = audioBuf->next;
		if (!q->first)
		q->last = NULL;
		q->size--;
		*buffer = audioBuf->buffer;
		ret = audioBuf->size;
		delete audioBuf;
	}

	SDL_UnlockMutex(q->mutex);

	return ret;
}

void video_queue_init(videoQueue *q) {
	memset(q, 0, sizeof(videoQueue));
	q->mutex = SDL_CreateMutex();
	q->cond = SDL_CreateCond();
}
int video_queue_put(videoQueue *q, GLubyte *ytex,
		GLubyte *utex,
		GLubyte *vtex,
		GLsizei w, GLsizei h,
		long long time_ms) {

	videoBuffers *videoBuf = new videoBuffers;
	if (!videoBuf)
	return -1;
	videoBuf->ytex = ytex;
	videoBuf->utex = utex;
	videoBuf->vtex = vtex;
	videoBuf->next = NULL;
	videoBuf->w = w;
	videoBuf->h = h;
	videoBuf->time_ms = time_ms;

	SDL_LockMutex(q->mutex);

	if (!q->last)
	q->first = videoBuf;
	else
	q->last->next = videoBuf;
	q->last = videoBuf;
	q->size ++;
	SDL_CondSignal(q->cond);

	SDL_UnlockMutex(q->mutex);
	return 0;
}
inline static int video_queue_get(videoQueue *q,
		GLubyte **ytex,
		GLubyte **utex,
		GLubyte **vtex,
		GLsizei *w, GLsizei *h) {
	videoBuffers *videoBuf;
	int ret = 0;

	SDL_LockMutex(q->mutex);

	videoBuf = q->first;
	if (videoBuf) {
		q->first = videoBuf->next;
		if (!q->first)
		q->last = NULL;
		q->size--;
		*ytex = videoBuf->ytex;
		*utex = videoBuf->utex;
		*vtex = videoBuf->vtex;
		*w = videoBuf->w;
		*h = videoBuf->h;
		ret = 1;
		delete videoBuf;
	}

	SDL_UnlockMutex(q->mutex);

	return ret;
}

#if 0
static void die_codec(vpx_codec_ctx_t *ctx, const char *s) {
	//const char *detail = vpx_codec_error_detail(ctx);
	fatal(s, vpx_codec_error(ctx));
}
#endif

void setMovieViewport() {
	float realAspect = (float) realWinWidth / realWinHeight;

	int vpHeight, vpWidth, vpOffsetX, vpOffsetY;
	if (realAspect > movieAspect) {
		vpHeight = realWinHeight;
		vpWidth = (int)(realWinHeight * movieAspect);
		vpOffsetY = 0;
		vpOffsetX = (realWinWidth - vpWidth) / 2;
	} else {
		vpWidth = realWinWidth;
		vpHeight = (int)((float) realWinWidth / movieAspect);
		vpOffsetY = (realWinHeight - vpHeight) / 2;
		vpOffsetX = 0;
	}
#if 0
	glViewport(vpOffsetX, vpOffsetY, vpWidth, vpHeight);
#endif
	const GLfloat bPMVMatrix[] = {
		2.0f / 640.f, .0, .0, .0,
		.0, -2.0f / 400.f, .0, .0,
		.0, .0, 1.0f, .0,
		-1.0, 1.0f, .0, 1.0f

	};
	for (int i = 0; i < 16; i++) {
		aPMVMatrix[i] = bPMVMatrix[i];
	}
}

static uint64_t xiph_lace_value(byte **np) {
	uint64_t lace;
	uint64_t value;
	byte *p = *np;

	lace = *p++;
	value = lace;
	while (lace == 255) {
		lace = *p++;
		value += lace;
	}

	*np = p;

	return value;
}

vorbis_dsp_state vorbisDspState;
long long audioChannels;

bool fakeAudio = false;

// send audio to audio device...
ALuint feedAudio(void *userdata, ALubyte *data, ALuint length) {
	static char *buffer = NULL;
	static uint bufOffset = 0;
	static uint bufSize = 0;

	ALuint got = 0;
	int bufLen;

	if (! buffer) {
		bufSize = audio_queue_get(&audioQ, &buffer);
		bufOffset = 0;
		if (bufSize <= 0) {
			bufSize = 0;
			buffer = NULL;
			if (! got) {
				got = audioChannels * 2;
				memset(data, 0, got);
				fprintf(stderr, "Faking audio...\n");
				fakeAudio = true;
			}
//				SDL_CondSignal(audioQ.cond);
			return got;
		}
	}

	fakeAudio = false;

	if (length > bufSize - bufOffset)
	bufLen = bufSize - bufOffset;
	else
	bufLen = length;

	memcpy(data, buffer + bufOffset, bufLen);

	bufOffset += bufLen;
	length -= bufLen;
	got += bufLen;

	if (bufSize <= bufOffset) {
		buffer = NULL;
		delete [] buffer;
	}
//	fprintf (stderr, "Sending %d bytes of audio.\n", got);

	return got;
}
#endif

int playMovie(int fileNumber) {
#if 0
	if (specialSettings & SPECIAL_SILENT)
	return 0;

	if (movieIsPlaying) return 0;

	movieSoundPlaying = false;

	vpx_codec_ctx_t codec;

	float pausefade = 1.0;

	using namespace mkvparser;

	MkvReader reader;

	if (reader.Open(fileNumber)) {
		warning(ERROR_MOVIE_ODDNESS);
		return 0;
	}

	long long pos = 0;

	EBMLHeader ebmlHeader;

	ebmlHeader.Parse(&reader, pos);

	mkvparser::Segment *pSegment;

	long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);
	if (ret) {
		fatal("Movie error: Segment::CreateInstance() failed.\n");
	}

	ret = pSegment->Load();
	if (ret < 0) {
		fatal("Movie error: Segment::Load() failed.\n");
	}

	//const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();
	//const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
	//const long long duration_ns = pSegmentInfo->GetDuration();
	//const char* const pTitle = pSegmentInfo->GetTitleAsUTF8();
	//const char* const pMuxingApp = pSegmentInfo->GetMuxingAppAsUTF8();
	//const char* const pWritingApp = pSegmentInfo->GetWritingAppAsUTF8();

	const mkvparser::Tracks *pTracks = pSegment->GetTracks();

	unsigned long i = 0;
	const unsigned long j = pTracks->GetTracksCount();

	enum {VIDEO_TRACK = 1, AUDIO_TRACK = 2};
	int videoTrack = -1;
	int audioTrack = -1;
	long long audioBitDepth;
	double audioSampleRate;
	ogg_packet oggPacket;
	vorbis_info vorbisInfo;
	vorbis_comment vorbisComment;
	vorbis_block vorbisBlock;

	while (i != j) {
		const Track *const pTrack = pTracks->GetTrackByIndex(i++);

		if (pTrack == NULL)
		continue;

		const long long trackType = pTrack->GetType();
		//const unsigned long long trackUid = pTrack->GetUid();
		//const char* pTrackName = pTrack->GetNameAsUTF8();

		if (trackType == VIDEO_TRACK && videoTrack < 0) {
			videoTrack = pTrack->GetNumber();
			const VideoTrack *const pVideoTrack =
			static_cast<const VideoTrack *>(pTrack);

			const long long width = pVideoTrack->GetWidth();
			const long long height = pVideoTrack->GetHeight();

			const double rate = pVideoTrack->GetFrameRate();

			if (rate > 0)
			Init_Special_Timer(rate);

			movieAspect = (float)width / height;
		}

		if (trackType == AUDIO_TRACK && audioTrack < 0) {
			audioTrack = pTrack->GetNumber();
			const AudioTrack *const pAudioTrack =
			static_cast<const AudioTrack *>(pTrack);

			audioChannels = pAudioTrack->GetChannels();
			audioBitDepth = pAudioTrack->GetBitDepth();
			audioSampleRate = pAudioTrack->GetSamplingRate();

			uint audioHeaderSize;
			const byte *audioHeader = pAudioTrack->GetCodecPrivate(audioHeaderSize);

			if (audioHeaderSize < 1) {
				warning("Strange audio track in movie.");
				audioTrack = -1;
				continue;
			}

			byte *p = (byte *)audioHeader;

			uint count = *p++ + 1;
			if (count != 3) {
				warning("Strange audio track in movie.");
				audioTrack = -1;
				continue;
			}

			uint64_t sizes[3], total;

			int i = 0;
			total = 0;
			while (--count) {
				sizes[i] = xiph_lace_value(&p);
				total += sizes[i];
				i += 1;
			}
			sizes[i] = audioHeaderSize - total - (p - audioHeader);

			// initialize vorbis
			vorbis_info_init(&vorbisInfo);
			vorbis_comment_init(&vorbisComment);
			memset(&vorbisDspState, 0, sizeof(vorbisDspState));
			memset(&vorbisBlock, 0, sizeof(vorbisBlock));

			oggPacket.e_o_s = false;
			oggPacket.granulepos = 0;
			oggPacket.packetno = 0;
			int r;
			for (int i = 0; i < 3; i++) {
				oggPacket.packet = p;
				oggPacket.bytes = sizes[i];
				oggPacket.b_o_s = oggPacket.packetno == 0;
				r = vorbis_synthesis_headerin(&vorbisInfo, &vorbisComment, &oggPacket);
				if (r)
				fprintf(stderr, "vorbis_synthesis_headerin failed, error: %d", r);
				oggPacket.packetno++;
				p += sizes[i];
			}

			r = vorbis_synthesis_init(&vorbisDspState, &vorbisInfo);
			if (r)
			fprintf(stderr, "vorbis_synthesis_init failed, error: %d", r);
			r = vorbis_block_init(&vorbisDspState, &vorbisBlock);
			if (r)
			fprintf(stderr, "vorbis_block_init failed, error: %d", r);

			ALenum audioFormat = alureGetSampleFormat(audioChannels, 16, 0);
			movieAudioIndex = initMovieSound(fileNumber, audioFormat, audioChannels, (ALuint) audioSampleRate, feedAudio);

			fprintf(stderr, "Movie sound inited.\n");
			audio_queue_init(&audioQ);
			audioNsPerByte = (1000000000 / audioSampleRate) / (audioChannels * 2);
			audioNsBuffered = 0;
			audioBufferLen = audioChannels * audioSampleRate;
		}
	}

	if (videoTrack < 0)
	fatal("Movie error: No video in movie file.");

	if (audioTrack < 0)
	fatal("Movie error: No sound found.");

	video_queue_init(&videoQ);

	const unsigned long clusterCount = pSegment->GetCount();

	if (clusterCount == 0) {
		fatal("Movie error: Segment has no clusters.\n");
	}

	/* Initialize video codec */
	if (vpx_codec_dec_init(&codec, interface, NULL, 0))
	die_codec(&codec, "Failed to initialize decoder for movie.");

	byte *frame = new byte[256 * 1024];
	if (! checkNew(frame)) return false;

	const mkvparser::Cluster *pCluster = pSegment->GetFirst();

	setMovieViewport();

	movieIsPlaying = playing;
	movieIsEnding = 0;

	glDepthMask(GL_FALSE);
	glDisable(GL_DEPTH_TEST);

	//const long long timeCode = pCluster->GetTimeCode();
	long long time_ns = pCluster->GetTime();

	const BlockEntry *pBlockEntry = pCluster->GetFirst();

	if ((pBlockEntry == NULL) || pBlockEntry->EOS()) {
		pCluster = pSegment->GetNext(pCluster);
		if ((pCluster == NULL) || pCluster->EOS()) {
			fatal("Error: No movie found in the movie file.");
		}
		pBlockEntry = pCluster->GetFirst();
	}
	const Block *pBlock = pBlockEntry->GetBlock();
	long long trackNum = pBlock->GetTrackNumber();
	unsigned long tn = static_cast<unsigned long>(trackNum);
	const Track *pTrack = pTracks->GetTrackByNumber(tn);
	long long trackType = pTrack->GetType();
	int frameCount = pBlock->GetFrameCount();
	time_ns = pBlock->GetTime(pCluster);

	const GLfloat texCoords[] = {
		0.0, 0.0,
		1.0, 0.0,
		0.0, 1.0,
		1.0, 1.0
	};

	const GLfloat vertices[] = {
		0.0, 0.0, 0.1,
		640.0, 0.0, 0.1,
		0.0, 400.0, 0.1,
		640.0, 400.0, 0.1
	};

	const GLfloat vertices1[] = {
		7.0, 7.0, 0.1,
		17.0, 7.0, 0.1,
		7.0, 29.0, 0.1,
		17.0, 29.0, 0.1
	};

	const GLfloat vertices2[] = {
		27.0, 7.0, 0.1,
		37.0, 7.0, 0.1,
		27.0, 29.0, 0.1,
		37.0, 29.0, 0.1
	};

	const GLfloat vertices3[] = {
		5.0, 5.0, 0.1,
		15.0, 5.0, 0.1,
		5.0, 27.0, 0.1,
		15.0, 27.0, 0.1
	};

	const GLfloat vertices4[] = {
		25.0, 5.0, 0.1,
		35.0, 5.0, 0.1,
		25.0, 27.0, 0.1,
		35.0, 27.0, 0.1
	};

	int frameCounter = 0;

	movieStartTick = SDL_GetTicks();

	while (movieIsPlaying) {

		checkInput();
		if (weAreDoneSoQuit)
		break;
		handleInput();

		if (movieIsPlaying && (! movieIsEnding) && (videoQ.size < 100 || audioQ.size < 100)) {
			// Decode a frame!

			if ((pCluster != NULL) && !pCluster->EOS()) {

				if (frameCounter >= frameCount) {

					pBlockEntry = pCluster->GetNext(pBlockEntry);
					if ((pBlockEntry == NULL) || pBlockEntry->EOS()) {
						pCluster = pSegment->GetNext(pCluster);
						if ((pCluster == NULL) || pCluster->EOS()) {
							goto movieHasEnded;
						}
						pBlockEntry = pCluster->GetFirst();
					}
					pBlock = pBlockEntry->GetBlock();
					trackNum = pBlock->GetTrackNumber();
					tn = static_cast<unsigned long>(trackNum);
					pTrack = pTracks->GetTrackByNumber(tn);
					trackType = pTrack->GetType();
					frameCount = pBlock->GetFrameCount();
					time_ns = pBlock->GetTime(pCluster);

					frameCounter = 0;
				}

				const Block::Frame &theFrame = pBlock->GetFrame(frameCounter);
				const long size = theFrame.len;
				//                const long long offset = theFrame.pos;

				if (size > sizeof(frame)) {
					if (frame) delete [] frame;
					frame = new byte[size];
					if (! checkNew(frame)) return 0;
				}
				/*
				 fprintf (stderr, "Block :%s,%s,%15lld\n",
				 (trackType == VIDEO_TRACK) ? "V" : "A",
				 pBlock->IsKey() ? "I" : "P",
				 time_ns);
				 */

				if (trackNum == videoTrack) {

					theFrame.Read(&reader, frame);

					/* Decode the frame */
					if (vpx_codec_decode(&codec, frame, size, NULL, 0))
					die_codec(&codec, "Failed to decode frame");

					// Let's decode an image frame!
					vpx_codec_iter_t iter = NULL;
					vpx_image_t *img;
					/* Get frame data */
					while ((img = vpx_codec_get_frame(&codec, &iter))) {
						if (img->fmt != VPX_IMG_FMT_I420)
						fatal("Movie error. The movie is not in I420 colour format, which is the only one I can hanlde at the moment.");

						uint y;

						GLubyte *ytex = NULL;
						GLubyte *utex = NULL;
						GLubyte *vtex = NULL;

						if (! ytex) {
							ytex = new GLubyte [img->d_w * img->d_h];
							utex = new GLubyte [(img->d_w >> 1) * (img->d_h >> 1)];
							vtex = new GLubyte [(img->d_w >> 1) * (img->d_h >> 1)];
							if (!ytex || !utex || !vtex)
							fatal(ERROR_OUT_OF_MEMORY);

						}

						byte *buf = img->planes[0];
						for (y = 0; y < img->d_h; y++) {
							memcpy(ytex + y * img->d_w, buf, img->d_w);
							buf += img->stride[0];
						}
						buf = img->planes[1];
						for (y = 0; y < img->d_h >> 1; y++) {
							memcpy(utex + y * (img->d_w >> 1), buf, img->d_w >> 1);
							buf += img->stride[1];
						}
						buf = img->planes[2];
						for (y = 0; y < img->d_h >> 1; y++) {
							memcpy(vtex + y * (img->d_w >> 1), buf, img->d_w >> 1);
							buf += img->stride[2];
						}

						video_queue_put(&videoQ, ytex, utex, vtex,
								img->d_w, img->d_h, time_ns / 1000000);

					}

				} else if (trackNum == audioTrack) {
					// Use this Audio Track
					if (size > 0) {
						theFrame.Read(&reader, frame);
						oggPacket.packet = frame;
						oggPacket.bytes = size;
						oggPacket.b_o_s = false;
						oggPacket.packetno++;
						oggPacket.granulepos = -1;
						if (! vorbis_synthesis(&vorbisBlock, &oggPacket)) {
							if (vorbis_synthesis_blockin(&vorbisDspState, &vorbisBlock))
							fprintf(stderr, "Vorbis Synthesis block in error.\n");

						} else {
							fprintf(stderr, "Vorbis Synthesis error.\n");
						}

						float **pcm;

						int numSamples = vorbis_synthesis_pcmout(&vorbisDspState, &pcm);

						if (numSamples > 0) {
							int word = 2;
							int sgned = 1;
							int i, j;
							long bytespersample = audioChannels * word;
							vorbis_fpu_control fpu;

							char *buffer = new char[bytespersample * numSamples];
							if (! checkNew(buffer)) return false;

							/* a tight loop to pack each size */
							{
								int val;
								if (word == 1) {
									int off = (sgned ? 0 : 128);
									vorbis_fpu_setround(&fpu);
									for (j = 0; j < numSamples; j++)
									for (i = 0; i < audioChannels; i++) {
										val = vorbis_ftoi(pcm[i][j] * 128.f);
										if (val > 127)val = 127;
										else if (val < -128)val = -128;
										*buffer++ = val + off;
									}
									vorbis_fpu_restore(fpu);
								} else {
									int off = (sgned ? 0 : 32768);

									if (sgned) {

										vorbis_fpu_setround(&fpu);
										for (i = 0; i < audioChannels; i++) { /* It's faster in this order */
											float *src = pcm[i];
											int16 *dest = ((int16 *)buffer) + i;
											for (j = 0; j < numSamples; j++) {
												val = vorbis_ftoi(src[j] * 32768.f);
												if (val > 32767)val = 32767;
												else if (val < -32768)val = -32768;
												*dest = val;
												dest += audioChannels;
											}
										}
										vorbis_fpu_restore(fpu);

									} else {

										vorbis_fpu_setround(&fpu);
										for (i = 0; i < audioChannels; i++) {
											float *src = pcm[i];
											int16 *dest = ((int16 *)buffer) + i;
											for (j = 0; j < numSamples; j++) {
												val = vorbis_ftoi(src[j] * 32768.f);
												if (val > 32767)val = 32767;
												else if (val < -32768)val = -32768;
												*dest = val + off;
												dest += audioChannels;
											}
										}
										vorbis_fpu_restore(fpu);

									}

								}
							}

							vorbis_synthesis_read(&vorbisDspState, numSamples);
							audioBufferLen = bytespersample * numSamples;
							audio_queue_put(&audioQ, buffer, audioBufferLen, time_ns / 1000000);

							//fprintf (stderr, "Audio buffered: %lld byte %lld ns\n",audioBufferLen, audioNsPerByte*audioBufferLen);

							if (! movieSoundPlaying && size > 1) {
								fprintf(stderr, "** starting sound ** \n");
								playMovieStream(movieAudioIndex);
								movieSoundPlaying = true;
							}
						}
					}
				}
				frameCounter++;

			} else {
				movieHasEnded:
				movieIsEnding = 1;
			}
		}

		bool videoUpdated = false;
		// Get a video frame.
		if (movieIsPlaying == playing) {

			videoBuffers *vB;
			// Do we have decoded video waiting?
			if (vB = videoQ.first) {
				Uint32 tick = SDL_GetTicks() - movieStartTick;

				// Is it time to display the frame yet?
				if ((tick + 1) < vB->time_ms) {
					SDL_Delay(1);
				} else {
					GLubyte *ytex = NULL;
					GLubyte *utex = NULL;
					GLubyte *vtex = NULL;
					GLsizei w, h;

					if (video_queue_get(&videoQ, &ytex, &utex, &vtex, &w, &h)) {

						if (! yTextureName) glGenTextures(1, &yTextureName);
						if (! uTextureName) glGenTextures(1, &uTextureName);
						if (! vTextureName) glGenTextures(1, &vTextureName);
						glBindTexture(GL_TEXTURE_2D, yTextureName);
						glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0,
								GL_ALPHA, GL_UNSIGNED_BYTE, ytex);
						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
						glBindTexture(GL_TEXTURE_2D, uTextureName);
						glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w >> 1, h >> 1, 0,
								GL_ALPHA, GL_UNSIGNED_BYTE, utex);
						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
						glBindTexture(GL_TEXTURE_2D, vTextureName);
						glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w >> 1, h >> 1, 0,
								GL_ALPHA, GL_UNSIGNED_BYTE, vtex);
						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

						glBindTexture(GL_TEXTURE_2D, yTextureName);
						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h,
								GL_ALPHA, GL_UNSIGNED_BYTE, ytex);
						glBindTexture(GL_TEXTURE_2D, uTextureName);
						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w >> 1, h >> 1,
								GL_ALPHA, GL_UNSIGNED_BYTE, utex);
						glBindTexture(GL_TEXTURE_2D, vTextureName);
						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w >> 1, h >> 1,
								GL_ALPHA, GL_UNSIGNED_BYTE, vtex);

						delete [] ytex;
						delete [] utex;
						delete [] vtex;
						ytex = utex = vtex = NULL;
						videoUpdated = true;

					}
				}
			} else if (movieIsEnding) {
				// We have reached the end of the movie.
				movieIsPlaying = nothing;
			}
		}

		// Update the screen if there's new video, or if we're paused
		if (videoUpdated || movieIsPlaying == paused) {
			// Clear The Screen
			glClear(GL_COLOR_BUFFER_BIT);

			// Display the current frame here
			if (shader.yuv) {
				glUseProgram(shader.yuv);
				glActiveTexture(GL_TEXTURE1);
				glBindTexture(GL_TEXTURE_2D, uTextureName);
				glActiveTexture(GL_TEXTURE2);
				glBindTexture(GL_TEXTURE_2D, vTextureName);
				glActiveTexture(GL_TEXTURE0);
			}
			glBindTexture(GL_TEXTURE_2D, yTextureName);
			glEnable(GL_BLEND);
			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

			setPMVMatrix(shader.yuv);
			drawQuad(shader.yuv, vertices, 1, texCoords);

			glUseProgram(0);

			if (movieIsPlaying == paused) {
				pausefade -= 1.0 / 24;
				if (pausefade < -1.0) pausefade = 1.0;

				// Paused.
				glEnable(GL_BLEND);

				glUseProgram(shader.color);

				setPMVMatrix(shader.color);
				setPrimaryColor(0.0f, 0.0f, 0.0f, fabs(pausefade));
				drawQuad(shader.color, vertices1, 0);
				drawQuad(shader.color, vertices2, 0);
				setPrimaryColor(1.0f, 1.0f, 1.0f, fabs(pausefade));
				drawQuad(shader.color, vertices3, 0);
				drawQuad(shader.color, vertices4, 0);

				glUseProgram(0);

				glDisable(GL_BLEND);

				Wait_Frame();
			}

			glFlush();

			EGL_SwapBuffers();

		}
		videoUpdated = false;
	}

	// Cleanup
	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);

	movieIsPlaying = nothing;
	for (int i = 0; i < 10; i++)
		Wait_Frame();
	huntKillFreeSound(fileNumber);

	if (vpx_codec_destroy(&codec))
	die_codec(&codec, "Failed to destroy codec");

	vorbis_dsp_clear(&vorbisDspState);
	vorbis_block_clear(&vorbisBlock);
	vorbis_comment_clear(&vorbisComment);
	vorbis_info_clear(&vorbisInfo);
	delete pSegment;
	deleteTextures(1, &yTextureName);
	deleteTextures(1, &uTextureName);
	deleteTextures(1, &vTextureName);
	yTextureName = uTextureName = vTextureName = 0;

	// Delete any remaining buffers
	videoBuffers *vB = videoQ.first;
	while (vB = videoQ.first) {
		videoQ.first = vB->next;
		delete [] vB->ytex;
		delete [] vB->utex;
		delete [] vB->vtex;
		delete vB;
	}
	videoQ.size = 0;

	audioBuffers *aB = audioQ.first;
	while (aB = audioQ.first) {
		audioQ.first = aB->next;
		delete [] aB->buffer;
		delete aB;
	}
	audioQ.size = 0;

	Init_Timer();

	glViewport(viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);

	setPixelCoords(false);
#endif
	return 1;
}

int stopMovie() {
	int r = movieIsPlaying;
	movieIsPlaying = nothing;
	return r;
}

int pauseMovie() {
#if 0
	if (movieIsPlaying == playing) {
		ALuint source = getSoundSource(movieAudioIndex);
		if (source) {

			alurePauseSource(source);

		}
		movieIsPlaying = paused;
		fprintf(stderr, "** Pausing **\n");
	} else if (movieIsPlaying == paused) {
		ALuint source = getSoundSource(movieAudioIndex);
		if (source) {

			alureResumeSource(source);

		}
		fprintf(stderr, "** Restarted movie ** sound: %d source: %d\n", movieSoundPlaying, source);
		movieIsPlaying = playing;
	}
#endif
	return movieIsPlaying;
}

} // End of namespace Sludge