]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
cosmetics: use one type per field in every structs
[ffmpeg] / 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 matroska.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 ((p->buf[0] << 24 | p->buf[1] << 16 |
864          p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
865         return 0;
866
867     /* length of header */
868     total = p->buf[4];
869     while (size <= 8 && !(total & len_mask)) {
870         size++;
871         len_mask >>= 1;
872     }
873     if (size > 8)
874       return 0;
875     total &= (len_mask - 1);
876     while (n < size)
877         total = (total << 8) | p->buf[4 + n++];
878
879     /* does the probe data contain the whole header? */
880     if (p->buf_size < 4 + size + total)
881       return 0;
882
883     /* the header must contain the document type 'matroska'. For now,
884      * we don't parse the whole header but simply check for the
885      * availability of that array of characters inside the header.
886      * Not fully fool-proof, but good enough. */
887     for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
888         if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
889             return AVPROBE_SCORE_MAX;
890
891     return 0;
892 }
893
894 /*
895  * From here on, it's all XML-style DTD stuff... Needs no comments.
896  */
897
898 static int
899 matroska_parse_info (MatroskaDemuxContext *matroska)
900 {
901     int res = 0;
902     uint32_t id;
903
904     av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
905
906     while (res == 0) {
907         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
908             res = AVERROR_IO;
909             break;
910         } else if (matroska->level_up) {
911             matroska->level_up--;
912             break;
913         }
914
915         switch (id) {
916             /* cluster timecode */
917             case MATROSKA_ID_TIMECODESCALE: {
918                 uint64_t num;
919                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
920                     break;
921                 matroska->time_scale = num;
922                 break;
923             }
924
925             case MATROSKA_ID_DURATION: {
926                 double num;
927                 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
928                     break;
929                 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
930                 break;
931             }
932
933             case MATROSKA_ID_TITLE: {
934                 char *text;
935                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
936                     break;
937                 strncpy(matroska->ctx->title, text,
938                         sizeof(matroska->ctx->title)-1);
939                 av_free(text);
940                 break;
941             }
942
943             case MATROSKA_ID_WRITINGAPP: {
944                 char *text;
945                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
946                     break;
947                 matroska->writing_app = text;
948                 break;
949             }
950
951             case MATROSKA_ID_MUXINGAPP: {
952                 char *text;
953                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
954                     break;
955                 matroska->muxing_app = text;
956                 break;
957             }
958
959             case MATROSKA_ID_DATEUTC: {
960                 int64_t time;
961                 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
962                     break;
963                 matroska->created = time;
964                 break;
965             }
966
967             default:
968                 av_log(matroska->ctx, AV_LOG_INFO,
969                        "Unknown entry 0x%x in info header\n", id);
970                 /* fall-through */
971
972             case EBML_ID_VOID:
973                 res = ebml_read_skip(matroska);
974                 break;
975         }
976
977         if (matroska->level_up) {
978             matroska->level_up--;
979             break;
980         }
981     }
982
983     return res;
984 }
985
986 static int
987 matroska_add_stream (MatroskaDemuxContext *matroska)
988 {
989     int res = 0;
990     uint32_t id;
991     MatroskaTrack *track;
992
993     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
994
995     /* Allocate a generic track. As soon as we know its type we'll realloc. */
996     track = av_mallocz(MAX_TRACK_SIZE);
997     matroska->num_tracks++;
998
999     /* start with the master */
1000     if ((res = ebml_read_master(matroska, &id)) < 0)
1001         return res;
1002
1003     /* try reading the trackentry headers */
1004     while (res == 0) {
1005         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1006             res = AVERROR_IO;
1007             break;
1008         } else if (matroska->level_up > 0) {
1009             matroska->level_up--;
1010             break;
1011         }
1012
1013         switch (id) {
1014             /* track number (unique stream ID) */
1015             case MATROSKA_ID_TRACKNUMBER: {
1016                 uint64_t num;
1017                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1018                     break;
1019                 track->num = num;
1020                 break;
1021             }
1022
1023             /* track UID (unique identifier) */
1024             case MATROSKA_ID_TRACKUID: {
1025                 uint64_t num;
1026                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1027                     break;
1028                 track->uid = num;
1029                 break;
1030             }
1031
1032             /* track type (video, audio, combined, subtitle, etc.) */
1033             case MATROSKA_ID_TRACKTYPE: {
1034                 uint64_t num;
1035                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1036                     break;
1037                 if (track->type && track->type != num) {
1038                     av_log(matroska->ctx, AV_LOG_INFO,
1039                            "More than one tracktype in an entry - skip\n");
1040                     break;
1041                 }
1042                 track->type = num;
1043
1044                 switch (track->type) {
1045                     case MATROSKA_TRACK_TYPE_VIDEO:
1046                     case MATROSKA_TRACK_TYPE_AUDIO:
1047                     case MATROSKA_TRACK_TYPE_SUBTITLE:
1048                         break;
1049                     case MATROSKA_TRACK_TYPE_COMPLEX:
1050                     case MATROSKA_TRACK_TYPE_LOGO:
1051                     case MATROSKA_TRACK_TYPE_CONTROL:
1052                     default:
1053                         av_log(matroska->ctx, AV_LOG_INFO,
1054                                "Unknown or unsupported track type 0x%x\n",
1055                                track->type);
1056                         track->type = 0;
1057                         break;
1058                 }
1059                 matroska->tracks[matroska->num_tracks - 1] = track;
1060                 break;
1061             }
1062
1063             /* tracktype specific stuff for video */
1064             case MATROSKA_ID_TRACKVIDEO: {
1065                 MatroskaVideoTrack *videotrack;
1066                 if (!track->type)
1067                     track->type = MATROSKA_TRACK_TYPE_VIDEO;
1068                 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1069                     av_log(matroska->ctx, AV_LOG_INFO,
1070                            "video data in non-video track - ignoring\n");
1071                     res = AVERROR_INVALIDDATA;
1072                     break;
1073                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1074                     break;
1075                 videotrack = (MatroskaVideoTrack *)track;
1076
1077                 while (res == 0) {
1078                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1079                         res = AVERROR_IO;
1080                         break;
1081                     } else if (matroska->level_up > 0) {
1082                         matroska->level_up--;
1083                         break;
1084                     }
1085
1086                     switch (id) {
1087                         /* fixme, this should be one-up, but I get it here */
1088                         case MATROSKA_ID_TRACKDEFAULTDURATION: {
1089                             uint64_t num;
1090                             if ((res = ebml_read_uint (matroska, &id,
1091                                                        &num)) < 0)
1092                                 break;
1093                             track->default_duration = num/matroska->time_scale;
1094                             break;
1095                         }
1096
1097                         /* video framerate */
1098                         case MATROSKA_ID_VIDEOFRAMERATE: {
1099                             double num;
1100                             if ((res = ebml_read_float(matroska, &id,
1101                                                        &num)) < 0)
1102                                 break;
1103                             track->default_duration = 1000000000/(matroska->time_scale*num);
1104                             break;
1105                         }
1106
1107                         /* width of the size to display the video at */
1108                         case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1109                             uint64_t num;
1110                             if ((res = ebml_read_uint(matroska, &id,
1111                                                       &num)) < 0)
1112                                 break;
1113                             videotrack->display_width = num;
1114                             break;
1115                         }
1116
1117                         /* height of the size to display the video at */
1118                         case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1119                             uint64_t num;
1120                             if ((res = ebml_read_uint(matroska, &id,
1121                                                       &num)) < 0)
1122                                 break;
1123                             videotrack->display_height = num;
1124                             break;
1125                         }
1126
1127                         /* width of the video in the file */
1128                         case MATROSKA_ID_VIDEOPIXELWIDTH: {
1129                             uint64_t num;
1130                             if ((res = ebml_read_uint(matroska, &id,
1131                                                       &num)) < 0)
1132                                 break;
1133                             videotrack->pixel_width = num;
1134                             break;
1135                         }
1136
1137                         /* height of the video in the file */
1138                         case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1139                             uint64_t num;
1140                             if ((res = ebml_read_uint(matroska, &id,
1141                                                       &num)) < 0)
1142                                 break;
1143                             videotrack->pixel_height = num;
1144                             break;
1145                         }
1146
1147                         /* whether the video is interlaced */
1148                         case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1149                             uint64_t num;
1150                             if ((res = ebml_read_uint(matroska, &id,
1151                                                       &num)) < 0)
1152                                 break;
1153                             if (num)
1154                                 track->flags |=
1155                                     MATROSKA_VIDEOTRACK_INTERLACED;
1156                             else
1157                                 track->flags &=
1158                                     ~MATROSKA_VIDEOTRACK_INTERLACED;
1159                             break;
1160                         }
1161
1162                         /* stereo mode (whether the video has two streams,
1163                          * where one is for the left eye and the other for
1164                          * the right eye, which creates a 3D-like
1165                          * effect) */
1166                         case MATROSKA_ID_VIDEOSTEREOMODE: {
1167                             uint64_t num;
1168                             if ((res = ebml_read_uint(matroska, &id,
1169                                                       &num)) < 0)
1170                                 break;
1171                             if (num != MATROSKA_EYE_MODE_MONO &&
1172                                 num != MATROSKA_EYE_MODE_LEFT &&
1173                                 num != MATROSKA_EYE_MODE_RIGHT &&
1174                                 num != MATROSKA_EYE_MODE_BOTH) {
1175                                 av_log(matroska->ctx, AV_LOG_INFO,
1176                                        "Ignoring unknown eye mode 0x%x\n",
1177                                        (uint32_t) num);
1178                                 break;
1179                             }
1180                             videotrack->eye_mode = num;
1181                             break;
1182                         }
1183
1184                         /* aspect ratio behaviour */
1185                         case MATROSKA_ID_VIDEOASPECTRATIO: {
1186                             uint64_t num;
1187                             if ((res = ebml_read_uint(matroska, &id,
1188                                                       &num)) < 0)
1189                                 break;
1190                             if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1191                                 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1192                                 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1193                                 av_log(matroska->ctx, AV_LOG_INFO,
1194                                        "Ignoring unknown aspect ratio 0x%x\n",
1195                                        (uint32_t) num);
1196                                 break;
1197                             }
1198                             videotrack->ar_mode = num;
1199                             break;
1200                         }
1201
1202                         /* colourspace (only matters for raw video)
1203                          * fourcc */
1204                         case MATROSKA_ID_VIDEOCOLOURSPACE: {
1205                             uint64_t num;
1206                             if ((res = ebml_read_uint(matroska, &id,
1207                                                       &num)) < 0)
1208                                 break;
1209                             videotrack->fourcc = num;
1210                             break;
1211                         }
1212
1213                         default:
1214                             av_log(matroska->ctx, AV_LOG_INFO,
1215                                    "Unknown video track header entry "
1216                                    "0x%x - ignoring\n", id);
1217                             /* pass-through */
1218
1219                         case EBML_ID_VOID:
1220                             res = ebml_read_skip(matroska);
1221                             break;
1222                     }
1223
1224                     if (matroska->level_up) {
1225                         matroska->level_up--;
1226                         break;
1227                     }
1228                 }
1229                 break;
1230             }
1231
1232             /* tracktype specific stuff for audio */
1233             case MATROSKA_ID_TRACKAUDIO: {
1234                 MatroskaAudioTrack *audiotrack;
1235                 if (!track->type)
1236                     track->type = MATROSKA_TRACK_TYPE_AUDIO;
1237                 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1238                     av_log(matroska->ctx, AV_LOG_INFO,
1239                            "audio data in non-audio track - ignoring\n");
1240                     res = AVERROR_INVALIDDATA;
1241                     break;
1242                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1243                     break;
1244                 audiotrack = (MatroskaAudioTrack *)track;
1245                 audiotrack->channels = 1;
1246                 audiotrack->samplerate = 8000;
1247
1248                 while (res == 0) {
1249                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1250                         res = AVERROR_IO;
1251                         break;
1252                     } else if (matroska->level_up > 0) {
1253                         matroska->level_up--;
1254                         break;
1255                     }
1256
1257                     switch (id) {
1258                         /* samplerate */
1259                         case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1260                             double num;
1261                             if ((res = ebml_read_float(matroska, &id,
1262                                                        &num)) < 0)
1263                                 break;
1264                             audiotrack->internal_samplerate =
1265                             audiotrack->samplerate = num;
1266                             break;
1267                         }
1268
1269                         case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1270                             double num;
1271                             if ((res = ebml_read_float(matroska, &id,
1272                                                        &num)) < 0)
1273                                 break;
1274                             audiotrack->samplerate = num;
1275                             break;
1276                         }
1277
1278                             /* bitdepth */
1279                         case MATROSKA_ID_AUDIOBITDEPTH: {
1280                             uint64_t num;
1281                             if ((res = ebml_read_uint(matroska, &id,
1282                                                       &num)) < 0)
1283                                 break;
1284                             audiotrack->bitdepth = num;
1285                             break;
1286                         }
1287
1288                             /* channels */
1289                         case MATROSKA_ID_AUDIOCHANNELS: {
1290                             uint64_t num;
1291                             if ((res = ebml_read_uint(matroska, &id,
1292                                                       &num)) < 0)
1293                                 break;
1294                             audiotrack->channels = num;
1295                             break;
1296                         }
1297
1298                         default:
1299                             av_log(matroska->ctx, AV_LOG_INFO,
1300                                    "Unknown audio track header entry "
1301                                    "0x%x - ignoring\n", id);
1302                             /* pass-through */
1303
1304                         case EBML_ID_VOID:
1305                             res = ebml_read_skip(matroska);
1306                             break;
1307                     }
1308
1309                     if (matroska->level_up) {
1310                         matroska->level_up--;
1311                         break;
1312                     }
1313                 }
1314                 break;
1315             }
1316
1317                 /* codec identifier */
1318             case MATROSKA_ID_CODECID: {
1319                 char *text;
1320                 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1321                     break;
1322                 track->codec_id = text;
1323                 break;
1324             }
1325
1326                 /* codec private data */
1327             case MATROSKA_ID_CODECPRIVATE: {
1328                 uint8_t *data;
1329                 int size;
1330                 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1331                     break;
1332                 track->codec_priv = data;
1333                 track->codec_priv_size = size;
1334                 break;
1335             }
1336
1337                 /* name of the codec */
1338             case MATROSKA_ID_CODECNAME: {
1339                 char *text;
1340                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1341                     break;
1342                 track->codec_name = text;
1343                 break;
1344             }
1345
1346                 /* name of this track */
1347             case MATROSKA_ID_TRACKNAME: {
1348                 char *text;
1349                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1350                     break;
1351                 track->name = text;
1352                 break;
1353             }
1354
1355                 /* language (matters for audio/subtitles, mostly) */
1356             case MATROSKA_ID_TRACKLANGUAGE: {
1357                 char *text;
1358                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1359                     break;
1360                 track->language = text;
1361                 break;
1362             }
1363
1364                 /* whether this is actually used */
1365             case MATROSKA_ID_TRACKFLAGENABLED: {
1366                 uint64_t num;
1367                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1368                     break;
1369                 if (num)
1370                     track->flags |= MATROSKA_TRACK_ENABLED;
1371                 else
1372                     track->flags &= ~MATROSKA_TRACK_ENABLED;
1373                 break;
1374             }
1375
1376                 /* whether it's the default for this track type */
1377             case MATROSKA_ID_TRACKFLAGDEFAULT: {
1378                 uint64_t num;
1379                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1380                     break;
1381                 if (num)
1382                     track->flags |= MATROSKA_TRACK_DEFAULT;
1383                 else
1384                     track->flags &= ~MATROSKA_TRACK_DEFAULT;
1385                 break;
1386             }
1387
1388                 /* lacing (like MPEG, where blocks don't end/start on frame
1389                  * boundaries) */
1390             case MATROSKA_ID_TRACKFLAGLACING: {
1391                 uint64_t num;
1392                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1393                     break;
1394                 if (num)
1395                     track->flags |= MATROSKA_TRACK_LACING;
1396                 else
1397                     track->flags &= ~MATROSKA_TRACK_LACING;
1398                 break;
1399             }
1400
1401                 /* default length (in time) of one data block in this track */
1402             case MATROSKA_ID_TRACKDEFAULTDURATION: {
1403                 uint64_t num;
1404                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1405                     break;
1406                 track->default_duration = num / matroska->time_scale;
1407                 break;
1408             }
1409
1410             default:
1411                 av_log(matroska->ctx, AV_LOG_INFO,
1412                        "Unknown track header entry 0x%x - ignoring\n", id);
1413                 /* pass-through */
1414
1415             case EBML_ID_VOID:
1416             /* we ignore these because they're nothing useful. */
1417             case MATROSKA_ID_CODECINFOURL:
1418             case MATROSKA_ID_CODECDOWNLOADURL:
1419             case MATROSKA_ID_TRACKMINCACHE:
1420             case MATROSKA_ID_TRACKMAXCACHE:
1421                 res = ebml_read_skip(matroska);
1422                 break;
1423         }
1424
1425         if (matroska->level_up) {
1426             matroska->level_up--;
1427             break;
1428         }
1429     }
1430
1431     return res;
1432 }
1433
1434 static int
1435 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1436 {
1437     int res = 0;
1438     uint32_t id;
1439
1440     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1441
1442     while (res == 0) {
1443         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1444             res = AVERROR_IO;
1445             break;
1446         } else if (matroska->level_up) {
1447             matroska->level_up--;
1448             break;
1449         }
1450
1451         switch (id) {
1452             /* one track within the "all-tracks" header */
1453             case MATROSKA_ID_TRACKENTRY:
1454                 res = matroska_add_stream(matroska);
1455                 break;
1456
1457             default:
1458                 av_log(matroska->ctx, AV_LOG_INFO,
1459                        "Unknown entry 0x%x in track header\n", id);
1460                 /* fall-through */
1461
1462             case EBML_ID_VOID:
1463                 res = ebml_read_skip(matroska);
1464                 break;
1465         }
1466
1467         if (matroska->level_up) {
1468             matroska->level_up--;
1469             break;
1470         }
1471     }
1472
1473     return res;
1474 }
1475
1476 static int
1477 matroska_parse_index (MatroskaDemuxContext *matroska)
1478 {
1479     int res = 0;
1480     uint32_t id;
1481     MatroskaDemuxIndex idx;
1482
1483     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1484
1485     while (res == 0) {
1486         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1487             res = AVERROR_IO;
1488             break;
1489         } else if (matroska->level_up) {
1490             matroska->level_up--;
1491             break;
1492         }
1493
1494         switch (id) {
1495             /* one single index entry ('point') */
1496             case MATROSKA_ID_POINTENTRY:
1497                 if ((res = ebml_read_master(matroska, &id)) < 0)
1498                     break;
1499
1500                 /* in the end, we hope to fill one entry with a
1501                  * timestamp, a file position and a tracknum */
1502                 idx.pos   = (uint64_t) -1;
1503                 idx.time  = (uint64_t) -1;
1504                 idx.track = (uint16_t) -1;
1505
1506                 while (res == 0) {
1507                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1508                         res = AVERROR_IO;
1509                         break;
1510                     } else if (matroska->level_up) {
1511                         matroska->level_up--;
1512                         break;
1513                     }
1514
1515                     switch (id) {
1516                         /* one single index entry ('point') */
1517                         case MATROSKA_ID_CUETIME: {
1518                             uint64_t time;
1519                             if ((res = ebml_read_uint(matroska, &id,
1520                                                       &time)) < 0)
1521                                 break;
1522                             idx.time = time * matroska->time_scale;
1523                             break;
1524                         }
1525
1526                         /* position in the file + track to which it
1527                          * belongs */
1528                         case MATROSKA_ID_CUETRACKPOSITION:
1529                             if ((res = ebml_read_master(matroska, &id)) < 0)
1530                                 break;
1531
1532                             while (res == 0) {
1533                                 if (!(id = ebml_peek_id (matroska,
1534                                                     &matroska->level_up))) {
1535                                     res = AVERROR_IO;
1536                                     break;
1537                                 } else if (matroska->level_up) {
1538                                     matroska->level_up--;
1539                                     break;
1540                                 }
1541
1542                                 switch (id) {
1543                                     /* track number */
1544                                     case MATROSKA_ID_CUETRACK: {
1545                                         uint64_t num;
1546                                         if ((res = ebml_read_uint(matroska,
1547                                                           &id, &num)) < 0)
1548                                             break;
1549                                         idx.track = num;
1550                                         break;
1551                                     }
1552
1553                                         /* position in file */
1554                                     case MATROSKA_ID_CUECLUSTERPOSITION: {
1555                                         uint64_t num;
1556                                         if ((res = ebml_read_uint(matroska,
1557                                                           &id, &num)) < 0)
1558                                             break;
1559                                         idx.pos = num+matroska->segment_start;
1560                                         break;
1561                                     }
1562
1563                                     default:
1564                                         av_log(matroska->ctx, AV_LOG_INFO,
1565                                                "Unknown entry 0x%x in "
1566                                                "CuesTrackPositions\n", id);
1567                                         /* fall-through */
1568
1569                                     case EBML_ID_VOID:
1570                                         res = ebml_read_skip(matroska);
1571                                         break;
1572                                 }
1573
1574                                 if (matroska->level_up) {
1575                                     matroska->level_up--;
1576                                     break;
1577                                 }
1578                             }
1579
1580                             break;
1581
1582                         default:
1583                             av_log(matroska->ctx, AV_LOG_INFO,
1584                                    "Unknown entry 0x%x in cuespoint "
1585                                    "index\n", id);
1586                             /* fall-through */
1587
1588                         case EBML_ID_VOID:
1589                             res = ebml_read_skip(matroska);
1590                             break;
1591                     }
1592
1593                     if (matroska->level_up) {
1594                         matroska->level_up--;
1595                         break;
1596                     }
1597                 }
1598
1599                 /* so let's see if we got what we wanted */
1600                 if (idx.pos   != (uint64_t) -1 &&
1601                     idx.time  != (uint64_t) -1 &&
1602                     idx.track != (uint16_t) -1) {
1603                     if (matroska->num_indexes % 32 == 0) {
1604                         /* re-allocate bigger index */
1605                         matroska->index =
1606                             av_realloc(matroska->index,
1607                                        (matroska->num_indexes + 32) *
1608                                        sizeof(MatroskaDemuxIndex));
1609                     }
1610                     matroska->index[matroska->num_indexes] = idx;
1611                     matroska->num_indexes++;
1612                 }
1613                 break;
1614
1615             default:
1616                 av_log(matroska->ctx, AV_LOG_INFO,
1617                        "Unknown entry 0x%x in cues header\n", id);
1618                 /* fall-through */
1619
1620             case EBML_ID_VOID:
1621                 res = ebml_read_skip(matroska);
1622                 break;
1623         }
1624
1625         if (matroska->level_up) {
1626             matroska->level_up--;
1627             break;
1628         }
1629     }
1630
1631     return res;
1632 }
1633
1634 static int
1635 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1636 {
1637     int res = 0;
1638     uint32_t id;
1639
1640     while (res == 0) {
1641         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1642             res = AVERROR_IO;
1643             break;
1644         } else if (matroska->level_up) {
1645             matroska->level_up--;
1646             break;
1647         }
1648
1649         switch (id) {
1650             /* Hm, this is unsupported... */
1651             default:
1652                 av_log(matroska->ctx, AV_LOG_INFO,
1653                        "Unknown entry 0x%x in metadata header\n", id);
1654                 /* fall-through */
1655
1656             case EBML_ID_VOID:
1657                 res = ebml_read_skip(matroska);
1658                 break;
1659         }
1660
1661         if (matroska->level_up) {
1662             matroska->level_up--;
1663             break;
1664         }
1665     }
1666
1667     return res;
1668 }
1669
1670 static int
1671 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1672 {
1673     int res = 0;
1674     uint32_t id;
1675
1676     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1677
1678     while (res == 0) {
1679         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1680             res = AVERROR_IO;
1681             break;
1682         } else if (matroska->level_up) {
1683             matroska->level_up--;
1684             break;
1685         }
1686
1687         switch (id) {
1688             case MATROSKA_ID_SEEKENTRY: {
1689                 uint32_t seek_id = 0, peek_id_cache = 0;
1690                 uint64_t seek_pos = (uint64_t) -1, t;
1691
1692                 if ((res = ebml_read_master(matroska, &id)) < 0)
1693                     break;
1694
1695                 while (res == 0) {
1696                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1697                         res = AVERROR_IO;
1698                         break;
1699                     } else if (matroska->level_up) {
1700                         matroska->level_up--;
1701                         break;
1702                     }
1703
1704                     switch (id) {
1705                         case MATROSKA_ID_SEEKID:
1706                             res = ebml_read_uint(matroska, &id, &t);
1707                             seek_id = t;
1708                             break;
1709
1710                         case MATROSKA_ID_SEEKPOSITION:
1711                             res = ebml_read_uint(matroska, &id, &seek_pos);
1712                             break;
1713
1714                         default:
1715                             av_log(matroska->ctx, AV_LOG_INFO,
1716                                    "Unknown seekhead ID 0x%x\n", id);
1717                             /* fall-through */
1718
1719                         case EBML_ID_VOID:
1720                             res = ebml_read_skip(matroska);
1721                             break;
1722                     }
1723
1724                     if (matroska->level_up) {
1725                         matroska->level_up--;
1726                         break;
1727                     }
1728                 }
1729
1730                 if (!seek_id || seek_pos == (uint64_t) -1) {
1731                     av_log(matroska->ctx, AV_LOG_INFO,
1732                            "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1733                            seek_id, seek_pos);
1734                     break;
1735                 }
1736
1737                 switch (seek_id) {
1738                     case MATROSKA_ID_CUES:
1739                     case MATROSKA_ID_TAGS: {
1740                         uint32_t level_up = matroska->level_up;
1741                         offset_t before_pos;
1742                         uint64_t length;
1743                         MatroskaLevel level;
1744
1745                         /* remember the peeked ID and the current position */
1746                         peek_id_cache = matroska->peek_id;
1747                         before_pos = url_ftell(&matroska->ctx->pb);
1748
1749                         /* seek */
1750                         if ((res = ebml_read_seek(matroska, seek_pos +
1751                                                matroska->segment_start)) < 0)
1752                             return res;
1753
1754                         /* we don't want to lose our seekhead level, so we add
1755                          * a dummy. This is a crude hack. */
1756                         if (matroska->num_levels == EBML_MAX_DEPTH) {
1757                             av_log(matroska->ctx, AV_LOG_INFO,
1758                                    "Max EBML element depth (%d) reached, "
1759                                    "cannot parse further.\n", EBML_MAX_DEPTH);
1760                             return AVERROR_UNKNOWN;
1761                         }
1762
1763                         level.start = 0;
1764                         level.length = (uint64_t)-1;
1765                         matroska->levels[matroska->num_levels] = level;
1766                         matroska->num_levels++;
1767
1768                         /* check ID */
1769                         if (!(id = ebml_peek_id (matroska,
1770                                                  &matroska->level_up)))
1771                             goto finish;
1772                         if (id != seek_id) {
1773                             av_log(matroska->ctx, AV_LOG_INFO,
1774                                    "We looked for ID=0x%x but got "
1775                                    "ID=0x%x (pos=%"PRIu64")",
1776                                    seek_id, id, seek_pos +
1777                                    matroska->segment_start);
1778                             goto finish;
1779                         }
1780
1781                         /* read master + parse */
1782                         if ((res = ebml_read_master(matroska, &id)) < 0)
1783                             goto finish;
1784                         switch (id) {
1785                             case MATROSKA_ID_CUES:
1786                                 if (!(res = matroska_parse_index(matroska)) ||
1787                                     url_feof(&matroska->ctx->pb)) {
1788                                     matroska->index_parsed = 1;
1789                                     res = 0;
1790                                 }
1791                                 break;
1792                             case MATROSKA_ID_TAGS:
1793                                 if (!(res = matroska_parse_metadata(matroska)) ||
1794                                    url_feof(&matroska->ctx->pb)) {
1795                                     matroska->metadata_parsed = 1;
1796                                     res = 0;
1797                                 }
1798                                 break;
1799                         }
1800
1801                     finish:
1802                         /* remove dummy level */
1803                         while (matroska->num_levels) {
1804                             matroska->num_levels--;
1805                             length =
1806                                 matroska->levels[matroska->num_levels].length;
1807                             if (length == (uint64_t)-1)
1808                                 break;
1809                         }
1810
1811                         /* seek back */
1812                         if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1813                             return res;
1814                         matroska->peek_id = peek_id_cache;
1815                         matroska->level_up = level_up;
1816                         break;
1817                     }
1818
1819                     default:
1820                         av_log(matroska->ctx, AV_LOG_INFO,
1821                                "Ignoring seekhead entry for ID=0x%x\n",
1822                                seek_id);
1823                         break;
1824                 }
1825
1826                 break;
1827             }
1828
1829             default:
1830                 av_log(matroska->ctx, AV_LOG_INFO,
1831                        "Unknown seekhead ID 0x%x\n", id);
1832                 /* fall-through */
1833
1834             case EBML_ID_VOID:
1835                 res = ebml_read_skip(matroska);
1836                 break;
1837         }
1838
1839         if (matroska->level_up) {
1840             matroska->level_up--;
1841             break;
1842         }
1843     }
1844
1845     return res;
1846 }
1847
1848 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
1849
1850 static int
1851 matroska_aac_profile (char *codec_id)
1852 {
1853     static const char *aac_profiles[] = {
1854         "MAIN", "LC", "SSR"
1855     };
1856     int profile;
1857
1858     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1859         if (strstr(codec_id, aac_profiles[profile]))
1860             break;
1861     return profile + 1;
1862 }
1863
1864 static int
1865 matroska_aac_sri (int samplerate)
1866 {
1867     static const int aac_sample_rates[] = {
1868         96000, 88200, 64000, 48000, 44100, 32000,
1869         24000, 22050, 16000, 12000, 11025,  8000,
1870     };
1871     int sri;
1872
1873     for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
1874         if (aac_sample_rates[sri] == samplerate)
1875             break;
1876     return sri;
1877 }
1878
1879 static int
1880 matroska_read_header (AVFormatContext    *s,
1881                       AVFormatParameters *ap)
1882 {
1883     MatroskaDemuxContext *matroska = s->priv_data;
1884     char *doctype;
1885     int version, last_level, res = 0;
1886     uint32_t id;
1887
1888     matroska->ctx = s;
1889
1890     /* First read the EBML header. */
1891     doctype = NULL;
1892     if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
1893         return res;
1894     if ((doctype == NULL) || strcmp(doctype, "matroska")) {
1895         av_log(matroska->ctx, AV_LOG_ERROR,
1896                "Wrong EBML doctype ('%s' != 'matroska').\n",
1897                doctype ? doctype : "(none)");
1898         if (doctype)
1899             av_free(doctype);
1900         return AVERROR_NOFMT;
1901     }
1902     av_free(doctype);
1903     if (version > 2) {
1904         av_log(matroska->ctx, AV_LOG_ERROR,
1905                "Matroska demuxer version 2 too old for file version %d\n",
1906                version);
1907         return AVERROR_NOFMT;
1908     }
1909
1910     /* The next thing is a segment. */
1911     while (1) {
1912         if (!(id = ebml_peek_id(matroska, &last_level)))
1913             return AVERROR_IO;
1914         if (id == MATROSKA_ID_SEGMENT)
1915             break;
1916
1917         /* oi! */
1918         av_log(matroska->ctx, AV_LOG_INFO,
1919                "Expected a Segment ID (0x%x), but received 0x%x!\n",
1920                MATROSKA_ID_SEGMENT, id);
1921         if ((res = ebml_read_skip(matroska)) < 0)
1922             return res;
1923     }
1924
1925     /* We now have a Matroska segment.
1926      * Seeks are from the beginning of the segment,
1927      * after the segment ID/length. */
1928     if ((res = ebml_read_master(matroska, &id)) < 0)
1929         return res;
1930     matroska->segment_start = url_ftell(&s->pb);
1931
1932     matroska->time_scale = 1000000;
1933     /* we've found our segment, start reading the different contents in here */
1934     while (res == 0) {
1935         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1936             res = AVERROR_IO;
1937             break;
1938         } else if (matroska->level_up) {
1939             matroska->level_up--;
1940             break;
1941         }
1942
1943         switch (id) {
1944             /* stream info */
1945             case MATROSKA_ID_INFO: {
1946                 if ((res = ebml_read_master(matroska, &id)) < 0)
1947                     break;
1948                 res = matroska_parse_info(matroska);
1949                 break;
1950             }
1951
1952             /* track info headers */
1953             case MATROSKA_ID_TRACKS: {
1954                 if ((res = ebml_read_master(matroska, &id)) < 0)
1955                     break;
1956                 res = matroska_parse_tracks(matroska);
1957                 break;
1958             }
1959
1960             /* stream index */
1961             case MATROSKA_ID_CUES: {
1962                 if (!matroska->index_parsed) {
1963                     if ((res = ebml_read_master(matroska, &id)) < 0)
1964                         break;
1965                     res = matroska_parse_index(matroska);
1966                 } else
1967                     res = ebml_read_skip(matroska);
1968                 break;
1969             }
1970
1971             /* metadata */
1972             case MATROSKA_ID_TAGS: {
1973                 if (!matroska->metadata_parsed) {
1974                     if ((res = ebml_read_master(matroska, &id)) < 0)
1975                         break;
1976                     res = matroska_parse_metadata(matroska);
1977                 } else
1978                     res = ebml_read_skip(matroska);
1979                 break;
1980             }
1981
1982             /* file index (if seekable, seek to Cues/Tags to parse it) */
1983             case MATROSKA_ID_SEEKHEAD: {
1984                 if ((res = ebml_read_master(matroska, &id)) < 0)
1985                     break;
1986                 res = matroska_parse_seekhead(matroska);
1987                 break;
1988             }
1989
1990             case MATROSKA_ID_CLUSTER: {
1991                 /* Do not read the master - this will be done in the next
1992                  * call to matroska_read_packet. */
1993                 res = 1;
1994                 break;
1995             }
1996
1997             default:
1998                 av_log(matroska->ctx, AV_LOG_INFO,
1999                        "Unknown matroska file header ID 0x%x\n", id);
2000             /* fall-through */
2001
2002             case EBML_ID_VOID:
2003                 res = ebml_read_skip(matroska);
2004                 break;
2005         }
2006
2007         if (matroska->level_up) {
2008             matroska->level_up--;
2009             break;
2010         }
2011     }
2012
2013     /* Have we found a cluster? */
2014     if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2015         int i, j;
2016         MatroskaTrack *track;
2017         AVStream *st;
2018
2019         for (i = 0; i < matroska->num_tracks; i++) {
2020             enum CodecID codec_id = CODEC_ID_NONE;
2021             uint8_t *extradata = NULL;
2022             int extradata_size = 0;
2023             int extradata_offset = 0;
2024             track = matroska->tracks[i];
2025
2026             /* libavformat does not really support subtitles.
2027              * Also apply some sanity checks. */
2028             if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2029                 (track->codec_id == NULL))
2030                 continue;
2031
2032             for(j=0; ff_mkv_codec_tags[j].str; j++){
2033                 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2034                             strlen(ff_mkv_codec_tags[j].str))){
2035                     codec_id= ff_mkv_codec_tags[j].id;
2036                     break;
2037                 }
2038             }
2039
2040             /* Set the FourCC from the CodecID. */
2041             /* This is the MS compatibility mode which stores a
2042              * BITMAPINFOHEADER in the CodecPrivate. */
2043             if (!strcmp(track->codec_id,
2044                         MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2045                 (track->codec_priv_size >= 40) &&
2046                 (track->codec_priv != NULL)) {
2047                 unsigned char *p;
2048
2049                 /* Offset of biCompression. Stored in LE. */
2050                 p = (unsigned char *)track->codec_priv + 16;
2051                 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2052                                  (p[2] << 16) | (p[1] << 8) | p[0];
2053                 codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);
2054
2055             }
2056
2057             /* This is the MS compatibility mode which stores a
2058              * WAVEFORMATEX in the CodecPrivate. */
2059             else if (!strcmp(track->codec_id,
2060                              MATROSKA_CODEC_ID_AUDIO_ACM) &&
2061                 (track->codec_priv_size >= 18) &&
2062                 (track->codec_priv != NULL)) {
2063                 unsigned char *p;
2064                 uint16_t tag;
2065
2066                 /* Offset of wFormatTag. Stored in LE. */
2067                 p = (unsigned char *)track->codec_priv;
2068                 tag = (p[1] << 8) | p[0];
2069                 codec_id = codec_get_id(codec_wav_tags, tag);
2070
2071             }
2072
2073             else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2074                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2075                 int profile = matroska_aac_profile(track->codec_id);
2076                 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2077                 extradata = av_malloc(5);
2078                 if (extradata == NULL)
2079                     return AVERROR_NOMEM;
2080                 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2081                 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2082                 if (strstr(track->codec_id, "SBR")) {
2083                     sri = matroska_aac_sri(audiotrack->samplerate);
2084                     extradata[2] = 0x56;
2085                     extradata[3] = 0xE5;
2086                     extradata[4] = 0x80 | (sri<<3);
2087                     extradata_size = 5;
2088                 } else {
2089                     extradata_size = 2;
2090                 }
2091                 track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2092             }
2093
2094             else if (codec_id == CODEC_ID_TTA) {
2095                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2096                 ByteIOContext b;
2097                 extradata_size = 30;
2098                 extradata = av_mallocz(extradata_size);
2099                 if (extradata == NULL)
2100                     return AVERROR_NOMEM;
2101                 init_put_byte(&b, extradata, extradata_size, 1,
2102                               NULL, NULL, NULL, NULL);
2103                 put_buffer(&b, (uint8_t *) "TTA1", 4);
2104                 put_le16(&b, 1);
2105                 put_le16(&b, audiotrack->channels);
2106                 put_le16(&b, audiotrack->bitdepth);
2107                 put_le32(&b, audiotrack->samplerate);
2108                 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2109             }
2110
2111             else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2112                      codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2113                 extradata_offset = 26;
2114                 track->codec_priv_size -= extradata_offset;
2115                 track->flags |= MATROSKA_TRACK_REAL_V;
2116             }
2117
2118             else if (codec_id == CODEC_ID_RA_144) {
2119                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2120                 audiotrack->samplerate = 8000;
2121                 audiotrack->channels = 1;
2122             }
2123
2124             else if (codec_id == CODEC_ID_RA_288 ||
2125                      codec_id == CODEC_ID_COOK ||
2126                      codec_id == CODEC_ID_ATRAC3) {
2127                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2128                 ByteIOContext b;
2129
2130                 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2131                               NULL, NULL, NULL, NULL);
2132                 url_fskip(&b, 24);
2133                 audiotrack->coded_framesize = get_be32(&b);
2134                 url_fskip(&b, 12);
2135                 audiotrack->sub_packet_h    = get_be16(&b);
2136                 audiotrack->frame_size      = get_be16(&b);
2137                 audiotrack->sub_packet_size = get_be16(&b);
2138                 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2139                 if (codec_id == CODEC_ID_RA_288) {
2140                     audiotrack->block_align = audiotrack->coded_framesize;
2141                     track->codec_priv_size = 0;
2142                 } else {
2143                     audiotrack->block_align = audiotrack->sub_packet_size;
2144                     extradata_offset = 78;
2145                     track->codec_priv_size -= extradata_offset;
2146                 }
2147             }
2148
2149             if (codec_id == CODEC_ID_NONE) {
2150                 av_log(matroska->ctx, AV_LOG_INFO,
2151                        "Unknown/unsupported CodecID %s.\n",
2152                        track->codec_id);
2153             }
2154
2155             track->stream_index = matroska->num_streams;
2156
2157             matroska->num_streams++;
2158             st = av_new_stream(s, track->stream_index);
2159             if (st == NULL)
2160                 return AVERROR_NOMEM;
2161             av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2162
2163             st->codec->codec_id = codec_id;
2164             st->start_time = 0;
2165
2166             if (track->default_duration)
2167                 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2168                           track->default_duration, 1000, 30000);
2169
2170             if(extradata){
2171                 st->codec->extradata = extradata;
2172                 st->codec->extradata_size = extradata_size;
2173             } else if(track->codec_priv && track->codec_priv_size > 0){
2174                 st->codec->extradata = av_malloc(track->codec_priv_size);
2175                 if(st->codec->extradata == NULL)
2176                     return AVERROR_NOMEM;
2177                 st->codec->extradata_size = track->codec_priv_size;
2178                 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2179                        track->codec_priv_size);
2180             }
2181
2182             if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2183                 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2184
2185                 st->codec->codec_type = CODEC_TYPE_VIDEO;
2186                 st->codec->codec_tag = videotrack->fourcc;
2187                 st->codec->width = videotrack->pixel_width;
2188                 st->codec->height = videotrack->pixel_height;
2189                 if (videotrack->display_width == 0)
2190                     videotrack->display_width= videotrack->pixel_width;
2191                 if (videotrack->display_height == 0)
2192                     videotrack->display_height= videotrack->pixel_height;
2193                 av_reduce(&st->codec->sample_aspect_ratio.num,
2194                           &st->codec->sample_aspect_ratio.den,
2195                           st->codec->height * videotrack->display_width,
2196                           st->codec-> width * videotrack->display_height,
2197                           255);
2198                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2199             } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2200                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2201
2202                 st->codec->codec_type = CODEC_TYPE_AUDIO;
2203                 st->codec->sample_rate = audiotrack->samplerate;
2204                 st->codec->channels = audiotrack->channels;
2205                 st->codec->block_align = audiotrack->block_align;
2206             } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2207                 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2208             }
2209
2210             /* What do we do with private data? E.g. for Vorbis. */
2211         }
2212         res = 0;
2213     }
2214
2215     if (matroska->index_parsed) {
2216         int i, track, stream;
2217         for (i=0; i<matroska->num_indexes; i++) {
2218             MatroskaDemuxIndex *idx = &matroska->index[i];
2219             track = matroska_find_track_by_num(matroska, idx->track);
2220             stream = matroska->tracks[track]->stream_index;
2221             av_add_index_entry(matroska->ctx->streams[stream],
2222                                idx->pos, idx->time/matroska->time_scale,
2223                                0, 0, AVINDEX_KEYFRAME);
2224         }
2225     }
2226
2227     return res;
2228 }
2229
2230 static inline int
2231 rv_offset(uint8_t *data, int slice, int slices)
2232 {
2233     return AV_RL32(data+8*slice+4) + 8*slices;
2234 }
2235
2236 static int
2237 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2238                      int64_t pos, uint64_t cluster_time, uint64_t duration,
2239                      int is_keyframe, int is_bframe)
2240 {
2241     int res = 0;
2242     int track;
2243     AVStream *st;
2244     AVPacket *pkt;
2245     uint8_t *origdata = data;
2246     int16_t block_time;
2247     uint32_t *lace_size = NULL;
2248     int n, flags, laces = 0;
2249     uint64_t num;
2250
2251     /* first byte(s): tracknum */
2252     if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2253         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2254         av_free(origdata);
2255         return res;
2256     }
2257     data += n;
2258     size -= n;
2259
2260     /* fetch track from num */
2261     track = matroska_find_track_by_num(matroska, num);
2262     if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2263         av_log(matroska->ctx, AV_LOG_INFO,
2264                "Invalid stream %d or size %u\n", track, size);
2265         av_free(origdata);
2266         return res;
2267     }
2268     st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2269     if (st->discard >= AVDISCARD_ALL) {
2270         av_free(origdata);
2271         return res;
2272     }
2273     if (duration == AV_NOPTS_VALUE)
2274         duration = matroska->tracks[track]->default_duration;
2275
2276     /* block_time (relative to cluster time) */
2277     block_time = (data[0] << 8) | data[1];
2278     data += 2;
2279     size -= 2;
2280     flags = *data;
2281     data += 1;
2282     size -= 1;
2283     if (is_keyframe == -1)
2284         is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2285
2286     if (matroska->skip_to_keyframe) {
2287         if (!is_keyframe || st != matroska->skip_to_stream)
2288             return res;
2289         matroska->skip_to_keyframe = 0;
2290     }
2291
2292     switch ((flags & 0x06) >> 1) {
2293         case 0x0: /* no lacing */
2294             laces = 1;
2295             lace_size = av_mallocz(sizeof(int));
2296             lace_size[0] = size;
2297             break;
2298
2299         case 0x1: /* xiph lacing */
2300         case 0x2: /* fixed-size lacing */
2301         case 0x3: /* EBML lacing */
2302             if (size == 0) {
2303                 res = -1;
2304                 break;
2305             }
2306             laces = (*data) + 1;
2307             data += 1;
2308             size -= 1;
2309             lace_size = av_mallocz(laces * sizeof(int));
2310
2311             switch ((flags & 0x06) >> 1) {
2312                 case 0x1: /* xiph lacing */ {
2313                     uint8_t temp;
2314                     uint32_t total = 0;
2315                     for (n = 0; res == 0 && n < laces - 1; n++) {
2316                         while (1) {
2317                             if (size == 0) {
2318                                 res = -1;
2319                                 break;
2320                             }
2321                             temp = *data;
2322                             lace_size[n] += temp;
2323                             data += 1;
2324                             size -= 1;
2325                             if (temp != 0xff)
2326                                 break;
2327                         }
2328                         total += lace_size[n];
2329                     }
2330                     lace_size[n] = size - total;
2331                     break;
2332                 }
2333
2334                 case 0x2: /* fixed-size lacing */
2335                     for (n = 0; n < laces; n++)
2336                         lace_size[n] = size / laces;
2337                     break;
2338
2339                 case 0x3: /* EBML lacing */ {
2340                     uint32_t total;
2341                     n = matroska_ebmlnum_uint(data, size, &num);
2342                     if (n < 0) {
2343                         av_log(matroska->ctx, AV_LOG_INFO,
2344                                "EBML block data error\n");
2345                         break;
2346                     }
2347                     data += n;
2348                     size -= n;
2349                     total = lace_size[0] = num;
2350                     for (n = 1; res == 0 && n < laces - 1; n++) {
2351                         int64_t snum;
2352                         int r;
2353                         r = matroska_ebmlnum_sint (data, size, &snum);
2354                         if (r < 0) {
2355                             av_log(matroska->ctx, AV_LOG_INFO,
2356                                    "EBML block data error\n");
2357                             break;
2358                         }
2359                         data += r;
2360                         size -= r;
2361                         lace_size[n] = lace_size[n - 1] + snum;
2362                         total += lace_size[n];
2363                     }
2364                     lace_size[n] = size - total;
2365                     break;
2366                 }
2367             }
2368             break;
2369     }
2370
2371     if (res == 0) {
2372         int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2373         uint64_t timecode = AV_NOPTS_VALUE;
2374
2375         if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
2376             timecode = cluster_time + block_time;
2377
2378         for (n = 0; n < laces; n++) {
2379             int slice, slices = 1;
2380
2381             if (real_v) {
2382                 slices = *data++ + 1;
2383                 lace_size[n]--;
2384             }
2385
2386             for (slice=0; slice<slices; slice++) {
2387                 int slice_size, slice_offset = 0;
2388                 if (real_v)
2389                     slice_offset = rv_offset(data, slice, slices);
2390                 if (slice+1 == slices)
2391                     slice_size = lace_size[n] - slice_offset;
2392                 else
2393                     slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2394
2395                 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2396                     st->codec->codec_id == CODEC_ID_COOK ||
2397                     st->codec->codec_id == CODEC_ID_ATRAC3) {
2398                     MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2399                     int a = st->codec->block_align;
2400                     int sps = audiotrack->sub_packet_size;
2401                     int cfs = audiotrack->coded_framesize;
2402                     int h = audiotrack->sub_packet_h;
2403                     int y = audiotrack->sub_packet_cnt;
2404                     int w = audiotrack->frame_size;
2405                     int x;
2406
2407                     if (!audiotrack->pkt_cnt) {
2408                         if (st->codec->codec_id == CODEC_ID_RA_288)
2409                             for (x=0; x<h/2; x++)
2410                                 memcpy(audiotrack->buf+x*2*w+y*cfs,
2411                                        data+x*cfs, cfs);
2412                         else
2413                             for (x=0; x<w/sps; x++)
2414                                 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2415
2416                         if (++audiotrack->sub_packet_cnt >= h) {
2417                             audiotrack->sub_packet_cnt = 0;
2418                             audiotrack->pkt_cnt = h*w / a;
2419                         }
2420                     }
2421                     while (audiotrack->pkt_cnt) {
2422                         pkt = av_mallocz(sizeof(AVPacket));
2423                         av_new_packet(pkt, a);
2424                         memcpy(pkt->data, audiotrack->buf
2425                                + a * (h*w / a - audiotrack->pkt_cnt--), a);
2426                         pkt->pos = pos;
2427                         pkt->stream_index = matroska->tracks[track]->stream_index;
2428                         matroska_queue_packet(matroska, pkt);
2429                     }
2430                 } else {
2431                     pkt = av_mallocz(sizeof(AVPacket));
2432                     /* XXX: prevent data copy... */
2433                     if (av_new_packet(pkt, slice_size) < 0) {
2434                         res = AVERROR_NOMEM;
2435                         n = laces-1;
2436                         break;
2437                     }
2438                     memcpy (pkt->data, data+slice_offset, slice_size);
2439
2440                     if (n == 0)
2441                         pkt->flags = is_keyframe;
2442                     pkt->stream_index = matroska->tracks[track]->stream_index;
2443
2444                     pkt->pts = timecode;
2445                     pkt->pos = pos;
2446                     pkt->duration = duration;
2447
2448                     matroska_queue_packet(matroska, pkt);
2449                 }
2450
2451                 if (timecode != AV_NOPTS_VALUE)
2452                     timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2453             }
2454             data += lace_size[n];
2455         }
2456     }
2457
2458     av_free(lace_size);
2459     av_free(origdata);
2460     return res;
2461 }
2462
2463 static int
2464 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2465                            uint64_t              cluster_time)
2466 {
2467     int res = 0;
2468     uint32_t id;
2469     int is_bframe = 0;
2470     int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2471     uint64_t duration = AV_NOPTS_VALUE;
2472     uint8_t *data;
2473     int size = 0;
2474     int64_t pos = 0;
2475
2476     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2477
2478     while (res == 0) {
2479         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2480             res = AVERROR_IO;
2481             break;
2482         } else if (matroska->level_up) {
2483             matroska->level_up--;
2484             break;
2485         }
2486
2487         switch (id) {
2488             /* one block inside the group. Note, block parsing is one
2489              * of the harder things, so this code is a bit complicated.
2490              * See http://www.matroska.org/ for documentation. */
2491             case MATROSKA_ID_BLOCK: {
2492                 pos = url_ftell(&matroska->ctx->pb);
2493                 res = ebml_read_binary(matroska, &id, &data, &size);
2494                 break;
2495             }
2496
2497             case MATROSKA_ID_BLOCKDURATION: {
2498                 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2499                     break;
2500                 duration /= matroska->time_scale;
2501                 break;
2502             }
2503
2504             case MATROSKA_ID_BLOCKREFERENCE: {
2505                 int64_t num;
2506                 /* We've found a reference, so not even the first frame in
2507                  * the lace is a key frame. */
2508                 is_keyframe = 0;
2509                 if (last_num_packets != matroska->num_packets)
2510                     matroska->packets[last_num_packets]->flags = 0;
2511                 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2512                     break;
2513                 if (num > 0)
2514                     is_bframe = 1;
2515                 break;
2516             }
2517
2518             default:
2519                 av_log(matroska->ctx, AV_LOG_INFO,
2520                        "Unknown entry 0x%x in blockgroup data\n", id);
2521                 /* fall-through */
2522
2523             case EBML_ID_VOID:
2524                 res = ebml_read_skip(matroska);
2525                 break;
2526         }
2527
2528         if (matroska->level_up) {
2529             matroska->level_up--;
2530             break;
2531         }
2532     }
2533
2534     if (res)
2535         return res;
2536
2537     if (size > 0)
2538         res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2539                                    duration, is_keyframe, is_bframe);
2540
2541     return res;
2542 }
2543
2544 static int
2545 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2546 {
2547     int res = 0;
2548     uint32_t id;
2549     uint64_t cluster_time = 0;
2550     uint8_t *data;
2551     int64_t pos;
2552     int size;
2553
2554     av_log(matroska->ctx, AV_LOG_DEBUG,
2555            "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2556
2557     while (res == 0) {
2558         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2559             res = AVERROR_IO;
2560             break;
2561         } else if (matroska->level_up) {
2562             matroska->level_up--;
2563             break;
2564         }
2565
2566         switch (id) {
2567             /* cluster timecode */
2568             case MATROSKA_ID_CLUSTERTIMECODE: {
2569                 uint64_t num;
2570                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2571                     break;
2572                 cluster_time = num;
2573                 break;
2574             }
2575
2576                 /* a group of blocks inside a cluster */
2577             case MATROSKA_ID_BLOCKGROUP:
2578                 if ((res = ebml_read_master(matroska, &id)) < 0)
2579                     break;
2580                 res = matroska_parse_blockgroup(matroska, cluster_time);
2581                 break;
2582
2583             case MATROSKA_ID_SIMPLEBLOCK:
2584                 pos = url_ftell(&matroska->ctx->pb);
2585                 res = ebml_read_binary(matroska, &id, &data, &size);
2586                 if (res == 0)
2587                     res = matroska_parse_block(matroska, data, size, pos,
2588                                                cluster_time, AV_NOPTS_VALUE,
2589                                                -1, 0);
2590                 break;
2591
2592             default:
2593                 av_log(matroska->ctx, AV_LOG_INFO,
2594                        "Unknown entry 0x%x in cluster data\n", id);
2595                 /* fall-through */
2596
2597             case EBML_ID_VOID:
2598                 res = ebml_read_skip(matroska);
2599                 break;
2600         }
2601
2602         if (matroska->level_up) {
2603             matroska->level_up--;
2604             break;
2605         }
2606     }
2607
2608     return res;
2609 }
2610
2611 static int
2612 matroska_read_packet (AVFormatContext *s,
2613                       AVPacket        *pkt)
2614 {
2615     MatroskaDemuxContext *matroska = s->priv_data;
2616     int res;
2617     uint32_t id;
2618
2619     /* Read stream until we have a packet queued. */
2620     while (matroska_deliver_packet(matroska, pkt)) {
2621
2622         /* Have we already reached the end? */
2623         if (matroska->done)
2624             return AVERROR_IO;
2625
2626         res = 0;
2627         while (res == 0) {
2628             if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2629                 return AVERROR_IO;
2630             } else if (matroska->level_up) {
2631                 matroska->level_up--;
2632                 break;
2633             }
2634
2635             switch (id) {
2636                 case MATROSKA_ID_CLUSTER:
2637                     if ((res = ebml_read_master(matroska, &id)) < 0)
2638                         break;
2639                     if ((res = matroska_parse_cluster(matroska)) == 0)
2640                         res = 1; /* Parsed one cluster, let's get out. */
2641                     break;
2642
2643                 default:
2644                 case EBML_ID_VOID:
2645                     res = ebml_read_skip(matroska);
2646                     break;
2647             }
2648
2649             if (matroska->level_up) {
2650                 matroska->level_up--;
2651                 break;
2652             }
2653         }
2654
2655         if (res == -1)
2656             matroska->done = 1;
2657     }
2658
2659     return 0;
2660 }
2661
2662 static int
2663 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2664                     int flags)
2665 {
2666     MatroskaDemuxContext *matroska = s->priv_data;
2667     AVStream *st = s->streams[stream_index];
2668     int index;
2669
2670     /* find index entry */
2671     index = av_index_search_timestamp(st, timestamp, flags);
2672     if (index < 0)
2673         return 0;
2674
2675     /* do the seek */
2676     url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2677     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2678     matroska->skip_to_stream = st;
2679     matroska->num_packets = 0;
2680     matroska->peek_id = 0;
2681     return 0;
2682 }
2683
2684 static int
2685 matroska_read_close (AVFormatContext *s)
2686 {
2687     MatroskaDemuxContext *matroska = s->priv_data;
2688     int n = 0;
2689
2690     av_free(matroska->writing_app);
2691     av_free(matroska->muxing_app);
2692     av_free(matroska->index);
2693
2694     if (matroska->packets != NULL) {
2695         for (n = 0; n < matroska->num_packets; n++) {
2696             av_free_packet(matroska->packets[n]);
2697             av_free(matroska->packets[n]);
2698         }
2699         av_free(matroska->packets);
2700     }
2701
2702     for (n = 0; n < matroska->num_tracks; n++) {
2703         MatroskaTrack *track = matroska->tracks[n];
2704         av_free(track->codec_id);
2705         av_free(track->codec_name);
2706         av_free(track->codec_priv);
2707         av_free(track->name);
2708         av_free(track->language);
2709
2710         if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2711             MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2712             av_free(audiotrack->buf);
2713         }
2714
2715         av_free(track);
2716     }
2717
2718     return 0;
2719 }
2720
2721 AVInputFormat matroska_demuxer = {
2722     "matroska",
2723     "Matroska file format",
2724     sizeof(MatroskaDemuxContext),
2725     matroska_probe,
2726     matroska_read_header,
2727     matroska_read_packet,
2728     matroska_read_close,
2729     matroska_read_seek,
2730 };