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