]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
498e3d9e75d4f526c4fe9a992dd5ed4b9c5a2bd9
[ffmpeg] / libavformat / matroskadec.c
1 /*
2  * Matroska file demuxer (no muxer yet)
3  * Copyright (c) 2003-2004 The ffmpeg Project
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file matroskadec.c
24  * Matroska file demuxer
25  * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * Specs available on the matroska project page:
28  * http://www.matroska.org/.
29  */
30
31 #include "avformat.h"
32 /* For codec_get_id(). */
33 #include "riff.h"
34 #include "isom.h"
35 #include "matroska.h"
36 #include "libavcodec/mpeg4audio.h"
37 #include "libavutil/intfloat_readwrite.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/lzo.h"
40 #ifdef CONFIG_ZLIB
41 #include <zlib.h>
42 #endif
43 #ifdef CONFIG_BZLIB
44 #include <bzlib.h>
45 #endif
46
47 typedef enum {
48     EBML_NONE,
49     EBML_UINT,
50     EBML_FLOAT,
51     EBML_STR,
52     EBML_UTF8,
53     EBML_BIN,
54     EBML_NEST,
55     EBML_PASS,
56     EBML_STOP,
57 } EbmlType;
58
59 typedef const struct EbmlSyntax {
60     uint32_t id;
61     EbmlType type;
62     int list_elem_size;
63     int data_offset;
64     union {
65         uint64_t    u;
66         double      f;
67         const char *s;
68         const struct EbmlSyntax *n;
69     } def;
70 } EbmlSyntax;
71
72 typedef struct {
73     int nb_elem;
74     void *elem;
75 } EbmlList;
76
77 typedef struct {
78     int      size;
79     uint8_t *data;
80     int64_t  pos;
81 } EbmlBin;
82
83 typedef struct {
84     uint64_t version;
85     uint64_t max_size;
86     uint64_t id_length;
87     char    *doctype;
88     uint64_t doctype_version;
89 } Ebml;
90
91 typedef struct {
92     uint64_t algo;
93     EbmlBin  settings;
94 } MatroskaTrackCompression;
95
96 typedef struct {
97     uint64_t scope;
98     uint64_t type;
99     MatroskaTrackCompression compression;
100 } MatroskaTrackEncoding;
101
102 typedef struct {
103     double   frame_rate;
104     uint64_t display_width;
105     uint64_t display_height;
106     uint64_t pixel_width;
107     uint64_t pixel_height;
108     uint64_t fourcc;
109 } MatroskaTrackVideo;
110
111 typedef struct {
112     double   samplerate;
113     double   out_samplerate;
114     uint64_t bitdepth;
115     uint64_t channels;
116
117     /* real audio header (extracted from extradata) */
118     int      coded_framesize;
119     int      sub_packet_h;
120     int      frame_size;
121     int      sub_packet_size;
122     int      sub_packet_cnt;
123     int      pkt_cnt;
124     uint8_t *buf;
125 } MatroskaTrackAudio;
126
127 typedef struct {
128     uint64_t num;
129     uint64_t type;
130     char    *codec_id;
131     EbmlBin  codec_priv;
132     char    *language;
133     double time_scale;
134     uint64_t default_duration;
135     uint64_t flag_default;
136     MatroskaTrackVideo video;
137     MatroskaTrackAudio audio;
138     EbmlList encodings;
139
140     AVStream *stream;
141 } MatroskaTrack;
142
143 typedef struct {
144     char *filename;
145     char *mime;
146     EbmlBin bin;
147 } MatroskaAttachement;
148
149 typedef struct {
150     uint64_t start;
151     uint64_t end;
152     uint64_t uid;
153     char    *title;
154 } MatroskaChapter;
155
156 typedef struct {
157     uint64_t track;
158     uint64_t pos;
159 } MatroskaIndexPos;
160
161 typedef struct {
162     uint64_t time;
163     EbmlList pos;
164 } MatroskaIndex;
165
166 typedef struct {
167     uint64_t id;
168     uint64_t pos;
169 } MatroskaSeekhead;
170
171 typedef struct {
172     uint64_t start;
173     uint64_t length;
174 } MatroskaLevel;
175
176 typedef struct {
177     AVFormatContext *ctx;
178
179     /* ebml stuff */
180     int num_levels;
181     MatroskaLevel levels[EBML_MAX_DEPTH];
182     int level_up;
183
184     uint64_t time_scale;
185     double   duration;
186     char    *title;
187     EbmlList tracks;
188     EbmlList attachments;
189     EbmlList chapters;
190     EbmlList index;
191     EbmlList seekhead;
192
193     /* num_streams is the number of streams that av_new_stream() was called
194      * for ( = that are available to the calling program). */
195     int num_streams;
196
197     /* cache for ID peeking */
198     uint32_t peek_id;
199
200     /* byte position of the segment inside the stream */
201     offset_t segment_start;
202
203     /* The packet queue. */
204     AVPacket **packets;
205     int num_packets;
206
207     int done;
208     int has_cluster_id;
209
210     /* What to skip before effectively reading a packet. */
211     int skip_to_keyframe;
212     AVStream *skip_to_stream;
213 } MatroskaDemuxContext;
214
215 typedef struct {
216     uint64_t duration;
217     int64_t  reference;
218     EbmlBin  bin;
219 } MatroskaBlock;
220
221 typedef struct {
222     uint64_t timecode;
223     EbmlList blocks;
224 } MatroskaCluster;
225
226 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
227
228 static EbmlSyntax ebml_header[] = {
229     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
230     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
231     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
232     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
233     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
234     { EBML_ID_EBMLVERSION,            EBML_NONE },
235     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
236     { EBML_ID_VOID,                   EBML_NONE },
237     { 0 }
238 };
239
240 static EbmlSyntax ebml_syntax[] = {
241     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
242     { 0 }
243 };
244
245 static EbmlSyntax matroska_info[] = {
246     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
247     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
248     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
249     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
250     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
251     { MATROSKA_ID_DATEUTC,            EBML_NONE },
252     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
253     { EBML_ID_VOID,                   EBML_NONE },
254     { 0 }
255 };
256
257 static EbmlSyntax matroska_track_video[] = {
258     { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
259     { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
260     { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
261     { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
262     { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
263     { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
264     { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
265     { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
266     { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
267     { EBML_ID_VOID,                   EBML_NONE },
268     { 0 }
269 };
270
271 static EbmlSyntax matroska_track_audio[] = {
272     { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
273     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
274     { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
275     { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
276     { EBML_ID_VOID,                   EBML_NONE },
277     { 0 }
278 };
279
280 static EbmlSyntax matroska_track_encoding_compression[] = {
281     { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
282     { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
283     { EBML_ID_VOID,                   EBML_NONE },
284     { 0 }
285 };
286
287 static EbmlSyntax matroska_track_encoding[] = {
288     { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
289     { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
290     { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
291     { EBML_ID_VOID,                   EBML_NONE },
292     { 0 }
293 };
294
295 static EbmlSyntax matroska_track_encodings[] = {
296     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
297     { EBML_ID_VOID,                   EBML_NONE },
298     { 0 }
299 };
300
301 static EbmlSyntax matroska_track[] = {
302     { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
303     { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
304     { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
305     { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
306     { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
307     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
308     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
309     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
310     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
311     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
312     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
313     { MATROSKA_ID_TRACKUID,             EBML_NONE },
314     { MATROSKA_ID_TRACKNAME,            EBML_NONE },
315     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
316     { MATROSKA_ID_TRACKFLAGFORCED,      EBML_NONE },
317     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
318     { MATROSKA_ID_CODECNAME,            EBML_NONE },
319     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
320     { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
321     { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
322     { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
323     { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
324     { EBML_ID_VOID,                     EBML_NONE },
325     { 0 }
326 };
327
328 static EbmlSyntax matroska_tracks[] = {
329     { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
330     { EBML_ID_VOID,                   EBML_NONE },
331     { 0 }
332 };
333
334 static EbmlSyntax matroska_attachment[] = {
335     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
336     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
337     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
338     { MATROSKA_ID_FILEUID,            EBML_NONE },
339     { EBML_ID_VOID,                   EBML_NONE },
340     { 0 }
341 };
342
343 static EbmlSyntax matroska_attachments[] = {
344     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
345     { EBML_ID_VOID,                   EBML_NONE },
346     { 0 }
347 };
348
349 static EbmlSyntax matroska_chapter_display[] = {
350     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
351     { EBML_ID_VOID,                   EBML_NONE },
352     { 0 }
353 };
354
355 static EbmlSyntax matroska_chapter_entry[] = {
356     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
357     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
358     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
359     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
360     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
361     { EBML_ID_VOID,                   EBML_NONE },
362     { 0 }
363 };
364
365 static EbmlSyntax matroska_chapter[] = {
366     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
367     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
368     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
369     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
370     { EBML_ID_VOID,                   EBML_NONE },
371     { 0 }
372 };
373
374 static EbmlSyntax matroska_chapters[] = {
375     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
376     { EBML_ID_VOID,                   EBML_NONE },
377     { 0 }
378 };
379
380 static EbmlSyntax matroska_index_pos[] = {
381     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
382     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
383     { EBML_ID_VOID,                   EBML_NONE },
384     { 0 }
385 };
386
387 static EbmlSyntax matroska_index_entry[] = {
388     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
389     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
390     { EBML_ID_VOID,                   EBML_NONE },
391     { 0 }
392 };
393
394 static EbmlSyntax matroska_index[] = {
395     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
396     { EBML_ID_VOID,                   EBML_NONE },
397     { 0 }
398 };
399
400 static EbmlSyntax matroska_tags[] = {
401     { EBML_ID_VOID,                   EBML_NONE },
402     { 0 }
403 };
404
405 static EbmlSyntax matroska_seekhead_entry[] = {
406     { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
407     { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
408     { EBML_ID_VOID,                   EBML_NONE },
409     { 0 }
410 };
411
412 static EbmlSyntax matroska_seekhead[] = {
413     { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
414     { EBML_ID_VOID,                   EBML_NONE },
415     { 0 }
416 };
417
418 static EbmlSyntax matroska_segment[] = {
419     { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
420     { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
421     { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
422     { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
423     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
424     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
425     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
426     { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
427     { EBML_ID_VOID,               EBML_NONE },
428     { 0 }
429 };
430
431 static EbmlSyntax matroska_segments[] = {
432     { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
433     { 0 }
434 };
435
436 static EbmlSyntax matroska_blockgroup[] = {
437     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
438     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
439     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
440     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
441     { EBML_ID_VOID,               EBML_NONE },
442     { 0 }
443 };
444
445 static EbmlSyntax matroska_cluster[] = {
446     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
447     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
448     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
449     { EBML_ID_VOID,               EBML_NONE },
450     { 0 }
451 };
452
453 static EbmlSyntax matroska_clusters[] = {
454     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
455     { 0 }
456 };
457
458 /*
459  * Return: the amount of levels in the hierarchy that the
460  * current element lies higher than the previous one.
461  * The opposite isn't done - that's auto-done using master
462  * element reading.
463  */
464 static int
465 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
466 {
467     ByteIOContext *pb = matroska->ctx->pb;
468     offset_t pos = url_ftell(pb);
469     int num = 0;
470
471     while (matroska->num_levels > 0) {
472         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
473
474         if (pos >= level->start + level->length) {
475             matroska->num_levels--;
476             num++;
477         } else {
478             break;
479         }
480     }
481
482     return num;
483 }
484
485 /*
486  * Read: an "EBML number", which is defined as a variable-length
487  * array of bytes. The first byte indicates the length by giving a
488  * number of 0-bits followed by a one. The position of the first
489  * "one" bit inside the first byte indicates the length of this
490  * number.
491  * Returns: num. of bytes read. < 0 on error.
492  */
493 static int
494 ebml_read_num (MatroskaDemuxContext *matroska,
495                int                   max_size,
496                uint64_t             *number)
497 {
498     ByteIOContext *pb = matroska->ctx->pb;
499     int len_mask = 0x80, read = 1, n = 1;
500     int64_t total = 0;
501
502     /* the first byte tells us the length in bytes - get_byte() can normally
503      * return 0, but since that's not a valid first ebmlID byte, we can
504      * use it safely here to catch EOS. */
505     if (!(total = get_byte(pb))) {
506         /* we might encounter EOS here */
507         if (!url_feof(pb)) {
508             offset_t pos = url_ftell(pb);
509             av_log(matroska->ctx, AV_LOG_ERROR,
510                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
511                    pos, pos);
512         }
513         return AVERROR(EIO); /* EOS or actual I/O error */
514     }
515
516     /* get the length of the EBML number */
517     while (read <= max_size && !(total & len_mask)) {
518         read++;
519         len_mask >>= 1;
520     }
521     if (read > max_size) {
522         offset_t pos = url_ftell(pb) - 1;
523         av_log(matroska->ctx, AV_LOG_ERROR,
524                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
525                (uint8_t) total, pos, pos);
526         return AVERROR_INVALIDDATA;
527     }
528
529     /* read out length */
530     total &= ~len_mask;
531     while (n++ < read)
532         total = (total << 8) | get_byte(pb);
533
534     *number = total;
535
536     return read;
537 }
538
539 /*
540  * Read: the element content data ID.
541  * Return: the number of bytes read or < 0 on error.
542  */
543 static int
544 ebml_read_element_id (MatroskaDemuxContext *matroska,
545                       uint32_t             *id,
546                       int                  *level_up)
547 {
548     int read;
549     uint64_t total;
550
551     /* if we re-call this, use our cached ID */
552     if (matroska->peek_id != 0) {
553         *id = matroska->peek_id;
554         return 0;
555     }
556
557     /* read out the "EBML number", include tag in ID */
558     if ((read = ebml_read_num(matroska, 4, &total)) < 0)
559         return read;
560     *id = matroska->peek_id  = total | (1 << (read * 7));
561
562     return read;
563 }
564
565 /*
566  * Read: element content length.
567  * Return: the number of bytes read or < 0 on error.
568  */
569 static int
570 ebml_read_element_length (MatroskaDemuxContext *matroska,
571                           uint64_t             *length)
572 {
573     /* clear cache since we're now beyond that data point */
574     matroska->peek_id = 0;
575
576     /* read out the "EBML number", include tag in ID */
577     return ebml_read_num(matroska, 8, length);
578 }
579
580 /*
581  * Return: the ID of the next element, or 0 on error.
582  * Level_up contains the amount of levels that this
583  * next element lies higher than the previous one.
584  */
585 static uint32_t
586 ebml_peek_id (MatroskaDemuxContext *matroska,
587               int                  *level_up)
588 {
589     uint32_t id;
590     int res;
591
592     res = ebml_read_element_id(matroska, &id, NULL);
593     if (res < 0)
594         return 0;
595
596     if (res > 0 && level_up)
597         *level_up = ebml_read_element_level_up(matroska);
598
599     return id;
600 }
601
602 /*
603  * Seek to a given offset.
604  * 0 is success, -1 is failure.
605  */
606 static int
607 ebml_read_seek (MatroskaDemuxContext *matroska,
608                 offset_t              offset)
609 {
610     ByteIOContext *pb = matroska->ctx->pb;
611
612     /* clear ID cache, if any */
613     matroska->peek_id = 0;
614
615     return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
616 }
617
618 /*
619  * Skip the next element.
620  * 0 is success, -1 is failure.
621  */
622 static int
623 ebml_read_skip (MatroskaDemuxContext *matroska)
624 {
625     ByteIOContext *pb = matroska->ctx->pb;
626     uint32_t id;
627     uint64_t length;
628     int res;
629
630     if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
631         (res = ebml_read_element_length(matroska, &length)) < 0)
632         return res;
633
634     url_fskip(pb, length);
635
636     return 0;
637 }
638
639 /*
640  * Read the next element as an unsigned int.
641  * 0 is success, < 0 is failure.
642  */
643 static int
644 ebml_read_uint (MatroskaDemuxContext *matroska,
645                 uint32_t             *id,
646                 uint64_t             *num)
647 {
648     ByteIOContext *pb = matroska->ctx->pb;
649     int n = 0, size, res;
650     uint64_t rlength;
651
652     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
653         (res = ebml_read_element_length(matroska, &rlength)) < 0)
654         return res;
655     size = rlength;
656     if (size < 1 || size > 8) {
657         offset_t pos = url_ftell(pb);
658         av_log(matroska->ctx, AV_LOG_ERROR,
659                "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
660                 size, pos, pos);
661         return AVERROR_INVALIDDATA;
662     }
663
664     /* big-endian ordening; build up number */
665     *num = 0;
666     while (n++ < size)
667         *num = (*num << 8) | get_byte(pb);
668
669     return 0;
670 }
671
672 /*
673  * Read the next element as a float.
674  * 0 is success, < 0 is failure.
675  */
676 static int
677 ebml_read_float (MatroskaDemuxContext *matroska,
678                  uint32_t             *id,
679                  double               *num)
680 {
681     ByteIOContext *pb = matroska->ctx->pb;
682     int size, res;
683     uint64_t rlength;
684
685     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
686         (res = ebml_read_element_length(matroska, &rlength)) < 0)
687         return res;
688     size = rlength;
689
690     if (size == 4) {
691         *num= av_int2flt(get_be32(pb));
692     } else if(size==8){
693         *num= av_int2dbl(get_be64(pb));
694     } else{
695         offset_t pos = url_ftell(pb);
696         av_log(matroska->ctx, AV_LOG_ERROR,
697                "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
698                size, pos, pos);
699         return AVERROR_INVALIDDATA;
700     }
701
702     return 0;
703 }
704
705 /*
706  * Read the next element as an ASCII string.
707  * 0 is success, < 0 is failure.
708  */
709 static int
710 ebml_read_ascii (MatroskaDemuxContext *matroska,
711                  uint32_t             *id,
712                  char                **str)
713 {
714     ByteIOContext *pb = matroska->ctx->pb;
715     int size, res;
716     uint64_t rlength;
717
718     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
719         (res = ebml_read_element_length(matroska, &rlength)) < 0)
720         return res;
721     size = rlength;
722
723     /* ebml strings are usually not 0-terminated, so we allocate one
724      * byte more, read the string and NULL-terminate it ourselves. */
725     if (size < 0 || !(*str = av_malloc(size + 1))) {
726         av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
727         return AVERROR(ENOMEM);
728     }
729     if (get_buffer(pb, (uint8_t *) *str, size) != size) {
730         offset_t pos = url_ftell(pb);
731         av_log(matroska->ctx, AV_LOG_ERROR,
732                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
733         av_free(*str);
734         return AVERROR(EIO);
735     }
736     (*str)[size] = '\0';
737
738     return 0;
739 }
740
741 /*
742  * Read the next element, but only the header. The contents
743  * are supposed to be sub-elements which can be read separately.
744  * 0 is success, < 0 is failure.
745  */
746 static int
747 ebml_read_master (MatroskaDemuxContext *matroska,
748                   uint32_t             *id)
749 {
750     ByteIOContext *pb = matroska->ctx->pb;
751     uint64_t length;
752     MatroskaLevel *level;
753     int res;
754
755     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
756         (res = ebml_read_element_length(matroska, &length)) < 0)
757         return res;
758
759     if (matroska->num_levels >= EBML_MAX_DEPTH) {
760         av_log(matroska->ctx, AV_LOG_ERROR,
761                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
762         return AVERROR(ENOSYS);
763     }
764
765     level = &matroska->levels[matroska->num_levels++];
766     level->start = url_ftell(pb);
767     level->length = length;
768
769     return 0;
770 }
771
772 /*
773  * Read the next element as binary data.
774  * 0 is success, < 0 is failure.
775  */
776 static int
777 ebml_read_binary (MatroskaDemuxContext *matroska,
778                   uint32_t             *id,
779                   uint8_t             **binary,
780                   int                  *size)
781 {
782     ByteIOContext *pb = matroska->ctx->pb;
783     uint64_t rlength;
784     int res;
785
786     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
787         (res = ebml_read_element_length(matroska, &rlength)) < 0)
788         return res;
789     *size = rlength;
790
791     if (!(*binary = av_malloc(*size))) {
792         av_log(matroska->ctx, AV_LOG_ERROR,
793                "Memory allocation error\n");
794         return AVERROR(ENOMEM);
795     }
796
797     if (get_buffer(pb, *binary, *size) != *size) {
798         offset_t pos = url_ftell(pb);
799         av_log(matroska->ctx, AV_LOG_ERROR,
800                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
801         return AVERROR(EIO);
802     }
803
804     return 0;
805 }
806
807 /*
808  * Read signed/unsigned "EBML" numbers.
809  * Return: number of bytes processed, < 0 on error.
810  * XXX: use ebml_read_num().
811  */
812 static int
813 matroska_ebmlnum_uint (uint8_t  *data,
814                        uint32_t  size,
815                        uint64_t *num)
816 {
817     int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
818     uint64_t total;
819
820     if (size <= 0)
821         return AVERROR_INVALIDDATA;
822
823     total = data[0];
824     while (read <= 8 && !(total & len_mask)) {
825         read++;
826         len_mask >>= 1;
827     }
828     if (read > 8)
829         return AVERROR_INVALIDDATA;
830
831     if ((total &= (len_mask - 1)) == len_mask - 1)
832         num_ffs++;
833     if (size < read)
834         return AVERROR_INVALIDDATA;
835     while (n < read) {
836         if (data[n] == 0xff)
837             num_ffs++;
838         total = (total << 8) | data[n];
839         n++;
840     }
841
842     if (read == num_ffs)
843         *num = (uint64_t)-1;
844     else
845         *num = total;
846
847     return read;
848 }
849
850 /*
851  * Same as above, but signed.
852  */
853 static int
854 matroska_ebmlnum_sint (uint8_t  *data,
855                        uint32_t  size,
856                        int64_t  *num)
857 {
858     uint64_t unum;
859     int res;
860
861     /* read as unsigned number first */
862     if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
863         return res;
864
865     /* make signed (weird way) */
866     if (unum == (uint64_t)-1)
867         *num = INT64_MAX;
868     else
869         *num = unum - ((1LL << ((7 * res) - 1)) - 1);
870
871     return res;
872 }
873
874
875 static MatroskaTrack *
876 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
877                             int                   num)
878 {
879     MatroskaTrack *tracks = matroska->tracks.elem;
880     int i;
881
882     for (i=0; i < matroska->tracks.nb_elem; i++)
883         if (tracks[i].num == num)
884             return &tracks[i];
885
886     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
887     return NULL;
888 }
889
890
891 /*
892  * Put one packet in an application-supplied AVPacket struct.
893  * Returns 0 on success or -1 on failure.
894  */
895 static int
896 matroska_deliver_packet (MatroskaDemuxContext *matroska,
897                          AVPacket             *pkt)
898 {
899     if (matroska->num_packets > 0) {
900         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
901         av_free(matroska->packets[0]);
902         if (matroska->num_packets > 1) {
903             memmove(&matroska->packets[0], &matroska->packets[1],
904                     (matroska->num_packets - 1) * sizeof(AVPacket *));
905             matroska->packets =
906                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
907                            sizeof(AVPacket *));
908         } else {
909             av_freep(&matroska->packets);
910         }
911         matroska->num_packets--;
912         return 0;
913     }
914
915     return -1;
916 }
917
918 /*
919  * Put a packet into our internal queue. Will be delivered to the
920  * user/application during the next get_packet() call.
921  */
922 static void
923 matroska_queue_packet (MatroskaDemuxContext *matroska,
924                        AVPacket             *pkt)
925 {
926     matroska->packets =
927         av_realloc(matroska->packets, (matroska->num_packets + 1) *
928                    sizeof(AVPacket *));
929     matroska->packets[matroska->num_packets] = pkt;
930     matroska->num_packets++;
931 }
932
933 /*
934  * Free all packets in our internal queue.
935  */
936 static void
937 matroska_clear_queue (MatroskaDemuxContext *matroska)
938 {
939     if (matroska->packets) {
940         int n;
941         for (n = 0; n < matroska->num_packets; n++) {
942             av_free_packet(matroska->packets[n]);
943             av_free(matroska->packets[n]);
944         }
945         av_free(matroska->packets);
946         matroska->packets = NULL;
947         matroska->num_packets = 0;
948     }
949 }
950
951
952 /*
953  * Autodetecting...
954  */
955 static int
956 matroska_probe (AVProbeData *p)
957 {
958     uint64_t total = 0;
959     int len_mask = 0x80, size = 1, n = 1;
960     uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
961
962     /* ebml header? */
963     if (AV_RB32(p->buf) != EBML_ID_HEADER)
964         return 0;
965
966     /* length of header */
967     total = p->buf[4];
968     while (size <= 8 && !(total & len_mask)) {
969         size++;
970         len_mask >>= 1;
971     }
972     if (size > 8)
973       return 0;
974     total &= (len_mask - 1);
975     while (n < size)
976         total = (total << 8) | p->buf[4 + n++];
977
978     /* does the probe data contain the whole header? */
979     if (p->buf_size < 4 + size + total)
980       return 0;
981
982     /* the header must contain the document type 'matroska'. For now,
983      * we don't parse the whole header but simply check for the
984      * availability of that array of characters inside the header.
985      * Not fully fool-proof, but good enough. */
986     for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
987         if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
988             return AVPROBE_SCORE_MAX;
989
990     return 0;
991 }
992
993 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
994                       void *data, uint32_t expected_id, int once);
995
996 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
997                            EbmlSyntax *syntax, void *data)
998 {
999     uint32_t id = syntax->id;
1000     EbmlBin *bin;
1001     int res;
1002
1003     data = (char *)data + syntax->data_offset;
1004     if (syntax->list_elem_size) {
1005         EbmlList *list = data;
1006         list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1007         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1008         memset(data, 0, syntax->list_elem_size);
1009         list->nb_elem++;
1010     }
1011     bin = data;
1012
1013     switch (syntax->type) {
1014     case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
1015     case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1016     case EBML_STR:
1017     case EBML_UTF8:  av_free(*(char **)data);
1018                      return ebml_read_ascii(matroska, &id, data);
1019     case EBML_BIN:   av_free(bin->data);
1020                      bin->pos = url_ftell(matroska->ctx->pb);
1021                      return ebml_read_binary(matroska, &id, &bin->data,
1022                                                             &bin->size);
1023     case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
1024                          return res;
1025                      if (id == MATROSKA_ID_SEGMENT)
1026                          matroska->segment_start = url_ftell(matroska->ctx->pb);
1027                      return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1028     case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1029     case EBML_STOP:  *(int *)data = 1;      return 1;
1030     default:         return ebml_read_skip(matroska);
1031     }
1032 }
1033
1034 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1035                          uint32_t id, void *data)
1036 {
1037     int i;
1038     for (i=0; syntax[i].id; i++)
1039         if (id == syntax[i].id)
1040             break;
1041     if (!syntax[i].id)
1042         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1043     return ebml_parse_elem(matroska, &syntax[i], data);
1044 }
1045
1046 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1047                       void *data, uint32_t expected_id, int once)
1048 {
1049     int i, res = 0;
1050     uint32_t id = 0;
1051
1052     for (i=0; syntax[i].id; i++)
1053         switch (syntax[i].type) {
1054         case EBML_UINT:
1055             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1056             break;
1057         case EBML_FLOAT:
1058             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1059             break;
1060         case EBML_STR:
1061         case EBML_UTF8:
1062             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1063             break;
1064         }
1065
1066     if (expected_id) {
1067         res = ebml_read_master(matroska, &id);
1068         if (id != expected_id)
1069             return AVERROR_INVALIDDATA;
1070         if (id == MATROSKA_ID_SEGMENT)
1071             matroska->segment_start = url_ftell(matroska->ctx->pb);
1072     }
1073
1074     while (!res) {
1075         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1076             res = AVERROR(EIO);
1077             break;
1078         } else if (matroska->level_up) {
1079             matroska->level_up--;
1080             break;
1081         }
1082
1083         res = ebml_parse_id(matroska, syntax, id, data);
1084         if (once)
1085             break;
1086     }
1087
1088     return res;
1089 }
1090
1091 static void ebml_free(EbmlSyntax *syntax, void *data)
1092 {
1093     int i, j;
1094     for (i=0; syntax[i].id; i++) {
1095         void *data_off = (char *)data + syntax[i].data_offset;
1096         switch (syntax[i].type) {
1097         case EBML_STR:
1098         case EBML_UTF8:  av_freep(data_off);                      break;
1099         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
1100         case EBML_NEST:
1101             if (syntax[i].list_elem_size) {
1102                 EbmlList *list = data_off;
1103                 char *ptr = list->elem;
1104                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1105                     ebml_free(syntax[i].def.n, ptr);
1106                 av_free(list->elem);
1107             } else
1108                 ebml_free(syntax[i].def.n, data_off);
1109         default:  break;
1110         }
1111     }
1112 }
1113
1114 static int
1115 matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1116 {
1117     MatroskaTrackEncoding *encodings = track->encodings.elem;
1118     uint8_t* data = *buf;
1119     int isize = *buf_size;
1120     uint8_t* pkt_data = NULL;
1121     int pkt_size = isize;
1122     int result = 0;
1123     int olen;
1124
1125     switch (encodings[0].compression.algo) {
1126     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1127         return encodings[0].compression.settings.size;
1128     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1129         do {
1130             olen = pkt_size *= 3;
1131             pkt_data = av_realloc(pkt_data,
1132                                   pkt_size+LZO_OUTPUT_PADDING);
1133             result = lzo1x_decode(pkt_data, &olen, data, &isize);
1134         } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1135         if (result)
1136             goto failed;
1137         pkt_size -= olen;
1138         break;
1139 #ifdef CONFIG_ZLIB
1140     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1141         z_stream zstream = {0};
1142         if (inflateInit(&zstream) != Z_OK)
1143             return -1;
1144         zstream.next_in = data;
1145         zstream.avail_in = isize;
1146         do {
1147             pkt_size *= 3;
1148             pkt_data = av_realloc(pkt_data, pkt_size);
1149             zstream.avail_out = pkt_size - zstream.total_out;
1150             zstream.next_out = pkt_data + zstream.total_out;
1151             result = inflate(&zstream, Z_NO_FLUSH);
1152         } while (result==Z_OK && pkt_size<10000000);
1153         pkt_size = zstream.total_out;
1154         inflateEnd(&zstream);
1155         if (result != Z_STREAM_END)
1156             goto failed;
1157         break;
1158     }
1159 #endif
1160 #ifdef CONFIG_BZLIB
1161     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1162         bz_stream bzstream = {0};
1163         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1164             return -1;
1165         bzstream.next_in = data;
1166         bzstream.avail_in = isize;
1167         do {
1168             pkt_size *= 3;
1169             pkt_data = av_realloc(pkt_data, pkt_size);
1170             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1171             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1172             result = BZ2_bzDecompress(&bzstream);
1173         } while (result==BZ_OK && pkt_size<10000000);
1174         pkt_size = bzstream.total_out_lo32;
1175         BZ2_bzDecompressEnd(&bzstream);
1176         if (result != BZ_STREAM_END)
1177             goto failed;
1178         break;
1179     }
1180 #endif
1181     }
1182
1183     *buf = pkt_data;
1184     *buf_size = pkt_size;
1185     return 0;
1186  failed:
1187     av_free(pkt_data);
1188     return -1;
1189 }
1190
1191 static void
1192 matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1193 {
1194     EbmlList *seekhead_list = &matroska->seekhead;
1195     MatroskaSeekhead *seekhead = seekhead_list->elem;
1196     uint32_t peek_id_cache = matroska->peek_id;
1197     uint32_t level_up = matroska->level_up;
1198     offset_t before_pos = url_ftell(matroska->ctx->pb);
1199     MatroskaLevel level;
1200     int i;
1201
1202     for (i=0; i<seekhead_list->nb_elem; i++) {
1203         if (seekhead[i].pos <= before_pos
1204             || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1205             || seekhead[i].id == MATROSKA_ID_CLUSTER)
1206             continue;
1207
1208         /* seek */
1209         if (ebml_read_seek(matroska,
1210                            seekhead[i].pos+matroska->segment_start) < 0)
1211             continue;
1212
1213         /* we don't want to lose our seekhead level, so we add
1214          * a dummy. This is a crude hack. */
1215         if (matroska->num_levels == EBML_MAX_DEPTH) {
1216             av_log(matroska->ctx, AV_LOG_INFO,
1217                    "Max EBML element depth (%d) reached, "
1218                    "cannot parse further.\n", EBML_MAX_DEPTH);
1219             break;
1220         }
1221
1222         level.start = 0;
1223         level.length = (uint64_t)-1;
1224         matroska->levels[matroska->num_levels] = level;
1225         matroska->num_levels++;
1226
1227         ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1228
1229         /* remove dummy level */
1230         while (matroska->num_levels) {
1231             uint64_t length = matroska->levels[--matroska->num_levels].length;
1232             if (length == (uint64_t)-1)
1233                 break;
1234         }
1235     }
1236
1237     /* seek back */
1238     ebml_read_seek(matroska, before_pos);
1239     matroska->peek_id = peek_id_cache;
1240     matroska->level_up = level_up;
1241 }
1242
1243 static int
1244 matroska_aac_profile (char *codec_id)
1245 {
1246     static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1247     int profile;
1248
1249     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1250         if (strstr(codec_id, aac_profiles[profile]))
1251             break;
1252     return profile + 1;
1253 }
1254
1255 static int
1256 matroska_aac_sri (int samplerate)
1257 {
1258     int sri;
1259
1260     for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1261         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1262             break;
1263     return sri;
1264 }
1265
1266 static int
1267 matroska_read_header (AVFormatContext    *s,
1268                       AVFormatParameters *ap)
1269 {
1270     MatroskaDemuxContext *matroska = s->priv_data;
1271     EbmlList *attachements_list = &matroska->attachments;
1272     MatroskaAttachement *attachements;
1273     EbmlList *chapters_list = &matroska->chapters;
1274     MatroskaChapter *chapters;
1275     MatroskaTrack *tracks;
1276     EbmlList *index_list;
1277     MatroskaIndex *index;
1278     Ebml ebml = { 0 };
1279     AVStream *st;
1280     int i, j;
1281
1282     matroska->ctx = s;
1283
1284     /* First read the EBML header. */
1285     if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1286         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1287         || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1288         || ebml.doctype_version > 2) {
1289         av_log(matroska->ctx, AV_LOG_ERROR,
1290                "EBML header using unsupported features\n"
1291                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1292                ebml.version, ebml.doctype, ebml.doctype_version);
1293         return AVERROR_NOFMT;
1294     }
1295     ebml_free(ebml_syntax, &ebml);
1296
1297     /* The next thing is a segment. */
1298     if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1299         return -1;
1300     matroska_execute_seekhead(matroska);
1301
1302     if (matroska->duration)
1303         matroska->ctx->duration = matroska->duration * matroska->time_scale
1304                                   * 1000 / AV_TIME_BASE;
1305     if (matroska->title)
1306         strncpy(matroska->ctx->title, matroska->title,
1307                 sizeof(matroska->ctx->title)-1);
1308
1309     tracks = matroska->tracks.elem;
1310     for (i=0; i < matroska->tracks.nb_elem; i++) {
1311         MatroskaTrack *track = &tracks[i];
1312         enum CodecID codec_id = CODEC_ID_NONE;
1313         EbmlList *encodings_list = &tracks->encodings;
1314         MatroskaTrackEncoding *encodings = encodings_list->elem;
1315         uint8_t *extradata = NULL;
1316         int extradata_size = 0;
1317         int extradata_offset = 0;
1318
1319         /* Apply some sanity checks. */
1320         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1321             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1322             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1323             av_log(matroska->ctx, AV_LOG_INFO,
1324                    "Unknown or unsupported track type %"PRIu64"\n",
1325                    track->type);
1326             continue;
1327         }
1328         if (track->codec_id == NULL)
1329             continue;
1330
1331         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1332             if (!track->default_duration)
1333                 track->default_duration = 1000000000/track->video.frame_rate;
1334             if (!track->video.display_width)
1335                 track->video.display_width = track->video.pixel_width;
1336             if (!track->video.display_height)
1337                 track->video.display_height = track->video.pixel_height;
1338         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1339             if (!track->audio.out_samplerate)
1340                 track->audio.out_samplerate = track->audio.samplerate;
1341         }
1342         if (encodings_list->nb_elem > 1) {
1343             av_log(matroska->ctx, AV_LOG_ERROR,
1344                    "Multiple combined encodings no supported");
1345         } else if (encodings_list->nb_elem == 1) {
1346             if (encodings[0].type ||
1347                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1348 #ifdef CONFIG_ZLIB
1349                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1350 #endif
1351 #ifdef CONFIG_BZLIB
1352                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1353 #endif
1354                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1355                 encodings[0].scope = 0;
1356                 av_log(matroska->ctx, AV_LOG_ERROR,
1357                        "Unsupported encoding type");
1358             } else if (track->codec_priv.size && encodings[0].scope&2) {
1359                 uint8_t *codec_priv = track->codec_priv.data;
1360                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1361                                                     &track->codec_priv.size,
1362                                                     track);
1363                 if (offset < 0) {
1364                     track->codec_priv.data = NULL;
1365                     track->codec_priv.size = 0;
1366                     av_log(matroska->ctx, AV_LOG_ERROR,
1367                            "Failed to decode codec private data\n");
1368                 } else if (offset > 0) {
1369                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1370                     memcpy(track->codec_priv.data,
1371                            encodings[0].compression.settings.data, offset);
1372                     memcpy(track->codec_priv.data+offset, codec_priv,
1373                            track->codec_priv.size);
1374                     track->codec_priv.size += offset;
1375                 }
1376                 if (codec_priv != track->codec_priv.data)
1377                     av_free(codec_priv);
1378             }
1379         }
1380
1381         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1382             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1383                         strlen(ff_mkv_codec_tags[j].str))){
1384                 codec_id= ff_mkv_codec_tags[j].id;
1385                 break;
1386             }
1387         }
1388
1389         st = track->stream = av_new_stream(s, matroska->num_streams++);
1390         if (st == NULL)
1391             return AVERROR(ENOMEM);
1392
1393         if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)
1394             && track->codec_priv.size >= 40
1395             && track->codec_priv.data != NULL) {
1396             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1397             codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1398         } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_AUDIO_ACM)
1399                    && track->codec_priv.size >= 18
1400                    && track->codec_priv.data != NULL) {
1401             uint16_t tag = AV_RL16(track->codec_priv.data);
1402             codec_id = codec_get_id(codec_wav_tags, tag);
1403         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1404                    && (track->codec_priv.size >= 86)
1405                    && (track->codec_priv.data != NULL)) {
1406             track->video.fourcc = AV_RL32(track->codec_priv.data);
1407             codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1408         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1409             int profile = matroska_aac_profile(track->codec_id);
1410             int sri = matroska_aac_sri(track->audio.samplerate);
1411             extradata = av_malloc(5);
1412             if (extradata == NULL)
1413                 return AVERROR(ENOMEM);
1414             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1415             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1416             if (strstr(track->codec_id, "SBR")) {
1417                 sri = matroska_aac_sri(track->audio.out_samplerate);
1418                 extradata[2] = 0x56;
1419                 extradata[3] = 0xE5;
1420                 extradata[4] = 0x80 | (sri<<3);
1421                 extradata_size = 5;
1422             } else
1423                 extradata_size = 2;
1424         } else if (codec_id == CODEC_ID_TTA) {
1425             ByteIOContext b;
1426             extradata_size = 30;
1427             extradata = av_mallocz(extradata_size);
1428             if (extradata == NULL)
1429                 return AVERROR(ENOMEM);
1430             init_put_byte(&b, extradata, extradata_size, 1,
1431                           NULL, NULL, NULL, NULL);
1432             put_buffer(&b, "TTA1", 4);
1433             put_le16(&b, 1);
1434             put_le16(&b, track->audio.channels);
1435             put_le16(&b, track->audio.bitdepth);
1436             put_le32(&b, track->audio.out_samplerate);
1437             put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1438         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1439                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1440             extradata_offset = 26;
1441             track->codec_priv.size -= extradata_offset;
1442         } else if (codec_id == CODEC_ID_RA_144) {
1443             track->audio.out_samplerate = 8000;
1444             track->audio.channels = 1;
1445         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1446                    codec_id == CODEC_ID_ATRAC3) {
1447             ByteIOContext b;
1448
1449             init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1450                           0, NULL, NULL, NULL, NULL);
1451             url_fskip(&b, 24);
1452             track->audio.coded_framesize = get_be32(&b);
1453             url_fskip(&b, 12);
1454             track->audio.sub_packet_h    = get_be16(&b);
1455             track->audio.frame_size      = get_be16(&b);
1456             track->audio.sub_packet_size = get_be16(&b);
1457             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1458             if (codec_id == CODEC_ID_RA_288) {
1459                 st->codec->block_align = track->audio.coded_framesize;
1460                 track->codec_priv.size = 0;
1461             } else {
1462                 st->codec->block_align = track->audio.sub_packet_size;
1463                 extradata_offset = 78;
1464                 track->codec_priv.size -= extradata_offset;
1465             }
1466         }
1467
1468         if (codec_id == CODEC_ID_NONE)
1469             av_log(matroska->ctx, AV_LOG_INFO,
1470                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1471
1472         av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1473
1474         st->codec->codec_id = codec_id;
1475         st->start_time = 0;
1476         if (strcmp(track->language, "und"))
1477             av_strlcpy(st->language, track->language, 4);
1478
1479         if (track->flag_default)
1480             st->disposition |= AV_DISPOSITION_DEFAULT;
1481
1482         if (track->default_duration)
1483             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1484                       track->default_duration, 1000000000, 30000);
1485
1486         if(extradata){
1487             st->codec->extradata = extradata;
1488             st->codec->extradata_size = extradata_size;
1489         } else if(track->codec_priv.data && track->codec_priv.size > 0){
1490             st->codec->extradata = av_malloc(track->codec_priv.size);
1491             if(st->codec->extradata == NULL)
1492                 return AVERROR(ENOMEM);
1493             st->codec->extradata_size = track->codec_priv.size;
1494             memcpy(st->codec->extradata,
1495                    track->codec_priv.data + extradata_offset,
1496                    track->codec_priv.size);
1497         }
1498
1499         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1500             st->codec->codec_type = CODEC_TYPE_VIDEO;
1501             st->codec->codec_tag  = track->video.fourcc;
1502             st->codec->width  = track->video.pixel_width;
1503             st->codec->height = track->video.pixel_height;
1504             av_reduce(&st->codec->sample_aspect_ratio.num,
1505                       &st->codec->sample_aspect_ratio.den,
1506                       st->codec->height * track->video.display_width,
1507                       st->codec-> width * track->video.display_height,
1508                       255);
1509             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1510         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1511             st->codec->codec_type = CODEC_TYPE_AUDIO;
1512             st->codec->sample_rate = track->audio.out_samplerate;
1513             st->codec->channels = track->audio.channels;
1514         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1515             st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1516         }
1517     }
1518
1519     attachements = attachements_list->elem;
1520     for (j=0; j<attachements_list->nb_elem; j++) {
1521         if (!(attachements[j].filename && attachements[j].mime &&
1522               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1523             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1524         } else {
1525             AVStream *st = av_new_stream(s, matroska->num_streams++);
1526             if (st == NULL)
1527                 break;
1528             st->filename          = av_strdup(attachements[j].filename);
1529             st->codec->codec_id = CODEC_ID_NONE;
1530             st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1531             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1532             if(st->codec->extradata == NULL)
1533                 break;
1534             st->codec->extradata_size = attachements[j].bin.size;
1535             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1536
1537             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1538                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1539                              strlen(ff_mkv_mime_tags[i].str))) {
1540                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1541                     break;
1542                 }
1543             }
1544         }
1545     }
1546
1547     chapters = chapters_list->elem;
1548     for (i=0; i<chapters_list->nb_elem; i++)
1549         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1550             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1551                            chapters[i].start, chapters[i].end,
1552                            chapters[i].title);
1553
1554     index_list = &matroska->index;
1555     index = index_list->elem;
1556     for (i=0; i<index_list->nb_elem; i++) {
1557         EbmlList *pos_list = &index[i].pos;
1558         MatroskaIndexPos *pos = pos_list->elem;
1559         for (j=0; j<pos_list->nb_elem; j++) {
1560             MatroskaTrack *track = matroska_find_track_by_num(matroska,
1561                                                               pos[j].track);
1562             if (track && track->stream)
1563                 av_add_index_entry(track->stream,
1564                                    pos[j].pos + matroska->segment_start,
1565                                    index[i].time*matroska->time_scale/AV_TIME_BASE,
1566                                    0, 0, AVINDEX_KEYFRAME);
1567         }
1568     }
1569
1570     return 0;
1571 }
1572
1573 static int
1574 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1575                      int64_t pos, uint64_t cluster_time, uint64_t duration,
1576                      int is_keyframe)
1577 {
1578     MatroskaTrack *track;
1579     int res = 0;
1580     AVStream *st;
1581     AVPacket *pkt;
1582     int16_t block_time;
1583     uint32_t *lace_size = NULL;
1584     int n, flags, laces = 0;
1585     uint64_t num;
1586
1587     if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1588         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1589         return res;
1590     }
1591     data += n;
1592     size -= n;
1593
1594     track = matroska_find_track_by_num(matroska, num);
1595     if (size <= 3 || !track || !track->stream) {
1596         av_log(matroska->ctx, AV_LOG_INFO,
1597                "Invalid stream %"PRIu64" or size %u\n", num, size);
1598         return res;
1599     }
1600     st = track->stream;
1601     if (st->discard >= AVDISCARD_ALL)
1602         return res;
1603     if (duration == AV_NOPTS_VALUE)
1604         duration = track->default_duration / matroska->time_scale;
1605
1606     block_time = AV_RB16(data);
1607     data += 2;
1608     flags = *data++;
1609     size -= 3;
1610     if (is_keyframe == -1)
1611         is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1612
1613     if (matroska->skip_to_keyframe) {
1614         if (!is_keyframe || st != matroska->skip_to_stream)
1615             return res;
1616         matroska->skip_to_keyframe = 0;
1617     }
1618
1619     switch ((flags & 0x06) >> 1) {
1620         case 0x0: /* no lacing */
1621             laces = 1;
1622             lace_size = av_mallocz(sizeof(int));
1623             lace_size[0] = size;
1624             break;
1625
1626         case 0x1: /* xiph lacing */
1627         case 0x2: /* fixed-size lacing */
1628         case 0x3: /* EBML lacing */
1629             assert(size>0); // size <=3 is checked before size-=3 above
1630             laces = (*data) + 1;
1631             data += 1;
1632             size -= 1;
1633             lace_size = av_mallocz(laces * sizeof(int));
1634
1635             switch ((flags & 0x06) >> 1) {
1636                 case 0x1: /* xiph lacing */ {
1637                     uint8_t temp;
1638                     uint32_t total = 0;
1639                     for (n = 0; res == 0 && n < laces - 1; n++) {
1640                         while (1) {
1641                             if (size == 0) {
1642                                 res = -1;
1643                                 break;
1644                             }
1645                             temp = *data;
1646                             lace_size[n] += temp;
1647                             data += 1;
1648                             size -= 1;
1649                             if (temp != 0xff)
1650                                 break;
1651                         }
1652                         total += lace_size[n];
1653                     }
1654                     lace_size[n] = size - total;
1655                     break;
1656                 }
1657
1658                 case 0x2: /* fixed-size lacing */
1659                     for (n = 0; n < laces; n++)
1660                         lace_size[n] = size / laces;
1661                     break;
1662
1663                 case 0x3: /* EBML lacing */ {
1664                     uint32_t total;
1665                     n = matroska_ebmlnum_uint(data, size, &num);
1666                     if (n < 0) {
1667                         av_log(matroska->ctx, AV_LOG_INFO,
1668                                "EBML block data error\n");
1669                         break;
1670                     }
1671                     data += n;
1672                     size -= n;
1673                     total = lace_size[0] = num;
1674                     for (n = 1; res == 0 && n < laces - 1; n++) {
1675                         int64_t snum;
1676                         int r;
1677                         r = matroska_ebmlnum_sint (data, size, &snum);
1678                         if (r < 0) {
1679                             av_log(matroska->ctx, AV_LOG_INFO,
1680                                    "EBML block data error\n");
1681                             break;
1682                         }
1683                         data += r;
1684                         size -= r;
1685                         lace_size[n] = lace_size[n - 1] + snum;
1686                         total += lace_size[n];
1687                     }
1688                     lace_size[n] = size - total;
1689                     break;
1690                 }
1691             }
1692             break;
1693     }
1694
1695     if (res == 0) {
1696         uint64_t timecode = AV_NOPTS_VALUE;
1697
1698         if (cluster_time != (uint64_t)-1
1699             && (block_time >= 0 || cluster_time >= -block_time))
1700             timecode = cluster_time + block_time;
1701
1702         for (n = 0; n < laces; n++) {
1703             if (st->codec->codec_id == CODEC_ID_RA_288 ||
1704                 st->codec->codec_id == CODEC_ID_COOK ||
1705                 st->codec->codec_id == CODEC_ID_ATRAC3) {
1706                 int a = st->codec->block_align;
1707                 int sps = track->audio.sub_packet_size;
1708                 int cfs = track->audio.coded_framesize;
1709                 int h = track->audio.sub_packet_h;
1710                 int y = track->audio.sub_packet_cnt;
1711                 int w = track->audio.frame_size;
1712                 int x;
1713
1714                 if (!track->audio.pkt_cnt) {
1715                     if (st->codec->codec_id == CODEC_ID_RA_288)
1716                         for (x=0; x<h/2; x++)
1717                             memcpy(track->audio.buf+x*2*w+y*cfs,
1718                                    data+x*cfs, cfs);
1719                     else
1720                         for (x=0; x<w/sps; x++)
1721                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1722
1723                     if (++track->audio.sub_packet_cnt >= h) {
1724                         track->audio.sub_packet_cnt = 0;
1725                         track->audio.pkt_cnt = h*w / a;
1726                     }
1727                 }
1728                 while (track->audio.pkt_cnt) {
1729                     pkt = av_mallocz(sizeof(AVPacket));
1730                     av_new_packet(pkt, a);
1731                     memcpy(pkt->data, track->audio.buf
1732                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1733                     pkt->pos = pos;
1734                     pkt->stream_index = st->index;
1735                     matroska_queue_packet(matroska, pkt);
1736                 }
1737             } else {
1738                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1739                 int offset = 0, pkt_size = lace_size[n];
1740                 uint8_t *pkt_data = data;
1741
1742                 if (encodings && encodings->scope & 1) {
1743                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1744                     if (offset < 0)
1745                         continue;
1746                 }
1747
1748                 pkt = av_mallocz(sizeof(AVPacket));
1749                 /* XXX: prevent data copy... */
1750                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1751                     av_free(pkt);
1752                     res = AVERROR(ENOMEM);
1753                     n = laces-1;
1754                     break;
1755                 }
1756                 if (offset)
1757                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1758                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1759
1760                 if (pkt_data != data)
1761                     av_free(pkt_data);
1762
1763                 if (n == 0)
1764                     pkt->flags = is_keyframe;
1765                 pkt->stream_index = st->index;
1766
1767                 pkt->pts = timecode;
1768                 pkt->pos = pos;
1769                 pkt->duration = duration;
1770
1771                 matroska_queue_packet(matroska, pkt);
1772             }
1773
1774             if (timecode != AV_NOPTS_VALUE)
1775                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1776             data += lace_size[n];
1777         }
1778     }
1779
1780     av_free(lace_size);
1781     return res;
1782 }
1783
1784 static int
1785 matroska_parse_cluster (MatroskaDemuxContext *matroska)
1786 {
1787     MatroskaCluster cluster = { 0 };
1788     EbmlList *blocks_list;
1789     MatroskaBlock *blocks;
1790     int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 0, 1);
1791     blocks_list = &cluster.blocks;
1792     blocks = blocks_list->elem;
1793     for (i=0; !res && i<blocks_list->nb_elem; i++)
1794         if (blocks[i].bin.size > 0)
1795             res=matroska_parse_block(matroska,
1796                                      blocks[i].bin.data, blocks[i].bin.size,
1797                                      blocks[i].bin.pos,  cluster.timecode,
1798                                      blocks[i].duration, !blocks[i].reference);
1799     ebml_free(matroska_cluster, &cluster);
1800     return res;
1801 }
1802
1803 static int
1804 matroska_read_packet (AVFormatContext *s,
1805                       AVPacket        *pkt)
1806 {
1807     MatroskaDemuxContext *matroska = s->priv_data;
1808
1809     while (matroska_deliver_packet(matroska, pkt)) {
1810         if (matroska->done)
1811             return AVERROR(EIO);
1812         if (matroska_parse_cluster(matroska) < 0)
1813             matroska->done = 1;
1814     }
1815
1816     return 0;
1817 }
1818
1819 static int
1820 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1821                     int flags)
1822 {
1823     MatroskaDemuxContext *matroska = s->priv_data;
1824     AVStream *st = s->streams[stream_index];
1825     int index;
1826
1827     index = av_index_search_timestamp(st, timestamp, flags);
1828     if (index < 0)
1829         return 0;
1830
1831     matroska_clear_queue(matroska);
1832
1833     url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1834     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1835     matroska->skip_to_stream = st;
1836     matroska->peek_id = 0;
1837     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1838     return 0;
1839 }
1840
1841 static int
1842 matroska_read_close (AVFormatContext *s)
1843 {
1844     MatroskaDemuxContext *matroska = s->priv_data;
1845     MatroskaTrack *tracks = matroska->tracks.elem;
1846     int n;
1847
1848     matroska_clear_queue(matroska);
1849
1850     for (n=0; n < matroska->tracks.nb_elem; n++)
1851         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1852             av_free(tracks[n].audio.buf);
1853     ebml_free(matroska_segment, matroska);
1854
1855     return 0;
1856 }
1857
1858 AVInputFormat matroska_demuxer = {
1859     "matroska",
1860     NULL_IF_CONFIG_SMALL("Matroska file format"),
1861     sizeof(MatroskaDemuxContext),
1862     matroska_probe,
1863     matroska_read_header,
1864     matroska_read_packet,
1865     matroska_read_close,
1866     matroska_read_seek,
1867 };