Debian Codegraph @

addons/video/ogv.c

raw
1 /* Ogg Theora/Vorbis video backend
2 *
3 * TODO:
4 * - seeking
5 * - generate video frame events
6 * - better ycbcr->rgb
7 * - improve frame skipping
8 * - Ogg Skeleton support
9 * - pass Theora test suite
10 *
11 * NOTE: we treat Ogg timestamps as the beginning of frames. In reality they
12 * are end timestamps. Normally this should not be noticeable, but can make a
13 * difference.
14 */
15
16 #include <stdio.h>
17 #include "allegro5/allegro5.h"
18 #include "allegro5/allegro_audio.h"
19 #include "allegro5/allegro_video.h"
20 #include "allegro5/internal/aintern_dtor.h"
21 #include "allegro5/internal/aintern_vector.h"
22 #include "allegro5/internal/aintern_video.h"
23
24 #include <ogg/ogg.h>
25 #include <theora/theora.h>
26 #include <theora/theoradec.h>
27 #include <vorbis/codec.h>
28
29 ALLEGRO_DEBUG_CHANNEL("video")
30
31
32 /* XXX probably should be based on stream parameters */
33 static const int NUM_FRAGS = 2;
34 static const int FRAG_SAMPLES = 4096;
35 static const int RGB_PIXEL_FORMAT = ALLEGRO_PIXEL_FORMAT_ABGR_8888;
36
37
38 typedef struct OGG_VIDEO OGG_VIDEO;
39 typedef struct STREAM STREAM;
40 typedef struct THEORA_STREAM THEORA_STREAM;
41 typedef struct VORBIS_STREAM VORBIS_STREAM;
42 typedef struct PACKET_NODE PACKET_NODE;
43
44 enum {
45 STREAM_TYPE_UNKNOWN = 0,
46 STREAM_TYPE_THEORA,
47 STREAM_TYPE_VORBIS
48 };
49
50 struct PACKET_NODE {
51 PACKET_NODE *next;
52 ogg_packet pkt;
53 };
54
55 struct THEORA_STREAM {
56 th_info info;
57 th_comment comment;
58 th_setup_info *setup;
59 th_dec_ctx *ctx;
60 ogg_int64_t prev_framenum;
61 double frame_duration;
62 };
63
64 struct VORBIS_STREAM {
65 vorbis_info info;
66 vorbis_comment comment;
67 bool inited_for_data;
68 vorbis_dsp_state dsp;
69 vorbis_block block;
70 int channels;
71 float *next_fragment; /* channels * FRAG_SAMPLES elements */
72 int next_fragment_pos;
73 };
74
75 struct STREAM {
76 int stream_type;
77 bool active;
78 bool headers_done;
79 ogg_stream_state state;
80 PACKET_NODE *packet_queue;
81 union {
82 THEORA_STREAM theora;
83 VORBIS_STREAM vorbis;
84 } u;
85 };
86
87 struct OGG_VIDEO {
88 ALLEGRO_FILE *fp;
89 bool reached_eof;
90 ogg_sync_state sync_state;
91 _AL_VECTOR streams; /* vector of STREAM pointers */
92 STREAM *selected_video_stream; /* one of the streams */
93 STREAM *selected_audio_stream; /* one of the streams */
94 int seek_counter;
95
96 /* Video output. */
97 th_pixel_fmt pixel_fmt;
98 th_ycbcr_buffer buffer;
99 bool buffer_dirty;
100 unsigned char* rgb_data;
101 ALLEGRO_BITMAP *frame_bmp;
102 ALLEGRO_BITMAP *pic_bmp; /* frame_bmp, or subbitmap thereof */
103
104 ALLEGRO_EVENT_SOURCE evtsrc;
105 ALLEGRO_EVENT_QUEUE *queue;
106 ALLEGRO_MUTEX *mutex;
107 ALLEGRO_COND *cond;
108 ALLEGRO_THREAD *thread;
109 };
110
111
112 /* forward declarations */
113 static bool ogv_close_video(ALLEGRO_VIDEO *video);
114
115
116 /* Packet queue. */
117
118 static PACKET_NODE *create_packet_node(ogg_packet *packet)
119 {
120 PACKET_NODE *node = al_malloc(sizeof(PACKET_NODE));
121
122 node->next = NULL;
123 node->pkt = *packet;
124 node->pkt.packet = al_malloc(packet->bytes);
125 memcpy(node->pkt.packet, packet->packet, packet->bytes);
126
127 return node;
128 }
129
130 static void free_packet_node(PACKET_NODE *node)
131 {
132 ASSERT(node->next == NULL);
133
134 al_free(node->pkt.packet);
135 al_free(node);
136 }
137
138 static void add_tail_packet(STREAM *stream, PACKET_NODE *node)
139 {
140 PACKET_NODE *cur;
141
142 ASSERT(node->next == NULL);
143
144 for (cur = stream->packet_queue; cur != NULL; cur = cur->next) {
145 if (cur->next == NULL) {
146 cur->next = node;
147 ASSERT(cur->pkt.packetno < node->pkt.packetno);
148 return;
149 }
150 }
151
152 ASSERT(stream->packet_queue == NULL);
153 stream->packet_queue = node;
154 }
155
156 static void add_head_packet(STREAM *stream, PACKET_NODE *node)
157 {
158 ASSERT(node->next == NULL);
159
160 node->next = stream->packet_queue;
161 stream->packet_queue = node;
162
163 if (node->next) {
164 ASSERT(node->pkt.packetno < node->next->pkt.packetno);
165 }
166 }
167
168 static PACKET_NODE *take_head_packet(STREAM *stream)
169 {
170 PACKET_NODE *cur;
171
172 cur = stream->packet_queue;
173 if (!cur) {
174 return NULL;
175 }
176 if (cur->next) {
177 ASSERT(cur->pkt.packetno < cur->next->pkt.packetno);
178 }
179 stream->packet_queue = cur->next;
180 cur->next = NULL;
181 return cur;
182 }
183
184 static void free_packet_queue(STREAM *stream)
185 {
186 while (stream->packet_queue) {
187 PACKET_NODE *node = stream->packet_queue;
188 stream->packet_queue = node->next;
189 node->next = NULL;
190 free_packet_node(node);
191 }
192 }
193
194 static void deactivate_stream(STREAM *stream)
195 {
196 stream->active = false;
197 free_packet_queue(stream);
198 }
199
200
201 /* Logical streams. */
202
203 static STREAM *create_stream(OGG_VIDEO *ogv, int serial)
204 {
205 STREAM *stream;
206 STREAM **slot;
207
208 stream = al_calloc(1, sizeof(STREAM));
209 stream->stream_type = STREAM_TYPE_UNKNOWN;
210 stream->active = true;
211 stream->headers_done = false;
212 ogg_stream_init(&stream->state, serial);
213 stream->packet_queue = NULL;
214
215 slot = _al_vector_alloc_back(&ogv->streams);
216 (*slot) = stream;
217
218 return stream;
219 }
220
221 static STREAM *find_stream(OGG_VIDEO *ogv, int serial)
222 {
223 unsigned i;
224
225 for (i = 0; i < _al_vector_size(&ogv->streams); i++) {
226 STREAM **slot = _al_vector_ref(&ogv->streams, i);
227 STREAM *stream = *slot;
228
229 if (stream->state.serialno == serial) {
230 return stream;
231 }
232 }
233
234 return NULL;
235 }
236
237 static void free_stream(STREAM *stream)
238 {
239 ASSERT(stream);
240
241 ogg_stream_clear(&stream->state);
242
243 free_packet_queue(stream);
244
245 switch (stream->stream_type) {
246 case STREAM_TYPE_UNKNOWN:
247 break;
248
249 case STREAM_TYPE_THEORA:
250 {
251 THEORA_STREAM *tstream = &stream->u.theora;
252
253 ALLEGRO_DEBUG("Clean up Theora.\n");
254 th_info_clear(&tstream->info);
255 th_comment_clear(&tstream->comment);
256 if (tstream->setup) {
257 th_setup_free(tstream->setup);
258 }
259 if (tstream->ctx) {
260 th_decode_free(tstream->ctx);
261 }
262 }
263 break;
264
265 case STREAM_TYPE_VORBIS:
266 {
267 VORBIS_STREAM *vstream = &stream->u.vorbis;
268
269 ALLEGRO_DEBUG("Clean up Vorbis.\n");
270 vorbis_info_clear(&vstream->info);
271 vorbis_comment_clear(&vstream->comment);
272 if (vstream->inited_for_data) {
273 vorbis_block_clear(&vstream->block);
274 vorbis_dsp_clear(&vstream->dsp);
275 }
276 al_free(vstream->next_fragment);
277 }
278 break;
279 }
280
281 al_free(stream);
282 }
283
284 /* Returns true if got a page. */
285 static bool read_page(OGG_VIDEO *ogv, ogg_page *page)
286 {
287 const int buffer_size = 4096;
288
289 if (al_feof(ogv->fp) || al_ferror(ogv->fp)) {
290 ogv->reached_eof = true;
291 return ogg_sync_pageout(&ogv->sync_state, page) == 1;
292 }
293
294 while (ogg_sync_pageout(&ogv->sync_state, page) != 1) {
295 char *buffer;
296 size_t bytes;
297 int rc;
298
299 buffer = ogg_sync_buffer(&ogv->sync_state, buffer_size);
300 bytes = al_fread(ogv->fp, buffer, buffer_size);
301 if (bytes == 0) {
302 ALLEGRO_DEBUG("End of file.\n");
303 return false;
304 }
305
306 rc = ogg_sync_wrote(&ogv->sync_state, bytes);
307 ASSERT(rc == 0);
308 }
309
310 return true;
311 }
312
313 /* Return true if got a packet for the stream. */
314 static bool read_packet(OGG_VIDEO *ogv, STREAM *stream, ogg_packet *packet)
315 {
316 ogg_page page;
317 int rc;
318
319 for (;;) {
320 rc = ogg_stream_packetout(&stream->state, packet);
321 if (rc == 1) {
322 /* Got a packet for stream. */
323 return true;
324 }
325
326 if (read_page(ogv, &page)) {
327 STREAM *page_stream = find_stream(ogv, ogg_page_serialno(&page));
328
329 if (page_stream && page_stream->active) {
330 rc = ogg_stream_pagein(&page_stream->state, &page);
331 ASSERT(rc == 0);
332 }
333 }
334 else {
335 return false;
336 }
337 }
338 }
339
340
341 /* Header decoding. */
342
343 static bool try_decode_theora_header(STREAM *stream, ogg_packet *packet)
344 {
345 int rc;
346
347 switch (stream->stream_type) {
348 case STREAM_TYPE_UNKNOWN:
349 th_info_init(&stream->u.theora.info);
350 th_comment_init(&stream->u.theora.comment);
351 break;
352 case STREAM_TYPE_THEORA:
353 break;
354 case STREAM_TYPE_VORBIS:
355 return false;
356 }
357
358 if (stream->headers_done) {
359 add_tail_packet(stream, create_packet_node(packet));
360 return true;
361 }
362
363 rc = th_decode_headerin(&stream->u.theora.info, &stream->u.theora.comment,
364 &stream->u.theora.setup, packet);
365
366 if (rc > 0) {
367 /* Successfully parsed a Theora header. */
368 if (stream->stream_type == STREAM_TYPE_UNKNOWN) {
369 ALLEGRO_DEBUG("Found Theora stream.\n");
370 stream->stream_type = STREAM_TYPE_THEORA;
371 }
372 return true;
373 }
374
375 if (rc == 0) {
376 /* First Theora data packet. */
377 add_tail_packet(stream, create_packet_node(packet));
378 stream->headers_done = true;
379 return true;
380 }
381
382 th_info_clear(&stream->u.theora.info);
383 th_comment_clear(&stream->u.theora.comment);
384 return false;
385 }
386
387 static int try_decode_vorbis_header(STREAM *stream, ogg_packet *packet)
388 {
389 int rc;
390
391 switch (stream->stream_type) {
392 case STREAM_TYPE_UNKNOWN:
393 vorbis_info_init(&stream->u.vorbis.info);
394 vorbis_comment_init(&stream->u.vorbis.comment);
395 break;
396 case STREAM_TYPE_VORBIS:
397 break;
398 case STREAM_TYPE_THEORA:
399 return false;
400 }
401
402 rc = vorbis_synthesis_headerin(&stream->u.vorbis.info,
403 &stream->u.vorbis.comment, packet);
404
405 if (rc == 0) {
406 /* Successfully parsed a Vorbis header. */
407 if (stream->stream_type == STREAM_TYPE_UNKNOWN) {
408 ALLEGRO_INFO("Found Vorbis stream.\n");
409 stream->stream_type = STREAM_TYPE_VORBIS;
410 stream->u.vorbis.inited_for_data = false;
411 }
412 return true;
413 }
414
415 if (stream->stream_type == STREAM_TYPE_VORBIS && rc == OV_ENOTVORBIS) {
416 /* First data packet. */
417 add_tail_packet(stream, create_packet_node(packet));
418 stream->headers_done = true;
419 return true;
420 }
421
422 vorbis_info_clear(&stream->u.vorbis.info);
423 vorbis_comment_clear(&stream->u.vorbis.comment);
424 return false;
425 }
426
427 static bool all_headers_done(OGG_VIDEO *ogv)
428 {
429 bool have_something = false;
430 unsigned i;
431
432 for (i = 0; i < _al_vector_size(&ogv->streams); i++) {
433 STREAM **slot = _al_vector_ref(&ogv->streams, i);
434 STREAM *stream = *slot;
435
436 switch (stream->stream_type) {
437 case STREAM_TYPE_THEORA:
438 case STREAM_TYPE_VORBIS:
439 have_something = true;
440 if (!stream->headers_done)
441 return false;
442 break;
443 case STREAM_TYPE_UNKNOWN:
444 break;
445 }
446 }
447
448 return have_something;
449 }
450
451 static void read_headers(OGG_VIDEO *ogv)
452 {
453 ogg_page page;
454 ogg_packet packet;
455 STREAM *stream;
456 int serial;
457 int rc;
458
459 ALLEGRO_DEBUG("Begin reading headers.\n");
460
461 do {
462 /* Read a page of data. */
463 if (!read_page(ogv, &page)) {
464 break;
465 }
466
467 /* Which stream is this page for? */
468 serial = ogg_page_serialno(&page);
469
470 /* Start a new stream or find an existing one. */
471 if (ogg_page_bos(&page)) {
472 stream = create_stream(ogv, serial);
473 }
474 else {
475 stream = find_stream(ogv, serial);
476 }
477
478 if (!stream) {
479 ALLEGRO_WARN("No stream for serial: %x\n", serial);
480 continue;
481 }
482
483 if (!stream->active) {
484 continue;
485 }
486
487 /* Add the page to the stream. */
488 rc = ogg_stream_pagein(&stream->state, &page);
489 ASSERT(rc == 0);
490
491 /* Look for a complete packet. */
492 rc = ogg_stream_packetpeek(&stream->state, &packet);
493 if (rc == 0) {
494 continue;
495 }
496 if (rc == -1) {
497 ALLEGRO_WARN("No packet due to lost sync or hole in data.\n");
498 continue;
499 }
500
501 /* Try to decode the packet as a Theora or Vorbis header. */
502 if (!try_decode_theora_header(stream, &packet)) {
503 if (!try_decode_vorbis_header(stream, &packet)) {
504 ALLEGRO_DEBUG("Unknown packet type ignored.\n");
505 }
506 }
507
508 /* Consume the packet. */
509 rc = ogg_stream_packetout(&stream->state, &packet);
510 ASSERT(rc == 1);
511
512 } while (!all_headers_done(ogv));
513
514 ALLEGRO_DEBUG("End reading headers.\n");
515 }
516
517
518 /* Vorbis streams. */
519
520 static void setup_vorbis_stream_decode(ALLEGRO_VIDEO *video, STREAM *stream)
521 {
522 VORBIS_STREAM * const vstream = &stream->u.vorbis;
523 int rc;
524
525 rc = vorbis_synthesis_init(&vstream->dsp, &vstream->info);
526 ASSERT(rc == 0);
527
528 rc = vorbis_block_init(&vstream->dsp, &vstream->block);
529 ASSERT(rc == 0);
530
531 vstream->inited_for_data = true;
532
533 video->audio_rate = vstream->info.rate;
534 vstream->channels = vstream->info.channels;
535
536 vstream->next_fragment =
537 al_calloc(vstream->channels * FRAG_SAMPLES, sizeof(float));
538
539 ALLEGRO_INFO("Audio rate: %f\n", video->audio_rate);
540 ALLEGRO_INFO("Audio channels: %d\n", vstream->channels);
541 }
542
543 static void handle_vorbis_data(VORBIS_STREAM *vstream, ogg_packet *packet)
544 {
545 int rc;
546
547 rc = vorbis_synthesis(&vstream->block, packet);
548 if (rc != 0) {
549 ALLEGRO_ERROR("vorbis_synthesis returned %d\n", rc);
550 return;
551 }
552
553 rc = vorbis_synthesis_blockin(&vstream->dsp, &vstream->block);
554 if (rc != 0) {
555 ALLEGRO_ERROR("vorbis_synthesis_blockin returned %d\n", rc);
556 return;
557 }
558 }
559
560 static bool generate_next_audio_fragment(VORBIS_STREAM *vstream)
561 {
562 float **pcm = NULL;
563 float *p;
564 int samples;
565 int i, ch;
566 int rc;
567
568 samples = vorbis_synthesis_pcmout(&vstream->dsp, &pcm);
569 if (samples == 0) {
570 return false;
571 }
572
573 if (samples > FRAG_SAMPLES - vstream->next_fragment_pos) {
574 samples = FRAG_SAMPLES - vstream->next_fragment_pos;
575 }
576
577 ASSERT(vstream->next_fragment);
578 p = &vstream->next_fragment[
579 vstream->channels * vstream->next_fragment_pos];
580
581 if (vstream->channels == 2) {
582 for (i = 0; i < samples; i++) {
583 *p++ = pcm[0][i];
584 *p++ = pcm[1][i];
585 }
586 }
587 else if (vstream->channels == 1) {
588 for (i = 0; i < samples; i++) {
589 *p++ = pcm[0][i];
590 }
591 }
592 else {
593 for (i = 0; i < samples; i++) {
594 for (ch = 0; ch < vstream->channels; ch++) {
595 *p++ = pcm[ch][i];
596 }
597 }
598 }
599
600 vstream->next_fragment_pos += samples;
601
602 rc = vorbis_synthesis_read(&vstream->dsp, samples);
603 ASSERT(rc == 0);
604 return true;
605 }
606
607 static void poll_vorbis_decode(OGG_VIDEO *ogv, STREAM *vstream_outer)
608 {
609 VORBIS_STREAM * const vstream = &vstream_outer->u.vorbis;
610
611 while (vstream->next_fragment_pos < FRAG_SAMPLES
612 && generate_next_audio_fragment(vstream))
613 {
614 }
615
616 while (vstream->next_fragment_pos < FRAG_SAMPLES) {
617 PACKET_NODE *node;
618 ogg_packet packet;
619
620 node = take_head_packet(vstream_outer);
621 if (node) {
622 handle_vorbis_data(vstream, &node->pkt);
623 generate_next_audio_fragment(vstream);
624 free_packet_node(node);
625 }
626 else if (read_packet(ogv, vstream_outer, &packet)) {
627 handle_vorbis_data(vstream, &packet);
628 generate_next_audio_fragment(vstream);
629 }
630 else {
631 break;
632 }
633 }
634 }
635
636 static ALLEGRO_AUDIO_STREAM *create_audio_stream(const ALLEGRO_VIDEO *video,
637 const STREAM *vstream_outer)
638 {
639 const VORBIS_STREAM *vstream = &vstream_outer->u.vorbis;
640 ALLEGRO_AUDIO_STREAM *audio;
641 int chanconf;
642 int rc;
643
644 switch (vstream->channels) {
645 case 1: chanconf = ALLEGRO_CHANNEL_CONF_1; break;
646 case 2: chanconf = ALLEGRO_CHANNEL_CONF_2; break;
647 case 3: chanconf = ALLEGRO_CHANNEL_CONF_3; break;
648 case 4: chanconf = ALLEGRO_CHANNEL_CONF_4; break;
649 case 6: chanconf = ALLEGRO_CHANNEL_CONF_5_1; break;
650 case 7: chanconf = ALLEGRO_CHANNEL_CONF_6_1; break;
651 case 8: chanconf = ALLEGRO_CHANNEL_CONF_7_1; break;
652 default:
653 ALLEGRO_WARN("Unsupported number of channels: %d\n",
654 vstream->channels);
655 return NULL;
656 }
657
658 audio = al_create_audio_stream(NUM_FRAGS, FRAG_SAMPLES,
659 vstream->info.rate, ALLEGRO_AUDIO_DEPTH_FLOAT32, chanconf);
660 if (!audio) {
661 ALLEGRO_ERROR("Could not create audio stream.\n");
662 return NULL;
663 }
664
665 if (video->mixer) {
666 rc = al_attach_audio_stream_to_mixer(audio, video->mixer);
667 }
668 else if (video->voice) {
669 rc = al_attach_audio_stream_to_voice(audio, video->voice);
670 }
671 else {
672 rc = al_attach_audio_stream_to_mixer(audio, al_get_default_mixer());
673 }
674
675 if (rc) {
676 ALLEGRO_DEBUG("Audio stream ready.\n");
677 }
678 else {
679 ALLEGRO_ERROR("Could not attach audio stream.\n");
680 al_destroy_audio_stream(audio);
681 audio = NULL;
682 }
683
684 return audio;
685 }
686
687 static void update_audio_fragment(ALLEGRO_AUDIO_STREAM *audio_stream,
688 VORBIS_STREAM *vstream, bool paused, bool reached_eof)
689 {
690 float *frag;
691
692 frag = al_get_audio_stream_fragment(audio_stream);
693 if (!frag)
694 return;
695
696 if (paused || vstream->next_fragment_pos < FRAG_SAMPLES) {
697 if (!paused && !reached_eof) {
698 ALLEGRO_WARN("Next fragment not ready.\n");
699 }
700 memset(frag, 0, vstream->channels * FRAG_SAMPLES * sizeof(float));
701 }
702 else {
703 memcpy(frag, vstream->next_fragment,
704 vstream->channels * FRAG_SAMPLES * sizeof(float));
705 vstream->next_fragment_pos = 0;
706 }
707
708 al_set_audio_stream_fragment(audio_stream, frag);
709 }
710
711
712 /* Theora streams. */
713
714 static void setup_theora_stream_decode(ALLEGRO_VIDEO *video, OGG_VIDEO *ogv,
715 STREAM *tstream_outer)
716 {
717 THEORA_STREAM * const tstream = &tstream_outer->u.theora;
718 int frame_w = tstream->info.frame_width;
719 int frame_h = tstream->info.frame_height;
720 int pic_x = tstream->info.pic_x;
721 int pic_y = tstream->info.pic_y;
722 int pic_w = tstream->info.pic_width;
723 int pic_h = tstream->info.pic_height;
724 float aspect_ratio = 1.0;
725
726 tstream->ctx = th_decode_alloc(&tstream->info, tstream->setup);
727 ASSERT(tstream->ctx);
728 th_setup_free(tstream->setup);
729 tstream->setup = NULL;
730
731 ogv->pixel_fmt = tstream->info.pixel_fmt;
732 ogv->frame_bmp = al_create_bitmap(frame_w, frame_h);
733 if (pic_x == 0 && pic_y == 0 && pic_w == frame_w && pic_h == frame_h) {
734 ogv->pic_bmp = ogv->frame_bmp;
735 }
736 else {
737 ogv->pic_bmp = al_create_sub_bitmap(ogv->frame_bmp,
738 pic_x, pic_y, pic_w, pic_h);
739 }
740 ogv->rgb_data =
741 al_malloc(al_get_pixel_size(RGB_PIXEL_FORMAT) * frame_w * frame_h);
742
743 video->fps =
744 (double)tstream->info.fps_numerator /
745 (double)tstream->info.fps_denominator;
746 tstream->frame_duration =
747 (double)tstream->info.fps_denominator /
748 (double)tstream->info.fps_numerator;
749
750 if (tstream->info.aspect_denominator != 0) {
751 aspect_ratio =
752 (double)(pic_w * tstream->info.aspect_numerator) /
753 (double)(pic_h * tstream->info.aspect_denominator);
754 }
755
756 _al_compute_scaled_dimensions(pic_w, pic_h, aspect_ratio, &video->scaled_width,
757 &video->scaled_height);
758
759 tstream->prev_framenum = -1;
760
761 ALLEGRO_INFO("Frame size: %dx%d\n", frame_w, frame_h);
762 ALLEGRO_INFO("Picture size: %dx%d\n", pic_w, pic_h);
763 ALLEGRO_INFO("Scaled size: %fx%f\n", video->scaled_width, video->scaled_height);
764 ALLEGRO_INFO("FPS: %f\n", video->fps);
765 ALLEGRO_INFO("Frame_duration: %f\n", tstream->frame_duration);
766 }
767
768 static int64_t get_theora_framenum(THEORA_STREAM *tstream, ogg_packet *packet)
769 {
770 if (packet->granulepos > 0) {
771 return th_granule_frame(&tstream->info, packet->granulepos);
772 }
773
774 return tstream->prev_framenum + 1;
775 }
776
777 static bool handle_theora_data(ALLEGRO_VIDEO *video, THEORA_STREAM *tstream,
778 ogg_packet *packet, bool *ret_new_frame)
779 {
780 int64_t expected_framenum;
781 int64_t framenum;
782 int rc;
783
784 expected_framenum = tstream->prev_framenum + 1;
785 framenum = get_theora_framenum(tstream, packet);
786
787 if (framenum > expected_framenum) {
788 /* Packet is for a later frame, don't decode it yet. */
789 ALLEGRO_DEBUG("Expected frame %ld, got %ld\n",
790 (long)expected_framenum, (long)framenum);
791 video->video_position += tstream->frame_duration;
792 tstream->prev_framenum++;
793 return false;
794 }
795
796 if (framenum < expected_framenum) {
797 ALLEGRO_DEBUG("Expected frame %ld, got %ld (decoding anyway)\n",
798 (long)expected_framenum, (long)framenum);
799 }
800
801 rc = th_decode_packetin(tstream->ctx, packet, NULL);
802 if (rc != TH_EBADPACKET) {
803 /* HACK: When we seek to beginning, the first few packets are actually
804 * headers. To properly fix this, those packets should be ignored when we
805 * do the seeking (see the XXX there). */
806 ASSERT(rc == 0 || rc == TH_DUPFRAME);
807 }
808
809 if (rc == 0) {
810 *ret_new_frame = true;
811
812 video->video_position = framenum * tstream->frame_duration;
813 tstream->prev_framenum = framenum;
814 }
815
816 return true;
817 }
818
819 /* Y'CrCb to RGB conversion. */
820 /* XXX simple slow implementation */
821
822 static unsigned char clamp(int x)
823 {
824 if (x < 0)
825 return 0;
826 if (x > 255)
827 return 255;
828 return x;
829 }
830
831 static INLINE void ycbcr_to_rgb(th_ycbcr_buffer buffer,
832 unsigned char* rgb_data, int pixel_size, int pitch, int xshift, int yshift)
833 {
834 const int w = buffer[0].width;
835 const int h = buffer[0].height;
836 int x, y;
837
838 for (y = 0; y < h; y++) {
839 const int y2 = y >> yshift;
840 for (x = 0; x < w; x++) {
841 const int x2 = x >> xshift;
842 unsigned char * const data = rgb_data + y * pitch + x * pixel_size;
843 const int yp = buffer[0].data[y * buffer[0].stride + x ];
844 const int cb = buffer[1].data[y2 * buffer[1].stride + x2];
845 const int cr = buffer[2].data[y2 * buffer[2].stride + x2];
846 const int C = yp - 16;
847 const int D = cb - 128;
848 const int E = cr - 128;
849
850 data[0] = clamp((298*C + 409*E + 128) >> 8);
851 data[1] = clamp((298*C - 100*D - 208*E + 128) >> 8);
852 data[2] = clamp((298*C + 516*D + 128) >> 8);
853 data[3] = 0xff;
854 }
855 }
856 }
857
858 static void convert_buffer_to_rgba(OGG_VIDEO *ogv)
859 {
860 const int pixel_size = al_get_pixel_size(RGB_PIXEL_FORMAT);
861 const int pitch = pixel_size * al_get_bitmap_width(ogv->frame_bmp);
862
863 switch (ogv->pixel_fmt) {
864 case TH_PF_420:
865 ycbcr_to_rgb(ogv->buffer, ogv->rgb_data, pixel_size, pitch, 1, 1);
866 break;
867 case TH_PF_422:
868 ycbcr_to_rgb(ogv->buffer, ogv->rgb_data, pixel_size, pitch, 1, 0);
869 break;
870 case TH_PF_444:
871 ycbcr_to_rgb(ogv->buffer, ogv->rgb_data, pixel_size, pitch, 0, 0);
872 break;
873 default:
874 ALLEGRO_ERROR("Unsupported pixel format.\n");
875 break;
876 }
877 }
878
879 static int poll_theora_decode(ALLEGRO_VIDEO *video, STREAM *tstream_outer)
880 {
881 OGG_VIDEO * const ogv = video->data;
882 THEORA_STREAM * const tstream = &tstream_outer->u.theora;
883 bool new_frame = false;
884 int num_frames = 0;
885 int rc;
886
887 while (video->video_position < video->position) {
888 PACKET_NODE *node;
889 ogg_packet packet;
890
891 node = take_head_packet(tstream_outer);
892 if (node) {
893 if (handle_theora_data(video, tstream, &node->pkt, &new_frame)) {
894 free_packet_node(node);
895 num_frames++;
896 }
897 else {
898 add_head_packet(tstream_outer, node);
899 }
900 }
901 else if (read_packet(ogv, tstream_outer, &packet)) {
902 if (handle_theora_data(video, tstream, &packet, &new_frame)) {
903 num_frames++;
904 }
905 else {
906 add_head_packet(tstream_outer, create_packet_node(&packet));
907 }
908 }
909 else {
910 break;
911 }
912
913 /* Only skip frames if we are really falling behind, not just slightly
914 * ahead of the target position.
915 * XXX improve frame skipping algorithm
916 */
917 if (video->video_position
918 >= video->position - 3.0*tstream->frame_duration) {
919 break;
920 }
921 }
922
923 if (new_frame) {
924 ALLEGRO_EVENT event;
925 al_lock_mutex(ogv->mutex);
926
927 rc = th_decode_ycbcr_out(tstream->ctx, ogv->buffer);
928 ASSERT(rc == 0);
929
930 convert_buffer_to_rgba(ogv);
931
932 ogv->buffer_dirty = true;
933
934 event.type = ALLEGRO_EVENT_VIDEO_FRAME_SHOW;
935 event.user.data1 = (intptr_t)video;
936 al_emit_user_event(&video->es, &event, NULL);
937
938 al_unlock_mutex(ogv->mutex);
939 }
940
941 return num_frames;
942 }
943
944
945 /* Seeking. */
946
947 static void seek_to_beginning(ALLEGRO_VIDEO *video, OGG_VIDEO *ogv,
948 THEORA_STREAM *tstream)
949 {
950 unsigned i;
951 int rc;
952 bool seeked;
953
954 for (i = 0; i < _al_vector_size(&ogv->streams); i++) {
955 STREAM **slot = _al_vector_ref(&ogv->streams, i);
956 STREAM *stream = *slot;
957
958 ogg_stream_reset(&stream->state);
959 free_packet_queue(stream);
960 }
961
962 if (tstream) {
963 ogg_int64_t granpos = 0;
964
965 rc = th_decode_ctl(tstream->ctx, TH_DECCTL_SET_GRANPOS, &granpos,
966 sizeof(granpos));
967 ASSERT(rc == 0);
968
969 tstream->prev_framenum = -1;
970 }
971
972 rc = ogg_sync_reset(&ogv->sync_state);
973 ASSERT(rc == 0);
974
975 seeked = al_fseek(ogv->fp, 0, SEEK_SET);
976 ASSERT(seeked);
977 /* XXX read enough file data to get into position */
978
979 ogv->reached_eof = false;
980 video->audio_position = 0.0;
981 video->video_position = 0.0;
982 video->position = 0.0;
983
984 /* XXX maybe clear backlog of time and stream fragment events */
985 }
986
987 /* Decode thread. */
988
989 static void *decode_thread_func(ALLEGRO_THREAD *thread, void *_video)
990 {
991 ALLEGRO_VIDEO * const video = _video;
992 OGG_VIDEO * const ogv = video->data;
993 STREAM *tstream_outer;
994 THEORA_STREAM *tstream = NULL;
995 STREAM *vstream_outer;
996 VORBIS_STREAM *vstream = NULL;
997 ALLEGRO_TIMER *timer;
998 double audio_pos_step = 0.0;
999 double timer_dur;
1000
1001 ALLEGRO_DEBUG("Thread started.\n");
1002
1003 /* Destruction is handled by al_close_video. */
1004 _al_push_destructor_owner();
1005 tstream_outer = ogv->selected_video_stream;
1006 if (tstream_outer) {
1007 ASSERT(tstream_outer->stream_type == STREAM_TYPE_THEORA);
1008 tstream = &tstream_outer->u.theora;
1009 }
1010
1011 vstream_outer = ogv->selected_audio_stream;
1012 if (vstream_outer) {
1013 ASSERT(vstream_outer->stream_type == STREAM_TYPE_VORBIS);
1014
1015 video->audio = create_audio_stream(video, vstream_outer);
1016 if (video->audio) {
1017 vstream = &vstream_outer->u.vorbis;
1018 audio_pos_step = (double)FRAG_SAMPLES / vstream->info.rate;
1019 }
1020 else {
1021 deactivate_stream(vstream_outer);
1022 vstream_outer = NULL;
1023 }
1024 }
1025
1026 if (!tstream_outer && !vstream_outer) {
1027 ALLEGRO_WARN("No audio or video stream found.\n");
1028 _al_pop_destructor_owner();
1029 return NULL;
1030 }
1031
1032 timer_dur = 1.0;
1033 if (audio_pos_step != 0.0) {
1034 timer_dur = audio_pos_step / NUM_FRAGS;
1035 }
1036 if (tstream && tstream->frame_duration < timer_dur) {
1037 timer_dur = tstream->frame_duration;
1038 }
1039 timer = al_create_timer(timer_dur);
1040 al_register_event_source(ogv->queue, al_get_timer_event_source(timer));
1041
1042 if (video->audio) {
1043 al_register_event_source(ogv->queue,
1044 al_get_audio_stream_event_source(video->audio));
1045 }
1046 _al_pop_destructor_owner();
1047
1048 ALLEGRO_DEBUG("Begin decode loop.\n");
1049
1050 al_start_timer(timer);
1051
1052 while (!al_get_thread_should_stop(thread)) {
1053 ALLEGRO_EVENT ev;
1054
1055 al_wait_for_event(ogv->queue, &ev);
1056
1057 if (ev.type == _ALLEGRO_EVENT_VIDEO_SEEK) {
1058 double seek_to = ev.user.data1 / 1.0e6;
1059 /* XXX we only know how to seek to start of video */
1060 ASSERT(seek_to <= 0.0);
1061 al_lock_mutex(ogv->mutex);
1062 seek_to_beginning(video, ogv, tstream);
1063 ogv->seek_counter++;
1064 al_broadcast_cond(ogv->cond);
1065 al_unlock_mutex(ogv->mutex);
1066 continue;
1067 }
1068
1069 if (ev.type == ALLEGRO_EVENT_TIMER) {
1070 if (vstream_outer && video->playing) {
1071 poll_vorbis_decode(ogv, vstream_outer);
1072 }
1073
1074 /* If no audio then video is master. */
1075 if (!video->audio && video->playing && !ogv->reached_eof) {
1076 video->position += tstream->frame_duration;
1077 }
1078
1079 if (tstream_outer) {
1080 poll_theora_decode(video, tstream_outer);
1081 }
1082
1083 if (video->playing && ogv->reached_eof) {
1084 ALLEGRO_EVENT event;
1085 video->playing = false;
1086
1087 event.type = ALLEGRO_EVENT_VIDEO_FINISHED;
1088 event.user.data1 = (intptr_t)video;
1089 al_emit_user_event(&video->es, &event, NULL);
1090 }
1091 }
1092
1093 if (ev.type == ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT) {
1094 /* Audio clock is master when it exists. */
1095 /* XXX This doesn't work well when the process is paused then resumed,
1096 * due to a problem with the audio addon. We get a flood of
1097 * fragment events which pushes the position field ahead of the
1098 * real audio position.
1099 */
1100 if (video->playing && !ogv->reached_eof) {
1101 video->audio_position += audio_pos_step;
1102 video->position = video->audio_position - NUM_FRAGS * audio_pos_step;
1103 }
1104 update_audio_fragment(video->audio, vstream, !video->playing,
1105 ogv->reached_eof);
1106 }
1107 }
1108
1109 ALLEGRO_DEBUG("End decode loop.\n");
1110
1111 if (video->audio) {
1112 al_drain_audio_stream(video->audio);
1113 al_destroy_audio_stream(video->audio);
1114 video->audio = NULL;
1115 }
1116 al_destroy_timer(timer);
1117
1118 ALLEGRO_DEBUG("Thread exit.\n");
1119
1120 return NULL;
1121 }
1122
1123
1124 static bool update_frame_bmp(OGG_VIDEO *ogv)
1125 {
1126 ALLEGRO_LOCKED_REGION *lr;
1127 int y;
1128 int pitch = al_get_pixel_size(RGB_PIXEL_FORMAT) * al_get_bitmap_width(ogv->frame_bmp);
1129
1130 lr = al_lock_bitmap(ogv->frame_bmp, RGB_PIXEL_FORMAT,
1131 ALLEGRO_LOCK_WRITEONLY);
1132 if (!lr) {
1133 ALLEGRO_ERROR("Failed to lock bitmap.\n");
1134 return false;
1135 }
1136
1137 for (y = 0; y < al_get_bitmap_height(ogv->frame_bmp); y++) {
1138 memcpy((unsigned char*)lr->data + y * lr->pitch, ogv->rgb_data + y * pitch, pitch);
1139 }
1140
1141 al_unlock_bitmap(ogv->frame_bmp);
1142 return true;
1143 }
1144
1145
1146 /* Video interface. */
1147
1148 static bool do_open_video(ALLEGRO_VIDEO *video, OGG_VIDEO *ogv)
1149 {
1150 unsigned i;
1151
1152 read_headers(ogv);
1153
1154 /* Select the first Theora and Vorbis tracks. */
1155 for (i = 0; i < _al_vector_size(&ogv->streams); i++) {
1156 STREAM **slot = _al_vector_ref(&ogv->streams, i);
1157 STREAM *stream = *slot;
1158
1159 if (stream->stream_type == STREAM_TYPE_THEORA &&
1160 !ogv->selected_video_stream)
1161 {
1162 setup_theora_stream_decode(video, ogv, stream);
1163 ogv->selected_video_stream = stream;
1164 }
1165 else if (stream->stream_type == STREAM_TYPE_VORBIS &&
1166 !ogv->selected_audio_stream)
1167 {
1168 setup_vorbis_stream_decode(video, stream);
1169 ogv->selected_audio_stream = stream;
1170 }
1171 else {
1172 deactivate_stream(stream);
1173 }
1174 }
1175
1176 return ogv->selected_video_stream || ogv->selected_audio_stream;
1177 }
1178
1179 static bool ogv_open_video(ALLEGRO_VIDEO *video)
1180 {
1181 ALLEGRO_FILE *fp;
1182 OGG_VIDEO *ogv;
1183 int rc;
1184
1185 fp = video->file;
1186 if (!fp) {
1187 ALLEGRO_WARN("Failed to open video file from file interface.\n");
1188 return false;
1189 }
1190
1191 ogv = al_calloc(1, sizeof(OGG_VIDEO));
1192 if (!ogv) {
1193 ALLEGRO_ERROR("Out of memory.\n");
1194 al_fclose(fp);
1195 return false;
1196 }
1197 ogv->fp = fp;
1198 rc = ogg_sync_init(&ogv->sync_state);
1199 ASSERT(rc == 0);
1200 _al_vector_init(&ogv->streams, sizeof(STREAM *));
1201
1202 if (!do_open_video(video, ogv)) {
1203 ALLEGRO_ERROR("No audio or video stream found.\n");
1204 ogv_close_video(video);
1205 return false;
1206 }
1207
1208 /* ogv->mutex and ogv->thread are created in ogv_start_video. */
1209
1210 video->data = ogv;
1211 return true;
1212 }
1213 static bool ogv_close_video(ALLEGRO_VIDEO *video)
1214 {
1215 OGG_VIDEO *ogv;
1216 unsigned i;
1217
1218 ogv = video->data;
1219 if (ogv) {
1220 if (ogv->thread) {
1221 al_join_thread(ogv->thread, NULL);
1222 al_destroy_user_event_source(&ogv->evtsrc);
1223 al_destroy_event_queue(ogv->queue);
1224 al_destroy_mutex(ogv->mutex);
1225 al_destroy_cond(ogv->cond);
1226 al_destroy_thread(ogv->thread);
1227 }
1228
1229 al_fclose(ogv->fp);
1230 ogg_sync_clear(&ogv->sync_state);
1231 for (i = 0; i < _al_vector_size(&ogv->streams); i++) {
1232 STREAM **slot = _al_vector_ref(&ogv->streams, i);
1233 free_stream(*slot);
1234 }
1235 _al_vector_free(&ogv->streams);
1236 if (ogv->pic_bmp != ogv->frame_bmp) {
1237 al_destroy_bitmap(ogv->pic_bmp);
1238 }
1239 al_destroy_bitmap(ogv->frame_bmp);
1240
1241 al_free(ogv->rgb_data);
1242
1243 al_free(ogv);
1244 }
1245 video->data = NULL;
1246
1247 return true;
1248 }
1249
1250 static bool ogv_start_video(ALLEGRO_VIDEO *video)
1251 {
1252 OGG_VIDEO *ogv = video->data;
1253
1254 if (ogv->thread != NULL) {
1255 ALLEGRO_ERROR("Thread already created.\n");
1256 return false;
1257 }
1258
1259 ogv->thread = al_create_thread(decode_thread_func, video);
1260 if (!ogv->thread) {
1261 ALLEGRO_ERROR("Could not create thread.\n");
1262 return false;
1263 }
1264
1265 al_init_user_event_source(&ogv->evtsrc);
1266 ogv->queue = al_create_event_queue();
1267 ogv->mutex = al_create_mutex();
1268 ogv->cond = al_create_cond();
1269
1270 al_register_event_source(ogv->queue, &ogv->evtsrc);
1271
1272 al_start_thread(ogv->thread);
1273 return true;
1274 }
1275
1276 static bool ogv_set_video_playing(ALLEGRO_VIDEO *video)
1277 {
1278 OGG_VIDEO * const ogv = video->data;
1279 if (ogv->reached_eof) {
1280 video->playing = false;
1281 }
1282 return true;
1283 }
1284
1285 static bool ogv_seek_video(ALLEGRO_VIDEO *video, double seek_to)
1286 {
1287 OGG_VIDEO *ogv = video->data;
1288 ALLEGRO_EVENT ev;
1289 int seek_counter;
1290
1291 /* XXX we only know how to seek to beginning */
1292 if (seek_to > 0.0) {
1293 return false;
1294 }
1295
1296 al_lock_mutex(ogv->mutex);
1297
1298 seek_counter = ogv->seek_counter;
1299
1300 ev.user.type = _ALLEGRO_EVENT_VIDEO_SEEK;
1301 ev.user.data1 = seek_to * 1.0e6;
1302 ev.user.data2 = 0;
1303 ev.user.data3 = 0;
1304 ev.user.data4 = 0;
1305 al_emit_user_event(&ogv->evtsrc, &ev, NULL);
1306
1307 while (seek_counter == ogv->seek_counter) {
1308 al_wait_cond(ogv->cond, ogv->mutex);
1309 }
1310
1311 al_unlock_mutex(ogv->mutex);
1312
1313 return true;
1314 }
1315
1316 static bool ogv_update_video(ALLEGRO_VIDEO *video)
1317 {
1318 OGG_VIDEO *ogv = video->data;
1319 int w, h;
1320 bool ret;
1321
1322 al_lock_mutex(ogv->mutex);
1323
1324 w = ogv->buffer[0].width;
1325 h = ogv->buffer[0].height;
1326
1327 if (w > 0 && h && h > 0 && ogv->frame_bmp) {
1328 ASSERT(w == al_get_bitmap_width(ogv->frame_bmp));
1329 ASSERT(h == al_get_bitmap_height(ogv->frame_bmp));
1330
1331 if (ogv->buffer_dirty) {
1332 ret = update_frame_bmp(ogv);
1333 ogv->buffer_dirty = false;
1334 }
1335 else {
1336 ret = true;
1337 }
1338
1339 video->current_frame = ogv->pic_bmp;
1340 }
1341 else {
1342 /* No frame ready yet. */
1343 ret = false;
1344 }
1345
1346 al_unlock_mutex(ogv->mutex);
1347
1348 return ret;
1349 }
1350
1351 static ALLEGRO_VIDEO_INTERFACE ogv_vtable = {
1352 ogv_open_video,
1353 ogv_close_video,
1354 ogv_start_video,
1355 ogv_set_video_playing,
1356 ogv_seek_video,
1357 ogv_update_video,
1358 };
1359
1360 ALLEGRO_VIDEO_INTERFACE *_al_video_ogv_vtable(void)
1361 {
1362 return &ogv_vtable;
1363 }
1364
1365 bool _al_video_identify_ogv(ALLEGRO_FILE *f)
1366 {
1367 uint8_t x[4];
1368 if (al_fread(f, x, 4) < 4)
1369 return false;
1370 /* TODO: This technically only verifies that this is an OGG container,
1371 * saying nothing of the contents. Maybe refactor read_headers and make
1372 * use of it here. */
1373 if (memcmp(x, "OggS", 4) == 0)
1374 return true;
1375 return false;
1376 }
1377
1378 /* vim: set sts=3 sw=3 et: */