use intreadwrite functions in matroskadec
[ffmpeg.git] / libavformat / matroskadec.c
1 /*
2  * Matroska file demuxer (no muxer yet)
3  * Copyright (c) 2003-2004 The ffmpeg Project
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file matroskadec.c
24  * Matroska file demuxer
25  * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * Specs available on the matroska project page:
28  * http://www.matroska.org/.
29  */
30
31 #include "avformat.h"
32 /* For codec_get_id(). */
33 #include "riff.h"
34 #include "intfloat_readwrite.h"
35 #include "matroska.h"
36
37 typedef struct Track {
38     MatroskaTrackType type;
39
40     /* Unique track number and track ID. stream_index is the index that
41      * the calling app uses for this track. */
42     uint32_t num;
43     uint32_t uid;
44     uint32_t stream_index;
45
46     char *name;
47     char *language;
48
49     char *codec_id;
50     char *codec_name;
51
52     unsigned char *codec_priv;
53     int codec_priv_size;
54
55     uint64_t default_duration;
56     MatroskaTrackFlags flags;
57 } MatroskaTrack;
58
59 typedef struct MatroskaVideoTrack {
60     MatroskaTrack track;
61
62     int pixel_width;
63     int pixel_height;
64     int display_width;
65     int display_height;
66
67     uint32_t fourcc;
68
69     MatroskaAspectRatioMode ar_mode;
70     MatroskaEyeMode eye_mode;
71
72     //..
73 } MatroskaVideoTrack;
74
75 typedef struct MatroskaAudioTrack {
76     MatroskaTrack track;
77
78     int channels;
79     int bitdepth;
80     int internal_samplerate;
81     int samplerate;
82     int block_align;
83
84     /* real audio header */
85     int coded_framesize;
86     int sub_packet_h;
87     int frame_size;
88     int sub_packet_size;
89     int sub_packet_cnt;
90     int pkt_cnt;
91     uint8_t *buf;
92     //..
93 } MatroskaAudioTrack;
94
95 typedef struct MatroskaSubtitleTrack {
96     MatroskaTrack track;
97
98     //..
99 } MatroskaSubtitleTrack;
100
101 #define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
102                                     sizeof(MatroskaAudioTrack)), \
103                                     sizeof(MatroskaSubtitleTrack)))
104
105 typedef struct MatroskaLevel {
106     uint64_t start;
107     uint64_t length;
108 } MatroskaLevel;
109
110 typedef struct MatroskaDemuxIndex {
111   uint64_t        pos;   /* of the corresponding *cluster*! */
112   uint16_t        track; /* reference to 'num' */
113   uint64_t        time;  /* in nanoseconds */
114 } MatroskaDemuxIndex;
115
116 typedef struct MatroskaDemuxContext {
117     AVFormatContext *ctx;
118
119     /* ebml stuff */
120     int num_levels;
121     MatroskaLevel levels[EBML_MAX_DEPTH];
122     int level_up;
123
124     /* matroska stuff */
125     char *writing_app;
126     char *muxing_app;
127     int64_t created;
128
129     /* timescale in the file */
130     int64_t time_scale;
131
132     /* num_streams is the number of streams that av_new_stream() was called
133      * for ( = that are available to the calling program). */
134     int num_tracks;
135     int num_streams;
136     MatroskaTrack *tracks[MAX_STREAMS];
137
138     /* cache for ID peeking */
139     uint32_t peek_id;
140
141     /* byte position of the segment inside the stream */
142     offset_t segment_start;
143
144     /* The packet queue. */
145     AVPacket **packets;
146     int num_packets;
147
148     /* have we already parse metadata/cues/clusters? */
149     int metadata_parsed;
150     int index_parsed;
151     int done;
152
153     /* The index for seeking. */
154     int num_indexes;
155     MatroskaDemuxIndex *index;
156
157     /* What to skip before effectively reading a packet. */
158     int skip_to_keyframe;
159     AVStream *skip_to_stream;
160 } MatroskaDemuxContext;
161
162 /*
163  * The first few functions handle EBML file parsing. The rest
164  * is the document interpretation. Matroska really just is a
165  * EBML file.
166  */
167
168 /*
169  * Return: the amount of levels in the hierarchy that the
170  * current element lies higher than the previous one.
171  * The opposite isn't done - that's auto-done using master
172  * element reading.
173  */
174
175 static int
176 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
177 {
178     ByteIOContext *pb = &matroska->ctx->pb;
179     offset_t pos = url_ftell(pb);
180     int num = 0;
181
182     while (matroska->num_levels > 0) {
183         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
184
185         if (pos >= level->start + level->length) {
186             matroska->num_levels--;
187             num++;
188         } else {
189             break;
190         }
191     }
192
193     return num;
194 }
195
196 /*
197  * Read: an "EBML number", which is defined as a variable-length
198  * array of bytes. The first byte indicates the length by giving a
199  * number of 0-bits followed by a one. The position of the first
200  * "one" bit inside the first byte indicates the length of this
201  * number.
202  * Returns: num. of bytes read. < 0 on error.
203  */
204
205 static int
206 ebml_read_num (MatroskaDemuxContext *matroska,
207                int                   max_size,
208                uint64_t             *number)
209 {
210     ByteIOContext *pb = &matroska->ctx->pb;
211     int len_mask = 0x80, read = 1, n = 1;
212     int64_t total = 0;
213
214     /* the first byte tells us the length in bytes - get_byte() can normally
215      * return 0, but since that's not a valid first ebmlID byte, we can
216      * use it safely here to catch EOS. */
217     if (!(total = get_byte(pb))) {
218         /* we might encounter EOS here */
219         if (!url_feof(pb)) {
220             offset_t pos = url_ftell(pb);
221             av_log(matroska->ctx, AV_LOG_ERROR,
222                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
223                    pos, pos);
224         }
225         return AVERROR_IO; /* EOS or actual I/O error */
226     }
227
228     /* get the length of the EBML number */
229     while (read <= max_size && !(total & len_mask)) {
230         read++;
231         len_mask >>= 1;
232     }
233     if (read > max_size) {
234         offset_t pos = url_ftell(pb) - 1;
235         av_log(matroska->ctx, AV_LOG_ERROR,
236                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
237                (uint8_t) total, pos, pos);
238         return AVERROR_INVALIDDATA;
239     }
240
241     /* read out length */
242     total &= ~len_mask;
243     while (n++ < read)
244         total = (total << 8) | get_byte(pb);
245
246     *number = total;
247
248     return read;
249 }
250
251 /*
252  * Read: the element content data ID.
253  * Return: the number of bytes read or < 0 on error.
254  */
255
256 static int
257 ebml_read_element_id (MatroskaDemuxContext *matroska,
258                       uint32_t             *id,
259                       int                  *level_up)
260 {
261     int read;
262     uint64_t total;
263
264     /* if we re-call this, use our cached ID */
265     if (matroska->peek_id != 0) {
266         if (level_up)
267             *level_up = 0;
268         *id = matroska->peek_id;
269         return 0;
270     }
271
272     /* read out the "EBML number", include tag in ID */
273     if ((read = ebml_read_num(matroska, 4, &total)) < 0)
274         return read;
275     *id = matroska->peek_id  = total | (1 << (read * 7));
276
277     /* level tracking */
278     if (level_up)
279         *level_up = ebml_read_element_level_up(matroska);
280
281     return read;
282 }
283
284 /*
285  * Read: element content length.
286  * Return: the number of bytes read or < 0 on error.
287  */
288
289 static int
290 ebml_read_element_length (MatroskaDemuxContext *matroska,
291                           uint64_t             *length)
292 {
293     /* clear cache since we're now beyond that data point */
294     matroska->peek_id = 0;
295
296     /* read out the "EBML number", include tag in ID */
297     return ebml_read_num(matroska, 8, length);
298 }
299
300 /*
301  * Return: the ID of the next element, or 0 on error.
302  * Level_up contains the amount of levels that this
303  * next element lies higher than the previous one.
304  */
305
306 static uint32_t
307 ebml_peek_id (MatroskaDemuxContext *matroska,
308               int                  *level_up)
309 {
310     uint32_t id;
311
312     assert(level_up != NULL);
313
314     if (ebml_read_element_id(matroska, &id, level_up) < 0)
315         return 0;
316
317     return id;
318 }
319
320 /*
321  * Seek to a given offset.
322  * 0 is success, -1 is failure.
323  */
324
325 static int
326 ebml_read_seek (MatroskaDemuxContext *matroska,
327                 offset_t              offset)
328 {
329     ByteIOContext *pb = &matroska->ctx->pb;
330
331     /* clear ID cache, if any */
332     matroska->peek_id = 0;
333
334     return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
335 }
336
337 /*
338  * Skip the next element.
339  * 0 is success, -1 is failure.
340  */
341
342 static int
343 ebml_read_skip (MatroskaDemuxContext *matroska)
344 {
345     ByteIOContext *pb = &matroska->ctx->pb;
346     uint32_t id;
347     uint64_t length;
348     int res;
349
350     if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
351         (res = ebml_read_element_length(matroska, &length)) < 0)
352         return res;
353
354     url_fskip(pb, length);
355
356     return 0;
357 }
358
359 /*
360  * Read the next element as an unsigned int.
361  * 0 is success, < 0 is failure.
362  */
363
364 static int
365 ebml_read_uint (MatroskaDemuxContext *matroska,
366                 uint32_t             *id,
367                 uint64_t             *num)
368 {
369     ByteIOContext *pb = &matroska->ctx->pb;
370     int n = 0, size, res;
371     uint64_t rlength;
372
373     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
374         (res = ebml_read_element_length(matroska, &rlength)) < 0)
375         return res;
376     size = rlength;
377     if (size < 1 || size > 8) {
378         offset_t pos = url_ftell(pb);
379         av_log(matroska->ctx, AV_LOG_ERROR,
380                "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
381                 size, pos, pos);
382         return AVERROR_INVALIDDATA;
383     }
384
385     /* big-endian ordening; build up number */
386     *num = 0;
387     while (n++ < size)
388         *num = (*num << 8) | get_byte(pb);
389
390     return 0;
391 }
392
393 /*
394  * Read the next element as a signed int.
395  * 0 is success, < 0 is failure.
396  */
397
398 static int
399 ebml_read_sint (MatroskaDemuxContext *matroska,
400                 uint32_t             *id,
401                 int64_t              *num)
402 {
403     ByteIOContext *pb = &matroska->ctx->pb;
404     int size, n = 1, negative = 0, res;
405     uint64_t rlength;
406
407     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
408         (res = ebml_read_element_length(matroska, &rlength)) < 0)
409         return res;
410     size = rlength;
411     if (size < 1 || size > 8) {
412         offset_t pos = url_ftell(pb);
413         av_log(matroska->ctx, AV_LOG_ERROR,
414                "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
415                 size, pos, pos);
416         return AVERROR_INVALIDDATA;
417     }
418     if ((*num = get_byte(pb)) & 0x80) {
419         negative = 1;
420         *num &= ~0x80;
421     }
422     while (n++ < size)
423         *num = (*num << 8) | get_byte(pb);
424
425     /* make signed */
426     if (negative)
427         *num = *num - (1LL << ((8 * size) - 1));
428
429     return 0;
430 }
431
432 /*
433  * Read the next element as a float.
434  * 0 is success, < 0 is failure.
435  */
436
437 static int
438 ebml_read_float (MatroskaDemuxContext *matroska,
439                  uint32_t             *id,
440                  double               *num)
441 {
442     ByteIOContext *pb = &matroska->ctx->pb;
443     int size, res;
444     uint64_t rlength;
445
446     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
447         (res = ebml_read_element_length(matroska, &rlength)) < 0)
448         return res;
449     size = rlength;
450
451     if (size == 4) {
452         *num= av_int2flt(get_be32(pb));
453     } else if(size==8){
454         *num= av_int2dbl(get_be64(pb));
455     } else{
456         offset_t pos = url_ftell(pb);
457         av_log(matroska->ctx, AV_LOG_ERROR,
458                "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
459                size, pos, pos);
460         return AVERROR_INVALIDDATA;
461     }
462
463     return 0;
464 }
465
466 /*
467  * Read the next element as an ASCII string.
468  * 0 is success, < 0 is failure.
469  */
470
471 static int
472 ebml_read_ascii (MatroskaDemuxContext *matroska,
473                  uint32_t             *id,
474                  char                **str)
475 {
476     ByteIOContext *pb = &matroska->ctx->pb;
477     int size, res;
478     uint64_t rlength;
479
480     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
481         (res = ebml_read_element_length(matroska, &rlength)) < 0)
482         return res;
483     size = rlength;
484
485     /* ebml strings are usually not 0-terminated, so we allocate one
486      * byte more, read the string and NULL-terminate it ourselves. */
487     if (size < 0 || !(*str = av_malloc(size + 1))) {
488         av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
489         return AVERROR_NOMEM;
490     }
491     if (get_buffer(pb, (uint8_t *) *str, size) != size) {
492         offset_t pos = url_ftell(pb);
493         av_log(matroska->ctx, AV_LOG_ERROR,
494                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
495         return AVERROR_IO;
496     }
497     (*str)[size] = '\0';
498
499     return 0;
500 }
501
502 /*
503  * Read the next element as a UTF-8 string.
504  * 0 is success, < 0 is failure.
505  */
506
507 static int
508 ebml_read_utf8 (MatroskaDemuxContext *matroska,
509                 uint32_t             *id,
510                 char                **str)
511 {
512   return ebml_read_ascii(matroska, id, str);
513 }
514
515 /*
516  * Read the next element as a date (nanoseconds since 1/1/2000).
517  * 0 is success, < 0 is failure.
518  */
519
520 static int
521 ebml_read_date (MatroskaDemuxContext *matroska,
522                 uint32_t             *id,
523                 int64_t              *date)
524 {
525   return ebml_read_sint(matroska, id, date);
526 }
527
528 /*
529  * Read the next element, but only the header. The contents
530  * are supposed to be sub-elements which can be read separately.
531  * 0 is success, < 0 is failure.
532  */
533
534 static int
535 ebml_read_master (MatroskaDemuxContext *matroska,
536                   uint32_t             *id)
537 {
538     ByteIOContext *pb = &matroska->ctx->pb;
539     uint64_t length;
540     MatroskaLevel *level;
541     int res;
542
543     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
544         (res = ebml_read_element_length(matroska, &length)) < 0)
545         return res;
546
547     /* protect... (Heaven forbids that the '>' is true) */
548     if (matroska->num_levels >= EBML_MAX_DEPTH) {
549         av_log(matroska->ctx, AV_LOG_ERROR,
550                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
551         return AVERROR_NOTSUPP;
552     }
553
554     /* remember level */
555     level = &matroska->levels[matroska->num_levels++];
556     level->start = url_ftell(pb);
557     level->length = length;
558
559     return 0;
560 }
561
562 /*
563  * Read the next element as binary data.
564  * 0 is success, < 0 is failure.
565  */
566
567 static int
568 ebml_read_binary (MatroskaDemuxContext *matroska,
569                   uint32_t             *id,
570                   uint8_t             **binary,
571                   int                  *size)
572 {
573     ByteIOContext *pb = &matroska->ctx->pb;
574     uint64_t rlength;
575     int res;
576
577     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
578         (res = ebml_read_element_length(matroska, &rlength)) < 0)
579         return res;
580     *size = rlength;
581
582     if (!(*binary = av_malloc(*size))) {
583         av_log(matroska->ctx, AV_LOG_ERROR,
584                "Memory allocation error\n");
585         return AVERROR_NOMEM;
586     }
587
588     if (get_buffer(pb, *binary, *size) != *size) {
589         offset_t pos = url_ftell(pb);
590         av_log(matroska->ctx, AV_LOG_ERROR,
591                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
592         return AVERROR_IO;
593     }
594
595     return 0;
596 }
597
598 /*
599  * Read signed/unsigned "EBML" numbers.
600  * Return: number of bytes processed, < 0 on error.
601  * XXX: use ebml_read_num().
602  */
603
604 static int
605 matroska_ebmlnum_uint (uint8_t  *data,
606                        uint32_t  size,
607                        uint64_t *num)
608 {
609     int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
610     uint64_t total;
611
612     if (size <= 0)
613         return AVERROR_INVALIDDATA;
614
615     total = data[0];
616     while (read <= 8 && !(total & len_mask)) {
617         read++;
618         len_mask >>= 1;
619     }
620     if (read > 8)
621         return AVERROR_INVALIDDATA;
622
623     if ((total &= (len_mask - 1)) == len_mask - 1)
624         num_ffs++;
625     if (size < read)
626         return AVERROR_INVALIDDATA;
627     while (n < read) {
628         if (data[n] == 0xff)
629             num_ffs++;
630         total = (total << 8) | data[n];
631         n++;
632     }
633
634     if (read == num_ffs)
635         *num = (uint64_t)-1;
636     else
637         *num = total;
638
639     return read;
640 }
641
642 /*
643  * Same as above, but signed.
644  */
645
646 static int
647 matroska_ebmlnum_sint (uint8_t  *data,
648                        uint32_t  size,
649                        int64_t  *num)
650 {
651     uint64_t unum;
652     int res;
653
654     /* read as unsigned number first */
655     if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
656         return res;
657
658     /* make signed (weird way) */
659     if (unum == (uint64_t)-1)
660         *num = INT64_MAX;
661     else
662         *num = unum - ((1LL << ((7 * res) - 1)) - 1);
663
664     return res;
665 }
666
667 /*
668  * Read an EBML header.
669  * 0 is success, < 0 is failure.
670  */
671
672 static int
673 ebml_read_header (MatroskaDemuxContext *matroska,
674                   char                **doctype,
675                   int                  *version)
676 {
677     uint32_t id;
678     int level_up, res = 0;
679
680     /* default init */
681     if (doctype)
682         *doctype = NULL;
683     if (version)
684         *version = 1;
685
686     if (!(id = ebml_peek_id(matroska, &level_up)) ||
687         level_up != 0 || id != EBML_ID_HEADER) {
688         av_log(matroska->ctx, AV_LOG_ERROR,
689                "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
690         return AVERROR_INVALIDDATA;
691     }
692     if ((res = ebml_read_master(matroska, &id)) < 0)
693         return res;
694
695     while (res == 0) {
696         if (!(id = ebml_peek_id(matroska, &level_up)))
697             return AVERROR_IO;
698
699         /* end-of-header */
700         if (level_up)
701             break;
702
703         switch (id) {
704             /* is our read version uptodate? */
705             case EBML_ID_EBMLREADVERSION: {
706                 uint64_t num;
707
708                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
709                     return res;
710                 if (num > EBML_VERSION) {
711                     av_log(matroska->ctx, AV_LOG_ERROR,
712                            "EBML version %"PRIu64" (> %d) is not supported\n",
713                            num, EBML_VERSION);
714                     return AVERROR_INVALIDDATA;
715                 }
716                 break;
717             }
718
719             /* we only handle 8 byte lengths at max */
720             case EBML_ID_EBMLMAXSIZELENGTH: {
721                 uint64_t num;
722
723                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
724                     return res;
725                 if (num > sizeof(uint64_t)) {
726                     av_log(matroska->ctx, AV_LOG_ERROR,
727                            "Integers of size %"PRIu64" (> %zd) not supported\n",
728                            num, sizeof(uint64_t));
729                     return AVERROR_INVALIDDATA;
730                 }
731                 break;
732             }
733
734             /* we handle 4 byte IDs at max */
735             case EBML_ID_EBMLMAXIDLENGTH: {
736                 uint64_t num;
737
738                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
739                     return res;
740                 if (num > sizeof(uint32_t)) {
741                     av_log(matroska->ctx, AV_LOG_ERROR,
742                            "IDs of size %"PRIu64" (> %zu) not supported\n",
743                             num, sizeof(uint32_t));
744                     return AVERROR_INVALIDDATA;
745                 }
746                 break;
747             }
748
749             case EBML_ID_DOCTYPE: {
750                 char *text;
751
752                 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
753                     return res;
754                 if (doctype) {
755                     if (*doctype)
756                         av_free(*doctype);
757                     *doctype = text;
758                 } else
759                     av_free(text);
760                 break;
761             }
762
763             case EBML_ID_DOCTYPEREADVERSION: {
764                 uint64_t num;
765
766                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
767                     return res;
768                 if (version)
769                     *version = num;
770                 break;
771             }
772
773             default:
774                 av_log(matroska->ctx, AV_LOG_INFO,
775                        "Unknown data type 0x%x in EBML header", id);
776                 /* pass-through */
777
778             case EBML_ID_VOID:
779             /* we ignore these two, as they don't tell us anything we
780              * care about */
781             case EBML_ID_EBMLVERSION:
782             case EBML_ID_DOCTYPEVERSION:
783                 res = ebml_read_skip (matroska);
784                 break;
785         }
786     }
787
788     return 0;
789 }
790
791
792 static int
793 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
794                             int                   num)
795 {
796     int i;
797
798     for (i = 0; i < matroska->num_tracks; i++)
799         if (matroska->tracks[i]->num == num)
800             return i;
801
802     return -1;
803 }
804
805
806 /*
807  * Put one packet in an application-supplied AVPacket struct.
808  * Returns 0 on success or -1 on failure.
809  */
810
811 static int
812 matroska_deliver_packet (MatroskaDemuxContext *matroska,
813                          AVPacket             *pkt)
814 {
815     if (matroska->num_packets > 0) {
816         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
817         av_free(matroska->packets[0]);
818         if (matroska->num_packets > 1) {
819             memmove(&matroska->packets[0], &matroska->packets[1],
820                     (matroska->num_packets - 1) * sizeof(AVPacket *));
821             matroska->packets =
822                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
823                            sizeof(AVPacket *));
824         } else {
825             av_freep(&matroska->packets);
826         }
827         matroska->num_packets--;
828         return 0;
829     }
830
831     return -1;
832 }
833
834 /*
835  * Put a packet into our internal queue. Will be delivered to the
836  * user/application during the next get_packet() call.
837  */
838
839 static void
840 matroska_queue_packet (MatroskaDemuxContext *matroska,
841                        AVPacket             *pkt)
842 {
843     matroska->packets =
844         av_realloc(matroska->packets, (matroska->num_packets + 1) *
845                    sizeof(AVPacket *));
846     matroska->packets[matroska->num_packets] = pkt;
847     matroska->num_packets++;
848 }
849
850
851 /*
852  * Autodetecting...
853  */
854
855 static int
856 matroska_probe (AVProbeData *p)
857 {
858     uint64_t total = 0;
859     int len_mask = 0x80, size = 1, n = 1;
860     uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
861
862     /* ebml header? */
863     if (AV_RB32(p->buf) != EBML_ID_HEADER)
864         return 0;
865
866     /* length of header */
867     total = p->buf[4];
868     while (size <= 8 && !(total & len_mask)) {
869         size++;
870         len_mask >>= 1;
871     }
872     if (size > 8)
873       return 0;
874     total &= (len_mask - 1);
875     while (n < size)
876         total = (total << 8) | p->buf[4 + n++];
877
878     /* does the probe data contain the whole header? */
879     if (p->buf_size < 4 + size + total)
880       return 0;
881
882     /* the header must contain the document type 'matroska'. For now,
883      * we don't parse the whole header but simply check for the
884      * availability of that array of characters inside the header.
885      * Not fully fool-proof, but good enough. */
886     for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
887         if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
888             return AVPROBE_SCORE_MAX;
889
890     return 0;
891 }
892
893 /*
894  * From here on, it's all XML-style DTD stuff... Needs no comments.
895  */
896
897 static int
898 matroska_parse_info (MatroskaDemuxContext *matroska)
899 {
900     int res = 0;
901     uint32_t id;
902
903     av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
904
905     while (res == 0) {
906         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
907             res = AVERROR_IO;
908             break;
909         } else if (matroska->level_up) {
910             matroska->level_up--;
911             break;
912         }
913
914         switch (id) {
915             /* cluster timecode */
916             case MATROSKA_ID_TIMECODESCALE: {
917                 uint64_t num;
918                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
919                     break;
920                 matroska->time_scale = num;
921                 break;
922             }
923
924             case MATROSKA_ID_DURATION: {
925                 double num;
926                 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
927                     break;
928                 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
929                 break;
930             }
931
932             case MATROSKA_ID_TITLE: {
933                 char *text;
934                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
935                     break;
936                 strncpy(matroska->ctx->title, text,
937                         sizeof(matroska->ctx->title)-1);
938                 av_free(text);
939                 break;
940             }
941
942             case MATROSKA_ID_WRITINGAPP: {
943                 char *text;
944                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
945                     break;
946                 matroska->writing_app = text;
947                 break;
948             }
949
950             case MATROSKA_ID_MUXINGAPP: {
951                 char *text;
952                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
953                     break;
954                 matroska->muxing_app = text;
955                 break;
956             }
957
958             case MATROSKA_ID_DATEUTC: {
959                 int64_t time;
960                 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
961                     break;
962                 matroska->created = time;
963                 break;
964             }
965
966             default:
967                 av_log(matroska->ctx, AV_LOG_INFO,
968                        "Unknown entry 0x%x in info header\n", id);
969                 /* fall-through */
970
971             case EBML_ID_VOID:
972                 res = ebml_read_skip(matroska);
973                 break;
974         }
975
976         if (matroska->level_up) {
977             matroska->level_up--;
978             break;
979         }
980     }
981
982     return res;
983 }
984
985 static int
986 matroska_add_stream (MatroskaDemuxContext *matroska)
987 {
988     int res = 0;
989     uint32_t id;
990     MatroskaTrack *track;
991
992     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
993
994     /* Allocate a generic track. As soon as we know its type we'll realloc. */
995     track = av_mallocz(MAX_TRACK_SIZE);
996     matroska->num_tracks++;
997
998     /* start with the master */
999     if ((res = ebml_read_master(matroska, &id)) < 0)
1000         return res;
1001
1002     /* try reading the trackentry headers */
1003     while (res == 0) {
1004         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1005             res = AVERROR_IO;
1006             break;
1007         } else if (matroska->level_up > 0) {
1008             matroska->level_up--;
1009             break;
1010         }
1011
1012         switch (id) {
1013             /* track number (unique stream ID) */
1014             case MATROSKA_ID_TRACKNUMBER: {
1015                 uint64_t num;
1016                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1017                     break;
1018                 track->num = num;
1019                 break;
1020             }
1021
1022             /* track UID (unique identifier) */
1023             case MATROSKA_ID_TRACKUID: {
1024                 uint64_t num;
1025                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1026                     break;
1027                 track->uid = num;
1028                 break;
1029             }
1030
1031             /* track type (video, audio, combined, subtitle, etc.) */
1032             case MATROSKA_ID_TRACKTYPE: {
1033                 uint64_t num;
1034                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1035                     break;
1036                 if (track->type && track->type != num) {
1037                     av_log(matroska->ctx, AV_LOG_INFO,
1038                            "More than one tracktype in an entry - skip\n");
1039                     break;
1040                 }
1041                 track->type = num;
1042
1043                 switch (track->type) {
1044                     case MATROSKA_TRACK_TYPE_VIDEO:
1045                     case MATROSKA_TRACK_TYPE_AUDIO:
1046                     case MATROSKA_TRACK_TYPE_SUBTITLE:
1047                         break;
1048                     case MATROSKA_TRACK_TYPE_COMPLEX:
1049                     case MATROSKA_TRACK_TYPE_LOGO:
1050                     case MATROSKA_TRACK_TYPE_CONTROL:
1051                     default:
1052                         av_log(matroska->ctx, AV_LOG_INFO,
1053                                "Unknown or unsupported track type 0x%x\n",
1054                                track->type);
1055                         track->type = 0;
1056                         break;
1057                 }
1058                 matroska->tracks[matroska->num_tracks - 1] = track;
1059                 break;
1060             }
1061
1062             /* tracktype specific stuff for video */
1063             case MATROSKA_ID_TRACKVIDEO: {
1064                 MatroskaVideoTrack *videotrack;
1065                 if (!track->type)
1066                     track->type = MATROSKA_TRACK_TYPE_VIDEO;
1067                 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1068                     av_log(matroska->ctx, AV_LOG_INFO,
1069                            "video data in non-video track - ignoring\n");
1070                     res = AVERROR_INVALIDDATA;
1071                     break;
1072                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1073                     break;
1074                 videotrack = (MatroskaVideoTrack *)track;
1075
1076                 while (res == 0) {
1077                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1078                         res = AVERROR_IO;
1079                         break;
1080                     } else if (matroska->level_up > 0) {
1081                         matroska->level_up--;
1082                         break;
1083                     }
1084
1085                     switch (id) {
1086                         /* fixme, this should be one-up, but I get it here */
1087                         case MATROSKA_ID_TRACKDEFAULTDURATION: {
1088                             uint64_t num;
1089                             if ((res = ebml_read_uint (matroska, &id,
1090                                                        &num)) < 0)
1091                                 break;
1092                             track->default_duration = num/matroska->time_scale;
1093                             break;
1094                         }
1095
1096                         /* video framerate */
1097                         case MATROSKA_ID_VIDEOFRAMERATE: {
1098                             double num;
1099                             if ((res = ebml_read_float(matroska, &id,
1100                                                        &num)) < 0)
1101                                 break;
1102                             track->default_duration = 1000000000/(matroska->time_scale*num);
1103                             break;
1104                         }
1105
1106                         /* width of the size to display the video at */
1107                         case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1108                             uint64_t num;
1109                             if ((res = ebml_read_uint(matroska, &id,
1110                                                       &num)) < 0)
1111                                 break;
1112                             videotrack->display_width = num;
1113                             break;
1114                         }
1115
1116                         /* height of the size to display the video at */
1117                         case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1118                             uint64_t num;
1119                             if ((res = ebml_read_uint(matroska, &id,
1120                                                       &num)) < 0)
1121                                 break;
1122                             videotrack->display_height = num;
1123                             break;
1124                         }
1125
1126                         /* width of the video in the file */
1127                         case MATROSKA_ID_VIDEOPIXELWIDTH: {
1128                             uint64_t num;
1129                             if ((res = ebml_read_uint(matroska, &id,
1130                                                       &num)) < 0)
1131                                 break;
1132                             videotrack->pixel_width = num;
1133                             break;
1134                         }
1135
1136                         /* height of the video in the file */
1137                         case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1138                             uint64_t num;
1139                             if ((res = ebml_read_uint(matroska, &id,
1140                                                       &num)) < 0)
1141                                 break;
1142                             videotrack->pixel_height = num;
1143                             break;
1144                         }
1145
1146                         /* whether the video is interlaced */
1147                         case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1148                             uint64_t num;
1149                             if ((res = ebml_read_uint(matroska, &id,
1150                                                       &num)) < 0)
1151                                 break;
1152                             if (num)
1153                                 track->flags |=
1154                                     MATROSKA_VIDEOTRACK_INTERLACED;
1155                             else
1156                                 track->flags &=
1157                                     ~MATROSKA_VIDEOTRACK_INTERLACED;
1158                             break;
1159                         }
1160
1161                         /* stereo mode (whether the video has two streams,
1162                          * where one is for the left eye and the other for
1163                          * the right eye, which creates a 3D-like
1164                          * effect) */
1165                         case MATROSKA_ID_VIDEOSTEREOMODE: {
1166                             uint64_t num;
1167                             if ((res = ebml_read_uint(matroska, &id,
1168                                                       &num)) < 0)
1169                                 break;
1170                             if (num != MATROSKA_EYE_MODE_MONO &&
1171                                 num != MATROSKA_EYE_MODE_LEFT &&
1172                                 num != MATROSKA_EYE_MODE_RIGHT &&
1173                                 num != MATROSKA_EYE_MODE_BOTH) {
1174                                 av_log(matroska->ctx, AV_LOG_INFO,
1175                                        "Ignoring unknown eye mode 0x%x\n",
1176                                        (uint32_t) num);
1177                                 break;
1178                             }
1179                             videotrack->eye_mode = num;
1180                             break;
1181                         }
1182
1183                         /* aspect ratio behaviour */
1184                         case MATROSKA_ID_VIDEOASPECTRATIO: {
1185                             uint64_t num;
1186                             if ((res = ebml_read_uint(matroska, &id,
1187                                                       &num)) < 0)
1188                                 break;
1189                             if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1190                                 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1191                                 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1192                                 av_log(matroska->ctx, AV_LOG_INFO,
1193                                        "Ignoring unknown aspect ratio 0x%x\n",
1194                                        (uint32_t) num);
1195                                 break;
1196                             }
1197                             videotrack->ar_mode = num;
1198                             break;
1199                         }
1200
1201                         /* colourspace (only matters for raw video)
1202                          * fourcc */
1203                         case MATROSKA_ID_VIDEOCOLOURSPACE: {
1204                             uint64_t num;
1205                             if ((res = ebml_read_uint(matroska, &id,
1206                                                       &num)) < 0)
1207                                 break;
1208                             videotrack->fourcc = num;
1209                             break;
1210                         }
1211
1212                         default:
1213                             av_log(matroska->ctx, AV_LOG_INFO,
1214                                    "Unknown video track header entry "
1215                                    "0x%x - ignoring\n", id);
1216                             /* pass-through */
1217
1218                         case EBML_ID_VOID:
1219                             res = ebml_read_skip(matroska);
1220                             break;
1221                     }
1222
1223                     if (matroska->level_up) {
1224                         matroska->level_up--;
1225                         break;
1226                     }
1227                 }
1228                 break;
1229             }
1230
1231             /* tracktype specific stuff for audio */
1232             case MATROSKA_ID_TRACKAUDIO: {
1233                 MatroskaAudioTrack *audiotrack;
1234                 if (!track->type)
1235                     track->type = MATROSKA_TRACK_TYPE_AUDIO;
1236                 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1237                     av_log(matroska->ctx, AV_LOG_INFO,
1238                            "audio data in non-audio track - ignoring\n");
1239                     res = AVERROR_INVALIDDATA;
1240                     break;
1241                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1242                     break;
1243                 audiotrack = (MatroskaAudioTrack *)track;
1244                 audiotrack->channels = 1;
1245                 audiotrack->samplerate = 8000;
1246
1247                 while (res == 0) {
1248                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1249                         res = AVERROR_IO;
1250                         break;
1251                     } else if (matroska->level_up > 0) {
1252                         matroska->level_up--;
1253                         break;
1254                     }
1255
1256                     switch (id) {
1257                         /* samplerate */
1258                         case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1259                             double num;
1260                             if ((res = ebml_read_float(matroska, &id,
1261                                                        &num)) < 0)
1262                                 break;
1263                             audiotrack->internal_samplerate =
1264                             audiotrack->samplerate = num;
1265                             break;
1266                         }
1267
1268                         case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1269                             double num;
1270                             if ((res = ebml_read_float(matroska, &id,
1271                                                        &num)) < 0)
1272                                 break;
1273                             audiotrack->samplerate = num;
1274                             break;
1275                         }
1276
1277                             /* bitdepth */
1278                         case MATROSKA_ID_AUDIOBITDEPTH: {
1279                             uint64_t num;
1280                             if ((res = ebml_read_uint(matroska, &id,
1281                                                       &num)) < 0)
1282                                 break;
1283                             audiotrack->bitdepth = num;
1284                             break;
1285                         }
1286
1287                             /* channels */
1288                         case MATROSKA_ID_AUDIOCHANNELS: {
1289                             uint64_t num;
1290                             if ((res = ebml_read_uint(matroska, &id,
1291                                                       &num)) < 0)
1292                                 break;
1293                             audiotrack->channels = num;
1294                             break;
1295                         }
1296
1297                         default:
1298                             av_log(matroska->ctx, AV_LOG_INFO,
1299                                    "Unknown audio track header entry "
1300                                    "0x%x - ignoring\n", id);
1301                             /* pass-through */
1302
1303                         case EBML_ID_VOID:
1304                             res = ebml_read_skip(matroska);
1305                             break;
1306                     }
1307
1308                     if (matroska->level_up) {
1309                         matroska->level_up--;
1310                         break;
1311                     }
1312                 }
1313                 break;
1314             }
1315
1316                 /* codec identifier */
1317             case MATROSKA_ID_CODECID: {
1318                 char *text;
1319                 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1320                     break;
1321                 track->codec_id = text;
1322                 break;
1323             }
1324
1325                 /* codec private data */
1326             case MATROSKA_ID_CODECPRIVATE: {
1327                 uint8_t *data;
1328                 int size;
1329                 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1330                     break;
1331                 track->codec_priv = data;
1332                 track->codec_priv_size = size;
1333                 break;
1334             }
1335
1336                 /* name of the codec */
1337             case MATROSKA_ID_CODECNAME: {
1338                 char *text;
1339                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1340                     break;
1341                 track->codec_name = text;
1342                 break;
1343             }
1344
1345                 /* name of this track */
1346             case MATROSKA_ID_TRACKNAME: {
1347                 char *text;
1348                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1349                     break;
1350                 track->name = text;
1351                 break;
1352             }
1353
1354                 /* language (matters for audio/subtitles, mostly) */
1355             case MATROSKA_ID_TRACKLANGUAGE: {
1356                 char *text;
1357                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1358                     break;
1359                 track->language = text;
1360                 break;
1361             }
1362
1363                 /* whether this is actually used */
1364             case MATROSKA_ID_TRACKFLAGENABLED: {
1365                 uint64_t num;
1366                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1367                     break;
1368                 if (num)
1369                     track->flags |= MATROSKA_TRACK_ENABLED;
1370                 else
1371                     track->flags &= ~MATROSKA_TRACK_ENABLED;
1372                 break;
1373             }
1374
1375                 /* whether it's the default for this track type */
1376             case MATROSKA_ID_TRACKFLAGDEFAULT: {
1377                 uint64_t num;
1378                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1379                     break;
1380                 if (num)
1381                     track->flags |= MATROSKA_TRACK_DEFAULT;
1382                 else
1383                     track->flags &= ~MATROSKA_TRACK_DEFAULT;
1384                 break;
1385             }
1386
1387                 /* lacing (like MPEG, where blocks don't end/start on frame
1388                  * boundaries) */
1389             case MATROSKA_ID_TRACKFLAGLACING: {
1390                 uint64_t num;
1391                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1392                     break;
1393                 if (num)
1394                     track->flags |= MATROSKA_TRACK_LACING;
1395                 else
1396                     track->flags &= ~MATROSKA_TRACK_LACING;
1397                 break;
1398             }
1399
1400                 /* default length (in time) of one data block in this track */
1401             case MATROSKA_ID_TRACKDEFAULTDURATION: {
1402                 uint64_t num;
1403                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1404                     break;
1405                 track->default_duration = num / matroska->time_scale;
1406                 break;
1407             }
1408
1409             default:
1410                 av_log(matroska->ctx, AV_LOG_INFO,
1411                        "Unknown track header entry 0x%x - ignoring\n", id);
1412                 /* pass-through */
1413
1414             case EBML_ID_VOID:
1415             /* we ignore these because they're nothing useful. */
1416             case MATROSKA_ID_CODECINFOURL:
1417             case MATROSKA_ID_CODECDOWNLOADURL:
1418             case MATROSKA_ID_TRACKMINCACHE:
1419             case MATROSKA_ID_TRACKMAXCACHE:
1420                 res = ebml_read_skip(matroska);
1421                 break;
1422         }
1423
1424         if (matroska->level_up) {
1425             matroska->level_up--;
1426             break;
1427         }
1428     }
1429
1430     return res;
1431 }
1432
1433 static int
1434 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1435 {
1436     int res = 0;
1437     uint32_t id;
1438
1439     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1440
1441     while (res == 0) {
1442         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1443             res = AVERROR_IO;
1444             break;
1445         } else if (matroska->level_up) {
1446             matroska->level_up--;
1447             break;
1448         }
1449
1450         switch (id) {
1451             /* one track within the "all-tracks" header */
1452             case MATROSKA_ID_TRACKENTRY:
1453                 res = matroska_add_stream(matroska);
1454                 break;
1455
1456             default:
1457                 av_log(matroska->ctx, AV_LOG_INFO,
1458                        "Unknown entry 0x%x in track header\n", id);
1459                 /* fall-through */
1460
1461             case EBML_ID_VOID:
1462                 res = ebml_read_skip(matroska);
1463                 break;
1464         }
1465
1466         if (matroska->level_up) {
1467             matroska->level_up--;
1468             break;
1469         }
1470     }
1471
1472     return res;
1473 }
1474
1475 static int
1476 matroska_parse_index (MatroskaDemuxContext *matroska)
1477 {
1478     int res = 0;
1479     uint32_t id;
1480     MatroskaDemuxIndex idx;
1481
1482     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1483
1484     while (res == 0) {
1485         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1486             res = AVERROR_IO;
1487             break;
1488         } else if (matroska->level_up) {
1489             matroska->level_up--;
1490             break;
1491         }
1492
1493         switch (id) {
1494             /* one single index entry ('point') */
1495             case MATROSKA_ID_POINTENTRY:
1496                 if ((res = ebml_read_master(matroska, &id)) < 0)
1497                     break;
1498
1499                 /* in the end, we hope to fill one entry with a
1500                  * timestamp, a file position and a tracknum */
1501                 idx.pos   = (uint64_t) -1;
1502                 idx.time  = (uint64_t) -1;
1503                 idx.track = (uint16_t) -1;
1504
1505                 while (res == 0) {
1506                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1507                         res = AVERROR_IO;
1508                         break;
1509                     } else if (matroska->level_up) {
1510                         matroska->level_up--;
1511                         break;
1512                     }
1513
1514                     switch (id) {
1515                         /* one single index entry ('point') */
1516                         case MATROSKA_ID_CUETIME: {
1517                             uint64_t time;
1518                             if ((res = ebml_read_uint(matroska, &id,
1519                                                       &time)) < 0)
1520                                 break;
1521                             idx.time = time * matroska->time_scale;
1522                             break;
1523                         }
1524
1525                         /* position in the file + track to which it
1526                          * belongs */
1527                         case MATROSKA_ID_CUETRACKPOSITION:
1528                             if ((res = ebml_read_master(matroska, &id)) < 0)
1529                                 break;
1530
1531                             while (res == 0) {
1532                                 if (!(id = ebml_peek_id (matroska,
1533                                                     &matroska->level_up))) {
1534                                     res = AVERROR_IO;
1535                                     break;
1536                                 } else if (matroska->level_up) {
1537                                     matroska->level_up--;
1538                                     break;
1539                                 }
1540
1541                                 switch (id) {
1542                                     /* track number */
1543                                     case MATROSKA_ID_CUETRACK: {
1544                                         uint64_t num;
1545                                         if ((res = ebml_read_uint(matroska,
1546                                                           &id, &num)) < 0)
1547                                             break;
1548                                         idx.track = num;
1549                                         break;
1550                                     }
1551
1552                                         /* position in file */
1553                                     case MATROSKA_ID_CUECLUSTERPOSITION: {
1554                                         uint64_t num;
1555                                         if ((res = ebml_read_uint(matroska,
1556                                                           &id, &num)) < 0)
1557                                             break;
1558                                         idx.pos = num+matroska->segment_start;
1559                                         break;
1560                                     }
1561
1562                                     default:
1563                                         av_log(matroska->ctx, AV_LOG_INFO,
1564                                                "Unknown entry 0x%x in "
1565                                                "CuesTrackPositions\n", id);
1566                                         /* fall-through */
1567
1568                                     case EBML_ID_VOID:
1569                                         res = ebml_read_skip(matroska);
1570                                         break;
1571                                 }
1572
1573                                 if (matroska->level_up) {
1574                                     matroska->level_up--;
1575                                     break;
1576                                 }
1577                             }
1578
1579                             break;
1580
1581                         default:
1582                             av_log(matroska->ctx, AV_LOG_INFO,
1583                                    "Unknown entry 0x%x in cuespoint "
1584                                    "index\n", id);
1585                             /* fall-through */
1586
1587                         case EBML_ID_VOID:
1588                             res = ebml_read_skip(matroska);
1589                             break;
1590                     }
1591
1592                     if (matroska->level_up) {
1593                         matroska->level_up--;
1594                         break;
1595                     }
1596                 }
1597
1598                 /* so let's see if we got what we wanted */
1599                 if (idx.pos   != (uint64_t) -1 &&
1600                     idx.time  != (uint64_t) -1 &&
1601                     idx.track != (uint16_t) -1) {
1602                     if (matroska->num_indexes % 32 == 0) {
1603                         /* re-allocate bigger index */
1604                         matroska->index =
1605                             av_realloc(matroska->index,
1606                                        (matroska->num_indexes + 32) *
1607                                        sizeof(MatroskaDemuxIndex));
1608                     }
1609                     matroska->index[matroska->num_indexes] = idx;
1610                     matroska->num_indexes++;
1611                 }
1612                 break;
1613
1614             default:
1615                 av_log(matroska->ctx, AV_LOG_INFO,
1616                        "Unknown entry 0x%x in cues header\n", id);
1617                 /* fall-through */
1618
1619             case EBML_ID_VOID:
1620                 res = ebml_read_skip(matroska);
1621                 break;
1622         }
1623
1624         if (matroska->level_up) {
1625             matroska->level_up--;
1626             break;
1627         }
1628     }
1629
1630     return res;
1631 }
1632
1633 static int
1634 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1635 {
1636     int res = 0;
1637     uint32_t id;
1638
1639     while (res == 0) {
1640         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1641             res = AVERROR_IO;
1642             break;
1643         } else if (matroska->level_up) {
1644             matroska->level_up--;
1645             break;
1646         }
1647
1648         switch (id) {
1649             /* Hm, this is unsupported... */
1650             default:
1651                 av_log(matroska->ctx, AV_LOG_INFO,
1652                        "Unknown entry 0x%x in metadata header\n", id);
1653                 /* fall-through */
1654
1655             case EBML_ID_VOID:
1656                 res = ebml_read_skip(matroska);
1657                 break;
1658         }
1659
1660         if (matroska->level_up) {
1661             matroska->level_up--;
1662             break;
1663         }
1664     }
1665
1666     return res;
1667 }
1668
1669 static int
1670 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1671 {
1672     int res = 0;
1673     uint32_t id;
1674
1675     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1676
1677     while (res == 0) {
1678         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1679             res = AVERROR_IO;
1680             break;
1681         } else if (matroska->level_up) {
1682             matroska->level_up--;
1683             break;
1684         }
1685
1686         switch (id) {
1687             case MATROSKA_ID_SEEKENTRY: {
1688                 uint32_t seek_id = 0, peek_id_cache = 0;
1689                 uint64_t seek_pos = (uint64_t) -1, t;
1690
1691                 if ((res = ebml_read_master(matroska, &id)) < 0)
1692                     break;
1693
1694                 while (res == 0) {
1695                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1696                         res = AVERROR_IO;
1697                         break;
1698                     } else if (matroska->level_up) {
1699                         matroska->level_up--;
1700                         break;
1701                     }
1702
1703                     switch (id) {
1704                         case MATROSKA_ID_SEEKID:
1705                             res = ebml_read_uint(matroska, &id, &t);
1706                             seek_id = t;
1707                             break;
1708
1709                         case MATROSKA_ID_SEEKPOSITION:
1710                             res = ebml_read_uint(matroska, &id, &seek_pos);
1711                             break;
1712
1713                         default:
1714                             av_log(matroska->ctx, AV_LOG_INFO,
1715                                    "Unknown seekhead ID 0x%x\n", id);
1716                             /* fall-through */
1717
1718                         case EBML_ID_VOID:
1719                             res = ebml_read_skip(matroska);
1720                             break;
1721                     }
1722
1723                     if (matroska->level_up) {
1724                         matroska->level_up--;
1725                         break;
1726                     }
1727                 }
1728
1729                 if (!seek_id || seek_pos == (uint64_t) -1) {
1730                     av_log(matroska->ctx, AV_LOG_INFO,
1731                            "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1732                            seek_id, seek_pos);
1733                     break;
1734                 }
1735
1736                 switch (seek_id) {
1737                     case MATROSKA_ID_CUES:
1738                     case MATROSKA_ID_TAGS: {
1739                         uint32_t level_up = matroska->level_up;
1740                         offset_t before_pos;
1741                         uint64_t length;
1742                         MatroskaLevel level;
1743
1744                         /* remember the peeked ID and the current position */
1745                         peek_id_cache = matroska->peek_id;
1746                         before_pos = url_ftell(&matroska->ctx->pb);
1747
1748                         /* seek */
1749                         if ((res = ebml_read_seek(matroska, seek_pos +
1750                                                matroska->segment_start)) < 0)
1751                             return res;
1752
1753                         /* we don't want to lose our seekhead level, so we add
1754                          * a dummy. This is a crude hack. */
1755                         if (matroska->num_levels == EBML_MAX_DEPTH) {
1756                             av_log(matroska->ctx, AV_LOG_INFO,
1757                                    "Max EBML element depth (%d) reached, "
1758                                    "cannot parse further.\n", EBML_MAX_DEPTH);
1759                             return AVERROR_UNKNOWN;
1760                         }
1761
1762                         level.start = 0;
1763                         level.length = (uint64_t)-1;
1764                         matroska->levels[matroska->num_levels] = level;
1765                         matroska->num_levels++;
1766
1767                         /* check ID */
1768                         if (!(id = ebml_peek_id (matroska,
1769                                                  &matroska->level_up)))
1770                             goto finish;
1771                         if (id != seek_id) {
1772                             av_log(matroska->ctx, AV_LOG_INFO,
1773                                    "We looked for ID=0x%x but got "
1774                                    "ID=0x%x (pos=%"PRIu64")",
1775                                    seek_id, id, seek_pos +
1776                                    matroska->segment_start);
1777                             goto finish;
1778                         }
1779
1780                         /* read master + parse */
1781                         if ((res = ebml_read_master(matroska, &id)) < 0)
1782                             goto finish;
1783                         switch (id) {
1784                             case MATROSKA_ID_CUES:
1785                                 if (!(res = matroska_parse_index(matroska)) ||
1786                                     url_feof(&matroska->ctx->pb)) {
1787                                     matroska->index_parsed = 1;
1788                                     res = 0;
1789                                 }
1790                                 break;
1791                             case MATROSKA_ID_TAGS:
1792                                 if (!(res = matroska_parse_metadata(matroska)) ||
1793                                    url_feof(&matroska->ctx->pb)) {
1794                                     matroska->metadata_parsed = 1;
1795                                     res = 0;
1796                                 }
1797                                 break;
1798                         }
1799
1800                     finish:
1801                         /* remove dummy level */
1802                         while (matroska->num_levels) {
1803                             matroska->num_levels--;
1804                             length =
1805                                 matroska->levels[matroska->num_levels].length;
1806                             if (length == (uint64_t)-1)
1807                                 break;
1808                         }
1809
1810                         /* seek back */
1811                         if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1812                             return res;
1813                         matroska->peek_id = peek_id_cache;
1814                         matroska->level_up = level_up;
1815                         break;
1816                     }
1817
1818                     default:
1819                         av_log(matroska->ctx, AV_LOG_INFO,
1820                                "Ignoring seekhead entry for ID=0x%x\n",
1821                                seek_id);
1822                         break;
1823                 }
1824
1825                 break;
1826             }
1827
1828             default:
1829                 av_log(matroska->ctx, AV_LOG_INFO,
1830                        "Unknown seekhead ID 0x%x\n", id);
1831                 /* fall-through */
1832
1833             case EBML_ID_VOID:
1834                 res = ebml_read_skip(matroska);
1835                 break;
1836         }
1837
1838         if (matroska->level_up) {
1839             matroska->level_up--;
1840             break;
1841         }
1842     }
1843
1844     return res;
1845 }
1846
1847 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
1848
1849 static int
1850 matroska_aac_profile (char *codec_id)
1851 {
1852     static const char *aac_profiles[] = {
1853         "MAIN", "LC", "SSR"
1854     };
1855     int profile;
1856
1857     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1858         if (strstr(codec_id, aac_profiles[profile]))
1859             break;
1860     return profile + 1;
1861 }
1862
1863 static int
1864 matroska_aac_sri (int samplerate)
1865 {
1866     static const int aac_sample_rates[] = {
1867         96000, 88200, 64000, 48000, 44100, 32000,
1868         24000, 22050, 16000, 12000, 11025,  8000,
1869     };
1870     int sri;
1871
1872     for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
1873         if (aac_sample_rates[sri] == samplerate)
1874             break;
1875     return sri;
1876 }
1877
1878 static int
1879 matroska_read_header (AVFormatContext    *s,
1880                       AVFormatParameters *ap)
1881 {
1882     MatroskaDemuxContext *matroska = s->priv_data;
1883     char *doctype;
1884     int version, last_level, res = 0;
1885     uint32_t id;
1886
1887     matroska->ctx = s;
1888
1889     /* First read the EBML header. */
1890     doctype = NULL;
1891     if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
1892         return res;
1893     if ((doctype == NULL) || strcmp(doctype, "matroska")) {
1894         av_log(matroska->ctx, AV_LOG_ERROR,
1895                "Wrong EBML doctype ('%s' != 'matroska').\n",
1896                doctype ? doctype : "(none)");
1897         if (doctype)
1898             av_free(doctype);
1899         return AVERROR_NOFMT;
1900     }
1901     av_free(doctype);
1902     if (version > 2) {
1903         av_log(matroska->ctx, AV_LOG_ERROR,
1904                "Matroska demuxer version 2 too old for file version %d\n",
1905                version);
1906         return AVERROR_NOFMT;
1907     }
1908
1909     /* The next thing is a segment. */
1910     while (1) {
1911         if (!(id = ebml_peek_id(matroska, &last_level)))
1912             return AVERROR_IO;
1913         if (id == MATROSKA_ID_SEGMENT)
1914             break;
1915
1916         /* oi! */
1917         av_log(matroska->ctx, AV_LOG_INFO,
1918                "Expected a Segment ID (0x%x), but received 0x%x!\n",
1919                MATROSKA_ID_SEGMENT, id);
1920         if ((res = ebml_read_skip(matroska)) < 0)
1921             return res;
1922     }
1923
1924     /* We now have a Matroska segment.
1925      * Seeks are from the beginning of the segment,
1926      * after the segment ID/length. */
1927     if ((res = ebml_read_master(matroska, &id)) < 0)
1928         return res;
1929     matroska->segment_start = url_ftell(&s->pb);
1930
1931     matroska->time_scale = 1000000;
1932     /* we've found our segment, start reading the different contents in here */
1933     while (res == 0) {
1934         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1935             res = AVERROR_IO;
1936             break;
1937         } else if (matroska->level_up) {
1938             matroska->level_up--;
1939             break;
1940         }
1941
1942         switch (id) {
1943             /* stream info */
1944             case MATROSKA_ID_INFO: {
1945                 if ((res = ebml_read_master(matroska, &id)) < 0)
1946                     break;
1947                 res = matroska_parse_info(matroska);
1948                 break;
1949             }
1950
1951             /* track info headers */
1952             case MATROSKA_ID_TRACKS: {
1953                 if ((res = ebml_read_master(matroska, &id)) < 0)
1954                     break;
1955                 res = matroska_parse_tracks(matroska);
1956                 break;
1957             }
1958
1959             /* stream index */
1960             case MATROSKA_ID_CUES: {
1961                 if (!matroska->index_parsed) {
1962                     if ((res = ebml_read_master(matroska, &id)) < 0)
1963                         break;
1964                     res = matroska_parse_index(matroska);
1965                 } else
1966                     res = ebml_read_skip(matroska);
1967                 break;
1968             }
1969
1970             /* metadata */
1971             case MATROSKA_ID_TAGS: {
1972                 if (!matroska->metadata_parsed) {
1973                     if ((res = ebml_read_master(matroska, &id)) < 0)
1974                         break;
1975                     res = matroska_parse_metadata(matroska);
1976                 } else
1977                     res = ebml_read_skip(matroska);
1978                 break;
1979             }
1980
1981             /* file index (if seekable, seek to Cues/Tags to parse it) */
1982             case MATROSKA_ID_SEEKHEAD: {
1983                 if ((res = ebml_read_master(matroska, &id)) < 0)
1984                     break;
1985                 res = matroska_parse_seekhead(matroska);
1986                 break;
1987             }
1988
1989             case MATROSKA_ID_CLUSTER: {
1990                 /* Do not read the master - this will be done in the next
1991                  * call to matroska_read_packet. */
1992                 res = 1;
1993                 break;
1994             }
1995
1996             default:
1997                 av_log(matroska->ctx, AV_LOG_INFO,
1998                        "Unknown matroska file header ID 0x%x\n", id);
1999             /* fall-through */
2000
2001             case EBML_ID_VOID:
2002                 res = ebml_read_skip(matroska);
2003                 break;
2004         }
2005
2006         if (matroska->level_up) {
2007             matroska->level_up--;
2008             break;
2009         }
2010     }
2011
2012     /* Have we found a cluster? */
2013     if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2014         int i, j;
2015         MatroskaTrack *track;
2016         AVStream *st;
2017
2018         for (i = 0; i < matroska->num_tracks; i++) {
2019             enum CodecID codec_id = CODEC_ID_NONE;
2020             uint8_t *extradata = NULL;
2021             int extradata_size = 0;
2022             int extradata_offset = 0;
2023             track = matroska->tracks[i];
2024
2025             /* libavformat does not really support subtitles.
2026              * Also apply some sanity checks. */
2027             if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2028                 (track->codec_id == NULL))
2029                 continue;
2030
2031             for(j=0; ff_mkv_codec_tags[j].str; j++){
2032                 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2033                             strlen(ff_mkv_codec_tags[j].str))){
2034                     codec_id= ff_mkv_codec_tags[j].id;
2035                     break;
2036                 }
2037             }
2038
2039             /* Set the FourCC from the CodecID. */
2040             /* This is the MS compatibility mode which stores a
2041              * BITMAPINFOHEADER in the CodecPrivate. */
2042             if (!strcmp(track->codec_id,
2043                         MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2044                 (track->codec_priv_size >= 40) &&
2045                 (track->codec_priv != NULL)) {
2046                 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2047
2048                 /* Offset of biCompression. Stored in LE. */
2049                 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2050                 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2051
2052             }
2053
2054             /* This is the MS compatibility mode which stores a
2055              * WAVEFORMATEX in the CodecPrivate. */
2056             else if (!strcmp(track->codec_id,
2057                              MATROSKA_CODEC_ID_AUDIO_ACM) &&
2058                 (track->codec_priv_size >= 18) &&
2059                 (track->codec_priv != NULL)) {
2060                 uint16_t tag;
2061
2062                 /* Offset of wFormatTag. Stored in LE. */
2063                 tag = AV_RL16(track->codec_priv);
2064                 codec_id = codec_get_id(codec_wav_tags, tag);
2065
2066             }
2067
2068             else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2069                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2070                 int profile = matroska_aac_profile(track->codec_id);
2071                 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2072                 extradata = av_malloc(5);
2073                 if (extradata == NULL)
2074                     return AVERROR_NOMEM;
2075                 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2076                 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2077                 if (strstr(track->codec_id, "SBR")) {
2078                     sri = matroska_aac_sri(audiotrack->samplerate);
2079                     extradata[2] = 0x56;
2080                     extradata[3] = 0xE5;
2081                     extradata[4] = 0x80 | (sri<<3);
2082                     extradata_size = 5;
2083                 } else {
2084                     extradata_size = 2;
2085                 }
2086                 track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2087             }
2088
2089             else if (codec_id == CODEC_ID_TTA) {
2090                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2091                 ByteIOContext b;
2092                 extradata_size = 30;
2093                 extradata = av_mallocz(extradata_size);
2094                 if (extradata == NULL)
2095                     return AVERROR_NOMEM;
2096                 init_put_byte(&b, extradata, extradata_size, 1,
2097                               NULL, NULL, NULL, NULL);
2098                 put_buffer(&b, (uint8_t *) "TTA1", 4);
2099                 put_le16(&b, 1);
2100                 put_le16(&b, audiotrack->channels);
2101                 put_le16(&b, audiotrack->bitdepth);
2102                 put_le32(&b, audiotrack->samplerate);
2103                 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2104             }
2105
2106             else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2107                      codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2108                 extradata_offset = 26;
2109                 track->codec_priv_size -= extradata_offset;
2110                 track->flags |= MATROSKA_TRACK_REAL_V;
2111             }
2112
2113             else if (codec_id == CODEC_ID_RA_144) {
2114                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2115                 audiotrack->samplerate = 8000;
2116                 audiotrack->channels = 1;
2117             }
2118
2119             else if (codec_id == CODEC_ID_RA_288 ||
2120                      codec_id == CODEC_ID_COOK ||
2121                      codec_id == CODEC_ID_ATRAC3) {
2122                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2123                 ByteIOContext b;
2124
2125                 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2126                               NULL, NULL, NULL, NULL);
2127                 url_fskip(&b, 24);
2128                 audiotrack->coded_framesize = get_be32(&b);
2129                 url_fskip(&b, 12);
2130                 audiotrack->sub_packet_h    = get_be16(&b);
2131                 audiotrack->frame_size      = get_be16(&b);
2132                 audiotrack->sub_packet_size = get_be16(&b);
2133                 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2134                 if (codec_id == CODEC_ID_RA_288) {
2135                     audiotrack->block_align = audiotrack->coded_framesize;
2136                     track->codec_priv_size = 0;
2137                 } else {
2138                     audiotrack->block_align = audiotrack->sub_packet_size;
2139                     extradata_offset = 78;
2140                     track->codec_priv_size -= extradata_offset;
2141                 }
2142             }
2143
2144             if (codec_id == CODEC_ID_NONE) {
2145                 av_log(matroska->ctx, AV_LOG_INFO,
2146                        "Unknown/unsupported CodecID %s.\n",
2147                        track->codec_id);
2148             }
2149
2150             track->stream_index = matroska->num_streams;
2151
2152             matroska->num_streams++;
2153             st = av_new_stream(s, track->stream_index);
2154             if (st == NULL)
2155                 return AVERROR_NOMEM;
2156             av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2157
2158             st->codec->codec_id = codec_id;
2159             st->start_time = 0;
2160
2161             if (track->default_duration)
2162                 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2163                           track->default_duration, 1000, 30000);
2164
2165             if(extradata){
2166                 st->codec->extradata = extradata;
2167                 st->codec->extradata_size = extradata_size;
2168             } else if(track->codec_priv && track->codec_priv_size > 0){
2169                 st->codec->extradata = av_malloc(track->codec_priv_size);
2170                 if(st->codec->extradata == NULL)
2171                     return AVERROR_NOMEM;
2172                 st->codec->extradata_size = track->codec_priv_size;
2173                 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2174                        track->codec_priv_size);
2175             }
2176
2177             if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2178                 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2179
2180                 st->codec->codec_type = CODEC_TYPE_VIDEO;
2181                 st->codec->codec_tag = videotrack->fourcc;
2182                 st->codec->width = videotrack->pixel_width;
2183                 st->codec->height = videotrack->pixel_height;
2184                 if (videotrack->display_width == 0)
2185                     videotrack->display_width= videotrack->pixel_width;
2186                 if (videotrack->display_height == 0)
2187                     videotrack->display_height= videotrack->pixel_height;
2188                 av_reduce(&st->codec->sample_aspect_ratio.num,
2189                           &st->codec->sample_aspect_ratio.den,
2190                           st->codec->height * videotrack->display_width,
2191                           st->codec-> width * videotrack->display_height,
2192                           255);
2193                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2194             } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2195                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2196
2197                 st->codec->codec_type = CODEC_TYPE_AUDIO;
2198                 st->codec->sample_rate = audiotrack->samplerate;
2199                 st->codec->channels = audiotrack->channels;
2200                 st->codec->block_align = audiotrack->block_align;
2201             } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2202                 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2203             }
2204
2205             /* What do we do with private data? E.g. for Vorbis. */
2206         }
2207         res = 0;
2208     }
2209
2210     if (matroska->index_parsed) {
2211         int i, track, stream;
2212         for (i=0; i<matroska->num_indexes; i++) {
2213             MatroskaDemuxIndex *idx = &matroska->index[i];
2214             track = matroska_find_track_by_num(matroska, idx->track);
2215             stream = matroska->tracks[track]->stream_index;
2216             av_add_index_entry(matroska->ctx->streams[stream],
2217                                idx->pos, idx->time/matroska->time_scale,
2218                                0, 0, AVINDEX_KEYFRAME);
2219         }
2220     }
2221
2222     return res;
2223 }
2224
2225 static inline int
2226 rv_offset(uint8_t *data, int slice, int slices)
2227 {
2228     return AV_RL32(data+8*slice+4) + 8*slices;
2229 }
2230
2231 static int
2232 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2233                      int64_t pos, uint64_t cluster_time, uint64_t duration,
2234                      int is_keyframe, int is_bframe)
2235 {
2236     int res = 0;
2237     int track;
2238     AVStream *st;
2239     AVPacket *pkt;
2240     uint8_t *origdata = data;
2241     int16_t block_time;
2242     uint32_t *lace_size = NULL;
2243     int n, flags, laces = 0;
2244     uint64_t num;
2245
2246     /* first byte(s): tracknum */
2247     if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2248         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2249         av_free(origdata);
2250         return res;
2251     }
2252     data += n;
2253     size -= n;
2254
2255     /* fetch track from num */
2256     track = matroska_find_track_by_num(matroska, num);
2257     if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2258         av_log(matroska->ctx, AV_LOG_INFO,
2259                "Invalid stream %d or size %u\n", track, size);
2260         av_free(origdata);
2261         return res;
2262     }
2263     st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2264     if (st->discard >= AVDISCARD_ALL) {
2265         av_free(origdata);
2266         return res;
2267     }
2268     if (duration == AV_NOPTS_VALUE)
2269         duration = matroska->tracks[track]->default_duration;
2270
2271     /* block_time (relative to cluster time) */
2272     block_time = AV_RB16(data);
2273     data += 2;
2274     size -= 2;
2275     flags = *data;
2276     data += 1;
2277     size -= 1;
2278     if (is_keyframe == -1)
2279         is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2280
2281     if (matroska->skip_to_keyframe) {
2282         if (!is_keyframe || st != matroska->skip_to_stream)
2283             return res;
2284         matroska->skip_to_keyframe = 0;
2285     }
2286
2287     switch ((flags & 0x06) >> 1) {
2288         case 0x0: /* no lacing */
2289             laces = 1;
2290             lace_size = av_mallocz(sizeof(int));
2291             lace_size[0] = size;
2292             break;
2293
2294         case 0x1: /* xiph lacing */
2295         case 0x2: /* fixed-size lacing */
2296         case 0x3: /* EBML lacing */
2297             if (size == 0) {
2298                 res = -1;
2299                 break;
2300             }
2301             laces = (*data) + 1;
2302             data += 1;
2303             size -= 1;
2304             lace_size = av_mallocz(laces * sizeof(int));
2305
2306             switch ((flags & 0x06) >> 1) {
2307                 case 0x1: /* xiph lacing */ {
2308                     uint8_t temp;
2309                     uint32_t total = 0;
2310                     for (n = 0; res == 0 && n < laces - 1; n++) {
2311                         while (1) {
2312                             if (size == 0) {
2313                                 res = -1;
2314                                 break;
2315                             }
2316                             temp = *data;
2317                             lace_size[n] += temp;
2318                             data += 1;
2319                             size -= 1;
2320                             if (temp != 0xff)
2321                                 break;
2322                         }
2323                         total += lace_size[n];
2324                     }
2325                     lace_size[n] = size - total;
2326                     break;
2327                 }
2328
2329                 case 0x2: /* fixed-size lacing */
2330                     for (n = 0; n < laces; n++)
2331                         lace_size[n] = size / laces;
2332                     break;
2333
2334                 case 0x3: /* EBML lacing */ {
2335                     uint32_t total;
2336                     n = matroska_ebmlnum_uint(data, size, &num);
2337                     if (n < 0) {
2338                         av_log(matroska->ctx, AV_LOG_INFO,
2339                                "EBML block data error\n");
2340                         break;
2341                     }
2342                     data += n;
2343                     size -= n;
2344                     total = lace_size[0] = num;
2345                     for (n = 1; res == 0 && n < laces - 1; n++) {
2346                         int64_t snum;
2347                         int r;
2348                         r = matroska_ebmlnum_sint (data, size, &snum);
2349                         if (r < 0) {
2350                             av_log(matroska->ctx, AV_LOG_INFO,
2351                                    "EBML block data error\n");
2352                             break;
2353                         }
2354                         data += r;
2355                         size -= r;
2356                         lace_size[n] = lace_size[n - 1] + snum;
2357                         total += lace_size[n];
2358                     }
2359                     lace_size[n] = size - total;
2360                     break;
2361                 }
2362             }
2363             break;
2364     }
2365
2366     if (res == 0) {
2367         int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2368         uint64_t timecode = AV_NOPTS_VALUE;
2369
2370         if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
2371             timecode = cluster_time + block_time;
2372
2373         for (n = 0; n < laces; n++) {
2374             int slice, slices = 1;
2375
2376             if (real_v) {
2377                 slices = *data++ + 1;
2378                 lace_size[n]--;
2379             }
2380
2381             for (slice=0; slice<slices; slice++) {
2382                 int slice_size, slice_offset = 0;
2383                 if (real_v)
2384                     slice_offset = rv_offset(data, slice, slices);
2385                 if (slice+1 == slices)
2386                     slice_size = lace_size[n] - slice_offset;
2387                 else
2388                     slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2389
2390                 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2391                     st->codec->codec_id == CODEC_ID_COOK ||
2392                     st->codec->codec_id == CODEC_ID_ATRAC3) {
2393                     MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2394                     int a = st->codec->block_align;
2395                     int sps = audiotrack->sub_packet_size;
2396                     int cfs = audiotrack->coded_framesize;
2397                     int h = audiotrack->sub_packet_h;
2398                     int y = audiotrack->sub_packet_cnt;
2399                     int w = audiotrack->frame_size;
2400                     int x;
2401
2402                     if (!audiotrack->pkt_cnt) {
2403                         if (st->codec->codec_id == CODEC_ID_RA_288)
2404                             for (x=0; x<h/2; x++)
2405                                 memcpy(audiotrack->buf+x*2*w+y*cfs,
2406                                        data+x*cfs, cfs);
2407                         else
2408                             for (x=0; x<w/sps; x++)
2409                                 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2410
2411                         if (++audiotrack->sub_packet_cnt >= h) {
2412                             audiotrack->sub_packet_cnt = 0;
2413                             audiotrack->pkt_cnt = h*w / a;
2414                         }
2415                     }
2416                     while (audiotrack->pkt_cnt) {
2417                         pkt = av_mallocz(sizeof(AVPacket));
2418                         av_new_packet(pkt, a);
2419                         memcpy(pkt->data, audiotrack->buf
2420                                + a * (h*w / a - audiotrack->pkt_cnt--), a);
2421                         pkt->pos = pos;
2422                         pkt->stream_index = matroska->tracks[track]->stream_index;
2423                         matroska_queue_packet(matroska, pkt);
2424                     }
2425                 } else {
2426                     pkt = av_mallocz(sizeof(AVPacket));
2427                     /* XXX: prevent data copy... */
2428                     if (av_new_packet(pkt, slice_size) < 0) {
2429                         res = AVERROR_NOMEM;
2430                         n = laces-1;
2431                         break;
2432                     }
2433                     memcpy (pkt->data, data+slice_offset, slice_size);
2434
2435                     if (n == 0)
2436                         pkt->flags = is_keyframe;
2437                     pkt->stream_index = matroska->tracks[track]->stream_index;
2438
2439                     pkt->pts = timecode;
2440                     pkt->pos = pos;
2441                     pkt->duration = duration;
2442
2443                     matroska_queue_packet(matroska, pkt);
2444                 }
2445
2446                 if (timecode != AV_NOPTS_VALUE)
2447                     timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2448             }
2449             data += lace_size[n];
2450         }
2451     }
2452
2453     av_free(lace_size);
2454     av_free(origdata);
2455     return res;
2456 }
2457
2458 static int
2459 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2460                            uint64_t              cluster_time)
2461 {
2462     int res = 0;
2463     uint32_t id;
2464     int is_bframe = 0;
2465     int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2466     uint64_t duration = AV_NOPTS_VALUE;
2467     uint8_t *data;
2468     int size = 0;
2469     int64_t pos = 0;
2470
2471     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2472
2473     while (res == 0) {
2474         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2475             res = AVERROR_IO;
2476             break;
2477         } else if (matroska->level_up) {
2478             matroska->level_up--;
2479             break;
2480         }
2481
2482         switch (id) {
2483             /* one block inside the group. Note, block parsing is one
2484              * of the harder things, so this code is a bit complicated.
2485              * See http://www.matroska.org/ for documentation. */
2486             case MATROSKA_ID_BLOCK: {
2487                 pos = url_ftell(&matroska->ctx->pb);
2488                 res = ebml_read_binary(matroska, &id, &data, &size);
2489                 break;
2490             }
2491
2492             case MATROSKA_ID_BLOCKDURATION: {
2493                 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2494                     break;
2495                 duration /= matroska->time_scale;
2496                 break;
2497             }
2498
2499             case MATROSKA_ID_BLOCKREFERENCE: {
2500                 int64_t num;
2501                 /* We've found a reference, so not even the first frame in
2502                  * the lace is a key frame. */
2503                 is_keyframe = 0;
2504                 if (last_num_packets != matroska->num_packets)
2505                     matroska->packets[last_num_packets]->flags = 0;
2506                 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2507                     break;
2508                 if (num > 0)
2509                     is_bframe = 1;
2510                 break;
2511             }
2512
2513             default:
2514                 av_log(matroska->ctx, AV_LOG_INFO,
2515                        "Unknown entry 0x%x in blockgroup data\n", id);
2516                 /* fall-through */
2517
2518             case EBML_ID_VOID:
2519                 res = ebml_read_skip(matroska);
2520                 break;
2521         }
2522
2523         if (matroska->level_up) {
2524             matroska->level_up--;
2525             break;
2526         }
2527     }
2528
2529     if (res)
2530         return res;
2531
2532     if (size > 0)
2533         res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2534                                    duration, is_keyframe, is_bframe);
2535
2536     return res;
2537 }
2538
2539 static int
2540 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2541 {
2542     int res = 0;
2543     uint32_t id;
2544     uint64_t cluster_time = 0;
2545     uint8_t *data;
2546     int64_t pos;
2547     int size;
2548
2549     av_log(matroska->ctx, AV_LOG_DEBUG,
2550            "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2551
2552     while (res == 0) {
2553         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2554             res = AVERROR_IO;
2555             break;
2556         } else if (matroska->level_up) {
2557             matroska->level_up--;
2558             break;
2559         }
2560
2561         switch (id) {
2562             /* cluster timecode */
2563             case MATROSKA_ID_CLUSTERTIMECODE: {
2564                 uint64_t num;
2565                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2566                     break;
2567                 cluster_time = num;
2568                 break;
2569             }
2570
2571                 /* a group of blocks inside a cluster */
2572             case MATROSKA_ID_BLOCKGROUP:
2573                 if ((res = ebml_read_master(matroska, &id)) < 0)
2574                     break;
2575                 res = matroska_parse_blockgroup(matroska, cluster_time);
2576                 break;
2577
2578             case MATROSKA_ID_SIMPLEBLOCK:
2579                 pos = url_ftell(&matroska->ctx->pb);
2580                 res = ebml_read_binary(matroska, &id, &data, &size);
2581                 if (res == 0)
2582                     res = matroska_parse_block(matroska, data, size, pos,
2583                                                cluster_time, AV_NOPTS_VALUE,
2584                                                -1, 0);
2585                 break;
2586
2587             default:
2588                 av_log(matroska->ctx, AV_LOG_INFO,
2589                        "Unknown entry 0x%x in cluster data\n", id);
2590                 /* fall-through */
2591
2592             case EBML_ID_VOID:
2593                 res = ebml_read_skip(matroska);
2594                 break;
2595         }
2596
2597         if (matroska->level_up) {
2598             matroska->level_up--;
2599             break;
2600         }
2601     }
2602
2603     return res;
2604 }
2605
2606 static int
2607 matroska_read_packet (AVFormatContext *s,
2608                       AVPacket        *pkt)
2609 {
2610     MatroskaDemuxContext *matroska = s->priv_data;
2611     int res;
2612     uint32_t id;
2613
2614     /* Read stream until we have a packet queued. */
2615     while (matroska_deliver_packet(matroska, pkt)) {
2616
2617         /* Have we already reached the end? */
2618         if (matroska->done)
2619             return AVERROR_IO;
2620
2621         res = 0;
2622         while (res == 0) {
2623             if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2624                 return AVERROR_IO;
2625             } else if (matroska->level_up) {
2626                 matroska->level_up--;
2627                 break;
2628             }
2629
2630             switch (id) {
2631                 case MATROSKA_ID_CLUSTER:
2632                     if ((res = ebml_read_master(matroska, &id)) < 0)
2633                         break;
2634                     if ((res = matroska_parse_cluster(matroska)) == 0)
2635                         res = 1; /* Parsed one cluster, let's get out. */
2636                     break;
2637
2638                 default:
2639                 case EBML_ID_VOID:
2640                     res = ebml_read_skip(matroska);
2641                     break;
2642             }
2643
2644             if (matroska->level_up) {
2645                 matroska->level_up--;
2646                 break;
2647             }
2648         }
2649
2650         if (res == -1)
2651             matroska->done = 1;
2652     }
2653
2654     return 0;
2655 }
2656
2657 static int
2658 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2659                     int flags)
2660 {
2661     MatroskaDemuxContext *matroska = s->priv_data;
2662     AVStream *st = s->streams[stream_index];
2663     int index;
2664
2665     /* find index entry */
2666     index = av_index_search_timestamp(st, timestamp, flags);
2667     if (index < 0)
2668         return 0;
2669
2670     /* do the seek */
2671     url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2672     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2673     matroska->skip_to_stream = st;
2674     matroska->num_packets = 0;
2675     matroska->peek_id = 0;
2676     return 0;
2677 }
2678
2679 static int
2680 matroska_read_close (AVFormatContext *s)
2681 {
2682     MatroskaDemuxContext *matroska = s->priv_data;
2683     int n = 0;
2684
2685     av_free(matroska->writing_app);
2686     av_free(matroska->muxing_app);
2687     av_free(matroska->index);
2688
2689     if (matroska->packets != NULL) {
2690         for (n = 0; n < matroska->num_packets; n++) {
2691             av_free_packet(matroska->packets[n]);
2692             av_free(matroska->packets[n]);
2693         }
2694         av_free(matroska->packets);
2695     }
2696
2697     for (n = 0; n < matroska->num_tracks; n++) {
2698         MatroskaTrack *track = matroska->tracks[n];
2699         av_free(track->codec_id);
2700         av_free(track->codec_name);
2701         av_free(track->codec_priv);
2702         av_free(track->name);
2703         av_free(track->language);
2704
2705         if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2706             MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2707             av_free(audiotrack->buf);
2708         }
2709
2710         av_free(track);
2711     }
2712
2713     return 0;
2714 }
2715
2716 AVInputFormat matroska_demuxer = {
2717     "matroska",
2718     "Matroska file format",
2719     sizeof(MatroskaDemuxContext),
2720     matroska_probe,
2721     matroska_read_header,
2722     matroska_read_packet,
2723     matroska_read_close,
2724     matroska_read_seek,
2725 };