]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
rtpproto: Check the size before reading buf[1]
[ffmpeg] / libavformat / matroskadec.c
1 /*
2  * Matroska file demuxer
3  * Copyright (c) 2003-2008 The Libav Project
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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
24  * Matroska file demuxer
25  * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28  * @see specs available on the Matroska project page: http://www.matroska.org/
29  */
30
31 #include <stdio.h>
32 #include "avformat.h"
33 #include "internal.h"
34 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
36 #include "riff.h"
37 #include "isom.h"
38 #include "rmsipr.h"
39 #include "matroska.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/mpeg4audio.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/lzo.h"
46 #include "libavutil/dict.h"
47 #if CONFIG_ZLIB
48 #include <zlib.h>
49 #endif
50 #if CONFIG_BZLIB
51 #include <bzlib.h>
52 #endif
53
54 typedef enum {
55     EBML_NONE,
56     EBML_UINT,
57     EBML_FLOAT,
58     EBML_STR,
59     EBML_UTF8,
60     EBML_BIN,
61     EBML_NEST,
62     EBML_PASS,
63     EBML_STOP,
64     EBML_TYPE_COUNT
65 } EbmlType;
66
67 typedef const struct EbmlSyntax {
68     uint32_t id;
69     EbmlType type;
70     int list_elem_size;
71     int data_offset;
72     union {
73         uint64_t    u;
74         double      f;
75         const char *s;
76         const struct EbmlSyntax *n;
77     } def;
78 } EbmlSyntax;
79
80 typedef struct {
81     int nb_elem;
82     void *elem;
83 } EbmlList;
84
85 typedef struct {
86     int      size;
87     uint8_t *data;
88     int64_t  pos;
89 } EbmlBin;
90
91 typedef struct {
92     uint64_t version;
93     uint64_t max_size;
94     uint64_t id_length;
95     char    *doctype;
96     uint64_t doctype_version;
97 } Ebml;
98
99 typedef struct {
100     uint64_t algo;
101     EbmlBin  settings;
102 } MatroskaTrackCompression;
103
104 typedef struct {
105     uint64_t scope;
106     uint64_t type;
107     MatroskaTrackCompression compression;
108 } MatroskaTrackEncoding;
109
110 typedef struct {
111     double   frame_rate;
112     uint64_t display_width;
113     uint64_t display_height;
114     uint64_t pixel_width;
115     uint64_t pixel_height;
116     uint64_t fourcc;
117 } MatroskaTrackVideo;
118
119 typedef struct {
120     double   samplerate;
121     double   out_samplerate;
122     uint64_t bitdepth;
123     uint64_t channels;
124
125     /* real audio header (extracted from extradata) */
126     int      coded_framesize;
127     int      sub_packet_h;
128     int      frame_size;
129     int      sub_packet_size;
130     int      sub_packet_cnt;
131     int      pkt_cnt;
132     uint64_t buf_timecode;
133     uint8_t *buf;
134 } MatroskaTrackAudio;
135
136 typedef struct {
137     uint64_t num;
138     uint64_t uid;
139     uint64_t type;
140     char    *name;
141     char    *codec_id;
142     EbmlBin  codec_priv;
143     char    *language;
144     double time_scale;
145     uint64_t default_duration;
146     uint64_t flag_default;
147     uint64_t flag_forced;
148     MatroskaTrackVideo video;
149     MatroskaTrackAudio audio;
150     EbmlList encodings;
151
152     AVStream *stream;
153     int64_t end_timecode;
154     int ms_compat;
155 } MatroskaTrack;
156
157 typedef struct {
158     uint64_t uid;
159     char *filename;
160     char *mime;
161     EbmlBin bin;
162
163     AVStream *stream;
164 } MatroskaAttachement;
165
166 typedef struct {
167     uint64_t start;
168     uint64_t end;
169     uint64_t uid;
170     char    *title;
171
172     AVChapter *chapter;
173 } MatroskaChapter;
174
175 typedef struct {
176     uint64_t track;
177     uint64_t pos;
178 } MatroskaIndexPos;
179
180 typedef struct {
181     uint64_t time;
182     EbmlList pos;
183 } MatroskaIndex;
184
185 typedef struct {
186     char *name;
187     char *string;
188     char *lang;
189     uint64_t def;
190     EbmlList sub;
191 } MatroskaTag;
192
193 typedef struct {
194     char    *type;
195     uint64_t typevalue;
196     uint64_t trackuid;
197     uint64_t chapteruid;
198     uint64_t attachuid;
199 } MatroskaTagTarget;
200
201 typedef struct {
202     MatroskaTagTarget target;
203     EbmlList tag;
204 } MatroskaTags;
205
206 typedef struct {
207     uint64_t id;
208     uint64_t pos;
209 } MatroskaSeekhead;
210
211 typedef struct {
212     uint64_t start;
213     uint64_t length;
214 } MatroskaLevel;
215
216 typedef struct {
217     uint64_t timecode;
218     EbmlList blocks;
219 } MatroskaCluster;
220
221 typedef struct {
222     AVFormatContext *ctx;
223
224     /* EBML stuff */
225     int num_levels;
226     MatroskaLevel levels[EBML_MAX_DEPTH];
227     int level_up;
228     uint32_t current_id;
229
230     uint64_t time_scale;
231     double   duration;
232     char    *title;
233     EbmlList tracks;
234     EbmlList attachments;
235     EbmlList chapters;
236     EbmlList index;
237     EbmlList tags;
238     EbmlList seekhead;
239
240     /* byte position of the segment inside the stream */
241     int64_t segment_start;
242
243     /* the packet queue */
244     AVPacket **packets;
245     int num_packets;
246     AVPacket *prev_pkt;
247
248     int done;
249
250     /* What to skip before effectively reading a packet. */
251     int skip_to_keyframe;
252     uint64_t skip_to_timecode;
253
254     /* File has a CUES element, but we defer parsing until it is needed. */
255     int cues_parsing_deferred;
256
257     int current_cluster_num_blocks;
258     int64_t current_cluster_pos;
259     MatroskaCluster current_cluster;
260
261     /* File has SSA subtitles which prevent incremental cluster parsing. */
262     int contains_ssa;
263 } MatroskaDemuxContext;
264
265 typedef struct {
266     uint64_t duration;
267     int64_t  reference;
268     uint64_t non_simple;
269     EbmlBin  bin;
270 } MatroskaBlock;
271
272 static EbmlSyntax ebml_header[] = {
273     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
274     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
275     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
276     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
277     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
278     { EBML_ID_EBMLVERSION,            EBML_NONE },
279     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
280     { 0 }
281 };
282
283 static EbmlSyntax ebml_syntax[] = {
284     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
285     { 0 }
286 };
287
288 static EbmlSyntax matroska_info[] = {
289     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
290     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
291     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
292     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
293     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
294     { MATROSKA_ID_DATEUTC,            EBML_NONE },
295     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
296     { 0 }
297 };
298
299 static EbmlSyntax matroska_track_video[] = {
300     { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
301     { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
302     { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
303     { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
304     { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
305     { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
306     { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
307     { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
308     { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
309     { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
310     { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
311     { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
312     { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
313     { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
314     { 0 }
315 };
316
317 static EbmlSyntax matroska_track_audio[] = {
318     { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
319     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
320     { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
321     { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
322     { 0 }
323 };
324
325 static EbmlSyntax matroska_track_encoding_compression[] = {
326     { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
327     { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
328     { 0 }
329 };
330
331 static EbmlSyntax matroska_track_encoding[] = {
332     { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
333     { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
334     { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
335     { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
336     { 0 }
337 };
338
339 static EbmlSyntax matroska_track_encodings[] = {
340     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
341     { 0 }
342 };
343
344 static EbmlSyntax matroska_track[] = {
345     { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
346     { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
347     { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
348     { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
349     { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
350     { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
351     { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
352     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
353     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
354     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
355     { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
356     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
357     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
358     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
359     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
360     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
361     { MATROSKA_ID_CODECNAME,            EBML_NONE },
362     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
363     { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
364     { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
365     { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
366     { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
367     { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
368     { 0 }
369 };
370
371 static EbmlSyntax matroska_tracks[] = {
372     { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
373     { 0 }
374 };
375
376 static EbmlSyntax matroska_attachment[] = {
377     { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
378     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
379     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
380     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
381     { MATROSKA_ID_FILEDESC,           EBML_NONE },
382     { 0 }
383 };
384
385 static EbmlSyntax matroska_attachments[] = {
386     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
387     { 0 }
388 };
389
390 static EbmlSyntax matroska_chapter_display[] = {
391     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
392     { MATROSKA_ID_CHAPLANG,           EBML_NONE },
393     { 0 }
394 };
395
396 static EbmlSyntax matroska_chapter_entry[] = {
397     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
398     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
399     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
400     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
401     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
402     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
403     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
404     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
405     { 0 }
406 };
407
408 static EbmlSyntax matroska_chapter[] = {
409     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
410     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
411     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
412     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
413     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
414     { 0 }
415 };
416
417 static EbmlSyntax matroska_chapters[] = {
418     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
419     { 0 }
420 };
421
422 static EbmlSyntax matroska_index_pos[] = {
423     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
424     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
425     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
426     { 0 }
427 };
428
429 static EbmlSyntax matroska_index_entry[] = {
430     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
431     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
432     { 0 }
433 };
434
435 static EbmlSyntax matroska_index[] = {
436     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
437     { 0 }
438 };
439
440 static EbmlSyntax matroska_simpletag[] = {
441     { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
442     { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
443     { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
444     { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
445     { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
446     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
447     { 0 }
448 };
449
450 static EbmlSyntax matroska_tagtargets[] = {
451     { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
452     { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
453     { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
454     { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
455     { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
456     { 0 }
457 };
458
459 static EbmlSyntax matroska_tag[] = {
460     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
461     { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
462     { 0 }
463 };
464
465 static EbmlSyntax matroska_tags[] = {
466     { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
467     { 0 }
468 };
469
470 static EbmlSyntax matroska_seekhead_entry[] = {
471     { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
472     { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
473     { 0 }
474 };
475
476 static EbmlSyntax matroska_seekhead[] = {
477     { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
478     { 0 }
479 };
480
481 static EbmlSyntax matroska_segment[] = {
482     { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
483     { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
484     { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
485     { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
486     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
487     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
488     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
489     { MATROSKA_ID_CLUSTER,        EBML_STOP },
490     { 0 }
491 };
492
493 static EbmlSyntax matroska_segments[] = {
494     { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
495     { 0 }
496 };
497
498 static EbmlSyntax matroska_blockgroup[] = {
499     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
500     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
501     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
502     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
503     { MATROSKA_ID_CODECSTATE,     EBML_NONE },
504     { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
505     { 0 }
506 };
507
508 static EbmlSyntax matroska_cluster[] = {
509     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
510     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
511     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
512     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
513     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
514     { 0 }
515 };
516
517 static EbmlSyntax matroska_clusters[] = {
518     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
519     { MATROSKA_ID_INFO,           EBML_NONE },
520     { MATROSKA_ID_CUES,           EBML_NONE },
521     { MATROSKA_ID_TAGS,           EBML_NONE },
522     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
523     { 0 }
524 };
525
526 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
527     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
528     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
529     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
530     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
531     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
532     { MATROSKA_ID_INFO,           EBML_NONE },
533     { MATROSKA_ID_CUES,           EBML_NONE },
534     { MATROSKA_ID_TAGS,           EBML_NONE },
535     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
536     { MATROSKA_ID_CLUSTER,        EBML_STOP },
537     { 0 }
538 };
539
540 static EbmlSyntax matroska_cluster_incremental[] = {
541     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
542     { MATROSKA_ID_BLOCKGROUP,     EBML_STOP },
543     { MATROSKA_ID_SIMPLEBLOCK,    EBML_STOP },
544     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
545     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
546     { 0 }
547 };
548
549 static EbmlSyntax matroska_clusters_incremental[] = {
550     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
551     { MATROSKA_ID_INFO,           EBML_NONE },
552     { MATROSKA_ID_CUES,           EBML_NONE },
553     { MATROSKA_ID_TAGS,           EBML_NONE },
554     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
555     { 0 }
556 };
557
558 static const char *const matroska_doctypes[] = { "matroska", "webm" };
559
560 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
561 {
562     AVIOContext *pb = matroska->ctx->pb;
563     uint32_t id;
564     matroska->current_id = 0;
565     matroska->num_levels = 0;
566
567     /* seek to next position to resync from */
568     if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
569         goto eof;
570
571     id = avio_rb32(pb);
572
573     // try to find a toplevel element
574     while (!pb->eof_reached) {
575         if (id == MATROSKA_ID_INFO     || id == MATROSKA_ID_TRACKS      ||
576             id == MATROSKA_ID_CUES     || id == MATROSKA_ID_TAGS        ||
577             id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
578             id == MATROSKA_ID_CLUSTER  || id == MATROSKA_ID_CHAPTERS) {
579                 matroska->current_id = id;
580                 return 0;
581         }
582         id = (id << 8) | avio_r8(pb);
583     }
584 eof:
585     matroska->done = 1;
586     return AVERROR_EOF;
587 }
588
589 /*
590  * Return: Whether we reached the end of a level in the hierarchy or not.
591  */
592 static int ebml_level_end(MatroskaDemuxContext *matroska)
593 {
594     AVIOContext *pb = matroska->ctx->pb;
595     int64_t pos = avio_tell(pb);
596
597     if (matroska->num_levels > 0) {
598         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
599         if (pos - level->start >= level->length || matroska->current_id) {
600             matroska->num_levels--;
601             return 1;
602         }
603     }
604     return 0;
605 }
606
607 /*
608  * Read: an "EBML number", which is defined as a variable-length
609  * array of bytes. The first byte indicates the length by giving a
610  * number of 0-bits followed by a one. The position of the first
611  * "one" bit inside the first byte indicates the length of this
612  * number.
613  * Returns: number of bytes read, < 0 on error
614  */
615 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
616                          int max_size, uint64_t *number)
617 {
618     int read = 1, n = 1;
619     uint64_t total = 0;
620
621     /* The first byte tells us the length in bytes - avio_r8() can normally
622      * return 0, but since that's not a valid first ebmlID byte, we can
623      * use it safely here to catch EOS. */
624     if (!(total = avio_r8(pb))) {
625         /* we might encounter EOS here */
626         if (!pb->eof_reached) {
627             int64_t pos = avio_tell(pb);
628             av_log(matroska->ctx, AV_LOG_ERROR,
629                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
630                    pos, pos);
631             return pb->error ? pb->error : AVERROR(EIO);
632         }
633         return AVERROR_EOF;
634     }
635
636     /* get the length of the EBML number */
637     read = 8 - ff_log2_tab[total];
638     if (read > max_size) {
639         int64_t pos = avio_tell(pb) - 1;
640         av_log(matroska->ctx, AV_LOG_ERROR,
641                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
642                (uint8_t) total, pos, pos);
643         return AVERROR_INVALIDDATA;
644     }
645
646     /* read out length */
647     total ^= 1 << ff_log2_tab[total];
648     while (n++ < read)
649         total = (total << 8) | avio_r8(pb);
650
651     *number = total;
652
653     return read;
654 }
655
656 /**
657  * Read a EBML length value.
658  * This needs special handling for the "unknown length" case which has multiple
659  * encodings.
660  */
661 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
662                             uint64_t *number)
663 {
664     int res = ebml_read_num(matroska, pb, 8, number);
665     if (res > 0 && *number + 1 == 1ULL << (7 * res))
666         *number = 0xffffffffffffffULL;
667     return res;
668 }
669
670 /*
671  * Read the next element as an unsigned int.
672  * 0 is success, < 0 is failure.
673  */
674 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
675 {
676     int n = 0;
677
678     if (size > 8)
679         return AVERROR_INVALIDDATA;
680
681     /* big-endian ordering; build up number */
682     *num = 0;
683     while (n++ < size)
684         *num = (*num << 8) | avio_r8(pb);
685
686     return 0;
687 }
688
689 /*
690  * Read the next element as a float.
691  * 0 is success, < 0 is failure.
692  */
693 static int ebml_read_float(AVIOContext *pb, int size, double *num)
694 {
695     if (size == 0) {
696         *num = 0;
697     } else if (size == 4) {
698         *num = av_int2float(avio_rb32(pb));
699     } else if (size == 8){
700         *num = av_int2double(avio_rb64(pb));
701     } else
702         return AVERROR_INVALIDDATA;
703
704     return 0;
705 }
706
707 /*
708  * Read the next element as an ASCII string.
709  * 0 is success, < 0 is failure.
710  */
711 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
712 {
713     char *res;
714
715     /* EBML strings are usually not 0-terminated, so we allocate one
716      * byte more, read the string and NULL-terminate it ourselves. */
717     if (!(res = av_malloc(size + 1)))
718         return AVERROR(ENOMEM);
719     if (avio_read(pb, (uint8_t *) res, size) != size) {
720         av_free(res);
721         return AVERROR(EIO);
722     }
723     (res)[size] = '\0';
724     av_free(*str);
725     *str = res;
726
727     return 0;
728 }
729
730 /*
731  * Read the next element as binary data.
732  * 0 is success, < 0 is failure.
733  */
734 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
735 {
736     av_free(bin->data);
737     if (!(bin->data = av_malloc(length)))
738         return AVERROR(ENOMEM);
739
740     bin->size = length;
741     bin->pos  = avio_tell(pb);
742     if (avio_read(pb, bin->data, length) != length) {
743         av_freep(&bin->data);
744         return AVERROR(EIO);
745     }
746
747     return 0;
748 }
749
750 /*
751  * Read the next element, but only the header. The contents
752  * are supposed to be sub-elements which can be read separately.
753  * 0 is success, < 0 is failure.
754  */
755 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
756 {
757     AVIOContext *pb = matroska->ctx->pb;
758     MatroskaLevel *level;
759
760     if (matroska->num_levels >= EBML_MAX_DEPTH) {
761         av_log(matroska->ctx, AV_LOG_ERROR,
762                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
763         return AVERROR(ENOSYS);
764     }
765
766     level = &matroska->levels[matroska->num_levels++];
767     level->start = avio_tell(pb);
768     level->length = length;
769
770     return 0;
771 }
772
773 /*
774  * Read signed/unsigned "EBML" numbers.
775  * Return: number of bytes processed, < 0 on error
776  */
777 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
778                                  uint8_t *data, uint32_t size, uint64_t *num)
779 {
780     AVIOContext pb;
781     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
782     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
783 }
784
785 /*
786  * Same as above, but signed.
787  */
788 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
789                                  uint8_t *data, uint32_t size, int64_t *num)
790 {
791     uint64_t unum;
792     int res;
793
794     /* read as unsigned number first */
795     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
796         return res;
797
798     /* make signed (weird way) */
799     *num = unum - ((1LL << (7*res - 1)) - 1);
800
801     return res;
802 }
803
804 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
805                            EbmlSyntax *syntax, void *data);
806
807 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
808                          uint32_t id, void *data)
809 {
810     int i;
811     for (i=0; syntax[i].id; i++)
812         if (id == syntax[i].id)
813             break;
814     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
815         matroska->num_levels > 0 &&
816         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
817         return 0;  // we reached the end of an unknown size cluster
818     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
819         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
820         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
821             return AVERROR_INVALIDDATA;
822     }
823     return ebml_parse_elem(matroska, &syntax[i], data);
824 }
825
826 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
827                       void *data)
828 {
829     if (!matroska->current_id) {
830         uint64_t id;
831         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
832         if (res < 0)
833             return res;
834         matroska->current_id = id | 1 << 7*res;
835     }
836     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
837 }
838
839 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
840                            void *data)
841 {
842     int i, res = 0;
843
844     for (i=0; syntax[i].id; i++)
845         switch (syntax[i].type) {
846         case EBML_UINT:
847             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
848             break;
849         case EBML_FLOAT:
850             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
851             break;
852         case EBML_STR:
853         case EBML_UTF8:
854             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
855             break;
856         }
857
858     while (!res && !ebml_level_end(matroska))
859         res = ebml_parse(matroska, syntax, data);
860
861     return res;
862 }
863
864 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
865                            EbmlSyntax *syntax, void *data)
866 {
867     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
868         [EBML_UINT]  = 8,
869         [EBML_FLOAT] = 8,
870         // max. 16 MB for strings
871         [EBML_STR]   = 0x1000000,
872         [EBML_UTF8]  = 0x1000000,
873         // max. 256 MB for binary data
874         [EBML_BIN]   = 0x10000000,
875         // no limits for anything else
876     };
877     AVIOContext *pb = matroska->ctx->pb;
878     uint32_t id = syntax->id;
879     uint64_t length;
880     int res;
881     void *newelem;
882
883     data = (char *)data + syntax->data_offset;
884     if (syntax->list_elem_size) {
885         EbmlList *list = data;
886         newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
887         if (!newelem)
888             return AVERROR(ENOMEM);
889         list->elem = newelem;
890         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
891         memset(data, 0, syntax->list_elem_size);
892         list->nb_elem++;
893     }
894
895     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
896         matroska->current_id = 0;
897         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
898             return res;
899         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
900             av_log(matroska->ctx, AV_LOG_ERROR,
901                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
902                    length, max_lengths[syntax->type], syntax->type);
903             return AVERROR_INVALIDDATA;
904         }
905     }
906
907     switch (syntax->type) {
908     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
909     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
910     case EBML_STR:
911     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
912     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
913     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
914                          return res;
915                      if (id == MATROSKA_ID_SEGMENT)
916                          matroska->segment_start = avio_tell(matroska->ctx->pb);
917                      return ebml_parse_nest(matroska, syntax->def.n, data);
918     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
919     case EBML_STOP:  return 1;
920     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
921     }
922     if (res == AVERROR_INVALIDDATA)
923         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
924     else if (res == AVERROR(EIO))
925         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
926     return res;
927 }
928
929 static void ebml_free(EbmlSyntax *syntax, void *data)
930 {
931     int i, j;
932     for (i=0; syntax[i].id; i++) {
933         void *data_off = (char *)data + syntax[i].data_offset;
934         switch (syntax[i].type) {
935         case EBML_STR:
936         case EBML_UTF8:  av_freep(data_off);                      break;
937         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
938         case EBML_NEST:
939             if (syntax[i].list_elem_size) {
940                 EbmlList *list = data_off;
941                 char *ptr = list->elem;
942                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
943                     ebml_free(syntax[i].def.n, ptr);
944                 av_free(list->elem);
945             } else
946                 ebml_free(syntax[i].def.n, data_off);
947         default:  break;
948         }
949     }
950 }
951
952
953 /*
954  * Autodetecting...
955  */
956 static int matroska_probe(AVProbeData *p)
957 {
958     uint64_t total = 0;
959     int len_mask = 0x80, size = 1, n = 1, i;
960
961     /* EBML header? */
962     if (AV_RB32(p->buf) != EBML_ID_HEADER)
963         return 0;
964
965     /* length of header */
966     total = p->buf[4];
967     while (size <= 8 && !(total & len_mask)) {
968         size++;
969         len_mask >>= 1;
970     }
971     if (size > 8)
972       return 0;
973     total &= (len_mask - 1);
974     while (n < size)
975         total = (total << 8) | p->buf[4 + n++];
976
977     /* Does the probe data contain the whole header? */
978     if (p->buf_size < 4 + size + total)
979       return 0;
980
981     /* The header should contain a known document type. For now,
982      * we don't parse the whole header but simply check for the
983      * availability of that array of characters inside the header.
984      * Not fully fool-proof, but good enough. */
985     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
986         int probelen = strlen(matroska_doctypes[i]);
987         if (total < probelen)
988             continue;
989         for (n = 4+size; n <= 4+size+total-probelen; n++)
990             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
991                 return AVPROBE_SCORE_MAX;
992     }
993
994     // probably valid EBML header but no recognized doctype
995     return AVPROBE_SCORE_EXTENSION;
996 }
997
998 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
999                                                  int num)
1000 {
1001     MatroskaTrack *tracks = matroska->tracks.elem;
1002     int i;
1003
1004     for (i=0; i < matroska->tracks.nb_elem; i++)
1005         if (tracks[i].num == num)
1006             return &tracks[i];
1007
1008     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1009     return NULL;
1010 }
1011
1012 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1013                                   MatroskaTrack *track)
1014 {
1015     MatroskaTrackEncoding *encodings = track->encodings.elem;
1016     uint8_t* data = *buf;
1017     int isize = *buf_size;
1018     uint8_t* pkt_data = NULL;
1019     uint8_t av_unused *newpktdata;
1020     int pkt_size = isize;
1021     int result = 0;
1022     int olen;
1023
1024     if (pkt_size >= 10000000)
1025         return AVERROR_INVALIDDATA;
1026
1027     switch (encodings[0].compression.algo) {
1028     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
1029         int header_size = encodings[0].compression.settings.size;
1030         uint8_t *header = encodings[0].compression.settings.data;
1031
1032         if (!header_size)
1033             return 0;
1034
1035         pkt_size = isize + header_size;
1036         pkt_data = av_malloc(pkt_size);
1037         if (!pkt_data)
1038             return AVERROR(ENOMEM);
1039
1040         memcpy(pkt_data, header, header_size);
1041         memcpy(pkt_data + header_size, data, isize);
1042         break;
1043     }
1044 #if CONFIG_LZO
1045     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1046         do {
1047             olen = pkt_size *= 3;
1048             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1049             if (!newpktdata) {
1050                 result = AVERROR(ENOMEM);
1051                 goto failed;
1052             }
1053             pkt_data = newpktdata;
1054             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1055         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1056         if (result) {
1057             result = AVERROR_INVALIDDATA;
1058             goto failed;
1059         }
1060         pkt_size -= olen;
1061         break;
1062 #endif
1063 #if CONFIG_ZLIB
1064     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1065         z_stream zstream = {0};
1066         if (inflateInit(&zstream) != Z_OK)
1067             return -1;
1068         zstream.next_in = data;
1069         zstream.avail_in = isize;
1070         do {
1071             pkt_size *= 3;
1072             newpktdata = av_realloc(pkt_data, pkt_size);
1073             if (!newpktdata) {
1074                 inflateEnd(&zstream);
1075                 goto failed;
1076             }
1077             pkt_data = newpktdata;
1078             zstream.avail_out = pkt_size - zstream.total_out;
1079             zstream.next_out = pkt_data + zstream.total_out;
1080             result = inflate(&zstream, Z_NO_FLUSH);
1081         } while (result==Z_OK && pkt_size<10000000);
1082         pkt_size = zstream.total_out;
1083         inflateEnd(&zstream);
1084         if (result != Z_STREAM_END) {
1085             if (result == Z_MEM_ERROR)
1086                 result = AVERROR(ENOMEM);
1087             else
1088                 result = AVERROR_INVALIDDATA;
1089             goto failed;
1090         }
1091         break;
1092     }
1093 #endif
1094 #if CONFIG_BZLIB
1095     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1096         bz_stream bzstream = {0};
1097         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1098             return -1;
1099         bzstream.next_in = data;
1100         bzstream.avail_in = isize;
1101         do {
1102             pkt_size *= 3;
1103             newpktdata = av_realloc(pkt_data, pkt_size);
1104             if (!newpktdata) {
1105                 BZ2_bzDecompressEnd(&bzstream);
1106                 goto failed;
1107             }
1108             pkt_data = newpktdata;
1109             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1110             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1111             result = BZ2_bzDecompress(&bzstream);
1112         } while (result==BZ_OK && pkt_size<10000000);
1113         pkt_size = bzstream.total_out_lo32;
1114         BZ2_bzDecompressEnd(&bzstream);
1115         if (result != BZ_STREAM_END) {
1116             if (result == BZ_MEM_ERROR)
1117                 result = AVERROR(ENOMEM);
1118             else
1119                 result = AVERROR_INVALIDDATA;
1120             goto failed;
1121         }
1122         break;
1123     }
1124 #endif
1125     default:
1126         return AVERROR_INVALIDDATA;
1127     }
1128
1129     *buf = pkt_data;
1130     *buf_size = pkt_size;
1131     return 0;
1132  failed:
1133     av_free(pkt_data);
1134     return result;
1135 }
1136
1137 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1138                                     AVPacket *pkt, uint64_t display_duration)
1139 {
1140     AVBufferRef *line;
1141     char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1142     for (; *ptr!=',' && ptr<end-1; ptr++);
1143     if (*ptr == ',')
1144         layer = ++ptr;
1145     for (; *ptr!=',' && ptr<end-1; ptr++);
1146     if (*ptr == ',') {
1147         int64_t end_pts = pkt->pts + display_duration;
1148         int sc = matroska->time_scale * pkt->pts / 10000000;
1149         int ec = matroska->time_scale * end_pts  / 10000000;
1150         int sh, sm, ss, eh, em, es, len;
1151         sh = sc/360000;  sc -= 360000*sh;
1152         sm = sc/  6000;  sc -=   6000*sm;
1153         ss = sc/   100;  sc -=    100*ss;
1154         eh = ec/360000;  ec -= 360000*eh;
1155         em = ec/  6000;  ec -=   6000*em;
1156         es = ec/   100;  ec -=    100*es;
1157         *ptr++ = '\0';
1158         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1159         if (!(line = av_buffer_alloc(len)))
1160             return;
1161         snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1162                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1163         av_buffer_unref(&pkt->buf);
1164         pkt->buf  = line;
1165         pkt->data = line->data;
1166         pkt->size = strlen(line->data);
1167     }
1168 }
1169
1170 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1171 {
1172     int old_size = out->size;
1173     int ret = av_grow_packet(out, in->size);
1174     if (ret < 0)
1175         return ret;
1176
1177     memcpy(out->data + old_size, in->data, in->size);
1178
1179     av_free_packet(in);
1180     av_free(in);
1181     return 0;
1182 }
1183
1184 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1185                                  AVDictionary **metadata, char *prefix)
1186 {
1187     MatroskaTag *tags = list->elem;
1188     char key[1024];
1189     int i;
1190
1191     for (i=0; i < list->nb_elem; i++) {
1192         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1193
1194         if (!tags[i].name) {
1195             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1196             continue;
1197         }
1198         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1199         else         av_strlcpy(key, tags[i].name, sizeof(key));
1200         if (tags[i].def || !lang) {
1201         av_dict_set(metadata, key, tags[i].string, 0);
1202         if (tags[i].sub.nb_elem)
1203             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1204         }
1205         if (lang) {
1206             av_strlcat(key, "-", sizeof(key));
1207             av_strlcat(key, lang, sizeof(key));
1208             av_dict_set(metadata, key, tags[i].string, 0);
1209             if (tags[i].sub.nb_elem)
1210                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1211         }
1212     }
1213     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1214 }
1215
1216 static void matroska_convert_tags(AVFormatContext *s)
1217 {
1218     MatroskaDemuxContext *matroska = s->priv_data;
1219     MatroskaTags *tags = matroska->tags.elem;
1220     int i, j;
1221
1222     for (i=0; i < matroska->tags.nb_elem; i++) {
1223         if (tags[i].target.attachuid) {
1224             MatroskaAttachement *attachment = matroska->attachments.elem;
1225             for (j=0; j<matroska->attachments.nb_elem; j++)
1226                 if (attachment[j].uid == tags[i].target.attachuid
1227                     && attachment[j].stream)
1228                     matroska_convert_tag(s, &tags[i].tag,
1229                                          &attachment[j].stream->metadata, NULL);
1230         } else if (tags[i].target.chapteruid) {
1231             MatroskaChapter *chapter = matroska->chapters.elem;
1232             for (j=0; j<matroska->chapters.nb_elem; j++)
1233                 if (chapter[j].uid == tags[i].target.chapteruid
1234                     && chapter[j].chapter)
1235                     matroska_convert_tag(s, &tags[i].tag,
1236                                          &chapter[j].chapter->metadata, NULL);
1237         } else if (tags[i].target.trackuid) {
1238             MatroskaTrack *track = matroska->tracks.elem;
1239             for (j=0; j<matroska->tracks.nb_elem; j++)
1240                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1241                     matroska_convert_tag(s, &tags[i].tag,
1242                                          &track[j].stream->metadata, NULL);
1243         } else {
1244             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1245                                  tags[i].target.type);
1246         }
1247     }
1248 }
1249
1250 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1251 {
1252     EbmlList *seekhead_list = &matroska->seekhead;
1253     MatroskaSeekhead *seekhead = seekhead_list->elem;
1254     uint32_t level_up = matroska->level_up;
1255     int64_t before_pos = avio_tell(matroska->ctx->pb);
1256     uint32_t saved_id = matroska->current_id;
1257     MatroskaLevel level;
1258     int64_t offset;
1259     int ret = 0;
1260
1261     if (idx >= seekhead_list->nb_elem
1262             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1263             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1264         return 0;
1265
1266     /* seek */
1267     offset = seekhead[idx].pos + matroska->segment_start;
1268     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1269         /* We don't want to lose our seekhead level, so we add
1270          * a dummy. This is a crude hack. */
1271         if (matroska->num_levels == EBML_MAX_DEPTH) {
1272             av_log(matroska->ctx, AV_LOG_INFO,
1273                    "Max EBML element depth (%d) reached, "
1274                    "cannot parse further.\n", EBML_MAX_DEPTH);
1275             ret = AVERROR_INVALIDDATA;
1276         } else {
1277             level.start = 0;
1278             level.length = (uint64_t)-1;
1279             matroska->levels[matroska->num_levels] = level;
1280             matroska->num_levels++;
1281             matroska->current_id = 0;
1282
1283             ret = ebml_parse(matroska, matroska_segment, matroska);
1284
1285             /* remove dummy level */
1286             while (matroska->num_levels) {
1287                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1288                 if (length == (uint64_t)-1)
1289                     break;
1290             }
1291         }
1292     }
1293     /* seek back */
1294     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1295     matroska->level_up = level_up;
1296     matroska->current_id = saved_id;
1297
1298     return ret;
1299 }
1300
1301 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1302 {
1303     EbmlList *seekhead_list = &matroska->seekhead;
1304     int64_t before_pos = avio_tell(matroska->ctx->pb);
1305     int i;
1306
1307     // we should not do any seeking in the streaming case
1308     if (!matroska->ctx->pb->seekable ||
1309         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1310         return;
1311
1312     for (i = 0; i < seekhead_list->nb_elem; i++) {
1313         MatroskaSeekhead *seekhead = seekhead_list->elem;
1314         if (seekhead[i].pos <= before_pos)
1315             continue;
1316
1317         // defer cues parsing until we actually need cue data.
1318         if (seekhead[i].id == MATROSKA_ID_CUES) {
1319             matroska->cues_parsing_deferred = 1;
1320             continue;
1321         }
1322
1323         if (matroska_parse_seekhead_entry(matroska, i) < 0)
1324             break;
1325     }
1326 }
1327
1328 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1329     EbmlList *seekhead_list = &matroska->seekhead;
1330     MatroskaSeekhead *seekhead = seekhead_list->elem;
1331     EbmlList *index_list;
1332     MatroskaIndex *index;
1333     int index_scale = 1;
1334     int i, j;
1335
1336     for (i = 0; i < seekhead_list->nb_elem; i++)
1337         if (seekhead[i].id == MATROSKA_ID_CUES)
1338             break;
1339     assert(i <= seekhead_list->nb_elem);
1340
1341     matroska_parse_seekhead_entry(matroska, i);
1342
1343     index_list = &matroska->index;
1344     index = index_list->elem;
1345     if (index_list->nb_elem
1346         && index[0].time > 1E14/matroska->time_scale) {
1347         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1348         index_scale = matroska->time_scale;
1349     }
1350     for (i = 0; i < index_list->nb_elem; i++) {
1351         EbmlList *pos_list = &index[i].pos;
1352         MatroskaIndexPos *pos = pos_list->elem;
1353         for (j = 0; j < pos_list->nb_elem; j++) {
1354             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1355             if (track && track->stream)
1356                 av_add_index_entry(track->stream,
1357                                    pos[j].pos + matroska->segment_start,
1358                                    index[i].time/index_scale, 0, 0,
1359                                    AVINDEX_KEYFRAME);
1360         }
1361     }
1362 }
1363
1364 static int matroska_aac_profile(char *codec_id)
1365 {
1366     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1367     int profile;
1368
1369     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1370         if (strstr(codec_id, aac_profiles[profile]))
1371             break;
1372     return profile + 1;
1373 }
1374
1375 static int matroska_aac_sri(int samplerate)
1376 {
1377     int sri;
1378
1379     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1380         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1381             break;
1382     return sri;
1383 }
1384
1385 static int matroska_read_header(AVFormatContext *s)
1386 {
1387     MatroskaDemuxContext *matroska = s->priv_data;
1388     EbmlList *attachements_list = &matroska->attachments;
1389     MatroskaAttachement *attachements;
1390     EbmlList *chapters_list = &matroska->chapters;
1391     MatroskaChapter *chapters;
1392     MatroskaTrack *tracks;
1393     uint64_t max_start = 0;
1394     int64_t pos;
1395     Ebml ebml = { 0 };
1396     AVStream *st;
1397     int i, j, res;
1398
1399     matroska->ctx = s;
1400
1401     /* First read the EBML header. */
1402     if (ebml_parse(matroska, ebml_syntax, &ebml)
1403         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1404         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1405         av_log(matroska->ctx, AV_LOG_ERROR,
1406                "EBML header using unsupported features\n"
1407                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1408                ebml.version, ebml.doctype, ebml.doctype_version);
1409         ebml_free(ebml_syntax, &ebml);
1410         return AVERROR_PATCHWELCOME;
1411     }
1412     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1413         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1414             break;
1415     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1416         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1417         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1418             ebml_free(ebml_syntax, &ebml);
1419             return AVERROR_INVALIDDATA;
1420         }
1421     }
1422     ebml_free(ebml_syntax, &ebml);
1423
1424     /* The next thing is a segment. */
1425     pos = avio_tell(matroska->ctx->pb);
1426     res = ebml_parse(matroska, matroska_segments, matroska);
1427     // try resyncing until we find a EBML_STOP type element.
1428     while (res != 1) {
1429         res = matroska_resync(matroska, pos);
1430         if (res < 0)
1431             return res;
1432         pos = avio_tell(matroska->ctx->pb);
1433         res = ebml_parse(matroska, matroska_segment, matroska);
1434     }
1435     matroska_execute_seekhead(matroska);
1436
1437     if (!matroska->time_scale)
1438         matroska->time_scale = 1000000;
1439     if (matroska->duration)
1440         matroska->ctx->duration = matroska->duration * matroska->time_scale
1441                                   * 1000 / AV_TIME_BASE;
1442     av_dict_set(&s->metadata, "title", matroska->title, 0);
1443
1444     tracks = matroska->tracks.elem;
1445     for (i=0; i < matroska->tracks.nb_elem; i++) {
1446         MatroskaTrack *track = &tracks[i];
1447         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1448         EbmlList *encodings_list = &tracks->encodings;
1449         MatroskaTrackEncoding *encodings = encodings_list->elem;
1450         uint8_t *extradata = NULL;
1451         int extradata_size = 0;
1452         int extradata_offset = 0;
1453         AVIOContext b;
1454
1455         /* Apply some sanity checks. */
1456         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1457             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1458             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1459             av_log(matroska->ctx, AV_LOG_INFO,
1460                    "Unknown or unsupported track type %"PRIu64"\n",
1461                    track->type);
1462             continue;
1463         }
1464         if (track->codec_id == NULL)
1465             continue;
1466
1467         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1468             if (!track->default_duration && track->video.frame_rate > 0)
1469                 track->default_duration = 1000000000/track->video.frame_rate;
1470             if (!track->video.display_width)
1471                 track->video.display_width = track->video.pixel_width;
1472             if (!track->video.display_height)
1473                 track->video.display_height = track->video.pixel_height;
1474         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1475             if (!track->audio.out_samplerate)
1476                 track->audio.out_samplerate = track->audio.samplerate;
1477         }
1478         if (encodings_list->nb_elem > 1) {
1479             av_log(matroska->ctx, AV_LOG_ERROR,
1480                    "Multiple combined encodings not supported");
1481         } else if (encodings_list->nb_elem == 1) {
1482             if (encodings[0].type ||
1483                 (
1484 #if CONFIG_ZLIB
1485                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1486 #endif
1487 #if CONFIG_BZLIB
1488                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1489 #endif
1490 #if CONFIG_LZO
1491                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1492 #endif
1493                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1494                 encodings[0].scope = 0;
1495                 av_log(matroska->ctx, AV_LOG_ERROR,
1496                        "Unsupported encoding type");
1497             } else if (track->codec_priv.size && encodings[0].scope&2) {
1498                 uint8_t *codec_priv = track->codec_priv.data;
1499                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1500                                                  &track->codec_priv.size,
1501                                                  track);
1502                 if (ret < 0) {
1503                     track->codec_priv.data = NULL;
1504                     track->codec_priv.size = 0;
1505                     av_log(matroska->ctx, AV_LOG_ERROR,
1506                            "Failed to decode codec private data\n");
1507                 }
1508
1509                 if (codec_priv != track->codec_priv.data)
1510                     av_free(codec_priv);
1511             }
1512         }
1513
1514         for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1515             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1516                         strlen(ff_mkv_codec_tags[j].str))){
1517                 codec_id= ff_mkv_codec_tags[j].id;
1518                 break;
1519             }
1520         }
1521
1522         st = track->stream = avformat_new_stream(s, NULL);
1523         if (st == NULL)
1524             return AVERROR(ENOMEM);
1525
1526         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1527             && track->codec_priv.size >= 40
1528             && track->codec_priv.data != NULL) {
1529             track->ms_compat = 1;
1530             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1531             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1532             extradata_offset = 40;
1533         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1534                    && track->codec_priv.size >= 14
1535                    && track->codec_priv.data != NULL) {
1536             int ret;
1537             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1538                               0, NULL, NULL, NULL, NULL);
1539             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1540             if (ret < 0)
1541                 return ret;
1542             codec_id = st->codec->codec_id;
1543             extradata_offset = FFMIN(track->codec_priv.size, 18);
1544         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1545                    && (track->codec_priv.size >= 86)
1546                    && (track->codec_priv.data != NULL)) {
1547             track->video.fourcc = AV_RL32(track->codec_priv.data);
1548             codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
1549         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1550             switch (track->audio.bitdepth) {
1551             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1552             case 24:  codec_id = AV_CODEC_ID_PCM_S24BE;  break;
1553             case 32:  codec_id = AV_CODEC_ID_PCM_S32BE;  break;
1554             }
1555         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1556             switch (track->audio.bitdepth) {
1557             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1558             case 24:  codec_id = AV_CODEC_ID_PCM_S24LE;  break;
1559             case 32:  codec_id = AV_CODEC_ID_PCM_S32LE;  break;
1560             }
1561         } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1562             codec_id = AV_CODEC_ID_PCM_F64LE;
1563         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1564             int profile = matroska_aac_profile(track->codec_id);
1565             int sri = matroska_aac_sri(track->audio.samplerate);
1566             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1567             if (extradata == NULL)
1568                 return AVERROR(ENOMEM);
1569             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1570             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1571             if (strstr(track->codec_id, "SBR")) {
1572                 sri = matroska_aac_sri(track->audio.out_samplerate);
1573                 extradata[2] = 0x56;
1574                 extradata[3] = 0xE5;
1575                 extradata[4] = 0x80 | (sri<<3);
1576                 extradata_size = 5;
1577             } else
1578                 extradata_size = 2;
1579         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1580             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1581                Create the "atom size", "tag", and "tag version" fields the
1582                decoder expects manually. */
1583             extradata_size = 12 + track->codec_priv.size;
1584             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1585             if (extradata == NULL)
1586                 return AVERROR(ENOMEM);
1587             AV_WB32(extradata, extradata_size);
1588             memcpy(&extradata[4], "alac", 4);
1589             AV_WB32(&extradata[8], 0);
1590             memcpy(&extradata[12], track->codec_priv.data,
1591                                    track->codec_priv.size);
1592         } else if (codec_id == AV_CODEC_ID_TTA) {
1593             extradata_size = 30;
1594             extradata = av_mallocz(extradata_size);
1595             if (extradata == NULL)
1596                 return AVERROR(ENOMEM);
1597             ffio_init_context(&b, extradata, extradata_size, 1,
1598                           NULL, NULL, NULL, NULL);
1599             avio_write(&b, "TTA1", 4);
1600             avio_wl16(&b, 1);
1601             avio_wl16(&b, track->audio.channels);
1602             avio_wl16(&b, track->audio.bitdepth);
1603             avio_wl32(&b, track->audio.out_samplerate);
1604             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1605         } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1606                    codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1607             extradata_offset = 26;
1608         } else if (codec_id == AV_CODEC_ID_RA_144) {
1609             track->audio.out_samplerate = 8000;
1610             track->audio.channels = 1;
1611         } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1612                    codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1613             int flavor;
1614             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1615                           0, NULL, NULL, NULL, NULL);
1616             avio_skip(&b, 22);
1617             flavor                       = avio_rb16(&b);
1618             track->audio.coded_framesize = avio_rb32(&b);
1619             avio_skip(&b, 12);
1620             track->audio.sub_packet_h    = avio_rb16(&b);
1621             track->audio.frame_size      = avio_rb16(&b);
1622             track->audio.sub_packet_size = avio_rb16(&b);
1623             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1624             if (codec_id == AV_CODEC_ID_RA_288) {
1625                 st->codec->block_align = track->audio.coded_framesize;
1626                 track->codec_priv.size = 0;
1627             } else {
1628                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1629                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1630                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1631                     st->codec->bit_rate = sipr_bit_rate[flavor];
1632                 }
1633                 st->codec->block_align = track->audio.sub_packet_size;
1634                 extradata_offset = 78;
1635             }
1636         }
1637         track->codec_priv.size -= extradata_offset;
1638
1639         if (codec_id == AV_CODEC_ID_NONE)
1640             av_log(matroska->ctx, AV_LOG_INFO,
1641                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1642
1643         if (track->time_scale < 0.01)
1644             track->time_scale = 1.0;
1645         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1646
1647         st->codec->codec_id = codec_id;
1648         st->start_time = 0;
1649         if (strcmp(track->language, "und"))
1650             av_dict_set(&st->metadata, "language", track->language, 0);
1651         av_dict_set(&st->metadata, "title", track->name, 0);
1652
1653         if (track->flag_default)
1654             st->disposition |= AV_DISPOSITION_DEFAULT;
1655         if (track->flag_forced)
1656             st->disposition |= AV_DISPOSITION_FORCED;
1657
1658         if (!st->codec->extradata) {
1659             if(extradata){
1660                 st->codec->extradata = extradata;
1661                 st->codec->extradata_size = extradata_size;
1662             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1663                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1664                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1665                 if(st->codec->extradata == NULL)
1666                     return AVERROR(ENOMEM);
1667                 st->codec->extradata_size = track->codec_priv.size;
1668                 memcpy(st->codec->extradata,
1669                        track->codec_priv.data + extradata_offset,
1670                        track->codec_priv.size);
1671             }
1672         }
1673
1674         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1675             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1676             st->codec->codec_tag  = track->video.fourcc;
1677             st->codec->width  = track->video.pixel_width;
1678             st->codec->height = track->video.pixel_height;
1679             av_reduce(&st->sample_aspect_ratio.num,
1680                       &st->sample_aspect_ratio.den,
1681                       st->codec->height * track->video.display_width,
1682                       st->codec-> width * track->video.display_height,
1683                       255);
1684             if (st->codec->codec_id != AV_CODEC_ID_H264)
1685             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1686             if (track->default_duration) {
1687                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1688                           1000000000, track->default_duration, 30000);
1689             }
1690         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1691             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1692             st->codec->sample_rate = track->audio.out_samplerate;
1693             st->codec->channels = track->audio.channels;
1694             if (st->codec->codec_id != AV_CODEC_ID_AAC)
1695             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1696         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1697             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1698             if (st->codec->codec_id == AV_CODEC_ID_SSA)
1699                 matroska->contains_ssa = 1;
1700         }
1701     }
1702
1703     attachements = attachements_list->elem;
1704     for (j=0; j<attachements_list->nb_elem; j++) {
1705         if (!(attachements[j].filename && attachements[j].mime &&
1706               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1707             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1708         } else {
1709             AVStream *st = avformat_new_stream(s, NULL);
1710             if (st == NULL)
1711                 break;
1712             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1713             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1714             st->codec->codec_id = AV_CODEC_ID_NONE;
1715             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1716             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1717             if(st->codec->extradata == NULL)
1718                 break;
1719             st->codec->extradata_size = attachements[j].bin.size;
1720             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1721
1722             for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1723                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1724                              strlen(ff_mkv_mime_tags[i].str))) {
1725                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1726                     break;
1727                 }
1728             }
1729             attachements[j].stream = st;
1730         }
1731     }
1732
1733     chapters = chapters_list->elem;
1734     for (i=0; i<chapters_list->nb_elem; i++)
1735         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1736             && (max_start==0 || chapters[i].start > max_start)) {
1737             chapters[i].chapter =
1738             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1739                            chapters[i].start, chapters[i].end,
1740                            chapters[i].title);
1741             av_dict_set(&chapters[i].chapter->metadata,
1742                              "title", chapters[i].title, 0);
1743             max_start = chapters[i].start;
1744         }
1745
1746     matroska_convert_tags(s);
1747
1748     return 0;
1749 }
1750
1751 /*
1752  * Put one packet in an application-supplied AVPacket struct.
1753  * Returns 0 on success or -1 on failure.
1754  */
1755 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1756                                    AVPacket *pkt)
1757 {
1758     if (matroska->num_packets > 0) {
1759         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1760         av_free(matroska->packets[0]);
1761         if (matroska->num_packets > 1) {
1762             void *newpackets;
1763             memmove(&matroska->packets[0], &matroska->packets[1],
1764                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1765             newpackets = av_realloc(matroska->packets,
1766                             (matroska->num_packets - 1) * sizeof(AVPacket *));
1767             if (newpackets)
1768                 matroska->packets = newpackets;
1769         } else {
1770             av_freep(&matroska->packets);
1771             matroska->prev_pkt = NULL;
1772         }
1773         matroska->num_packets--;
1774         return 0;
1775     }
1776
1777     return -1;
1778 }
1779
1780 /*
1781  * Free all packets in our internal queue.
1782  */
1783 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1784 {
1785     matroska->prev_pkt = NULL;
1786     if (matroska->packets) {
1787         int n;
1788         for (n = 0; n < matroska->num_packets; n++) {
1789             av_free_packet(matroska->packets[n]);
1790             av_free(matroska->packets[n]);
1791         }
1792         av_freep(&matroska->packets);
1793         matroska->num_packets = 0;
1794     }
1795 }
1796
1797 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
1798                                 int* buf_size, int type,
1799                                 uint32_t **lace_buf, int *laces)
1800 {
1801     int res = 0, n, size = *buf_size;
1802     uint8_t *data = *buf;
1803     uint32_t *lace_size;
1804
1805     if (!type) {
1806         *laces = 1;
1807         *lace_buf = av_mallocz(sizeof(int));
1808         if (!*lace_buf)
1809             return AVERROR(ENOMEM);
1810
1811         *lace_buf[0] = size;
1812         return 0;
1813     }
1814
1815     assert(size > 0);
1816     *laces = *data + 1;
1817     data += 1;
1818     size -= 1;
1819     lace_size = av_mallocz(*laces * sizeof(int));
1820     if (!lace_size)
1821         return AVERROR(ENOMEM);
1822
1823     switch (type) {
1824     case 0x1: /* Xiph lacing */ {
1825         uint8_t temp;
1826         uint32_t total = 0;
1827         for (n = 0; res == 0 && n < *laces - 1; n++) {
1828             while (1) {
1829                 if (size == 0) {
1830                     res = AVERROR_EOF;
1831                     break;
1832                 }
1833                 temp = *data;
1834                 lace_size[n] += temp;
1835                 data += 1;
1836                 size -= 1;
1837                 if (temp != 0xff)
1838                     break;
1839             }
1840             total += lace_size[n];
1841         }
1842         if (size <= total) {
1843             res = AVERROR_INVALIDDATA;
1844             break;
1845         }
1846
1847         lace_size[n] = size - total;
1848         break;
1849     }
1850
1851     case 0x2: /* fixed-size lacing */
1852         if (size % (*laces)) {
1853             res = AVERROR_INVALIDDATA;
1854             break;
1855         }
1856         for (n = 0; n < *laces; n++)
1857             lace_size[n] = size / *laces;
1858         break;
1859
1860     case 0x3: /* EBML lacing */ {
1861         uint64_t num;
1862         uint64_t total;
1863         n = matroska_ebmlnum_uint(matroska, data, size, &num);
1864         if (n < 0) {
1865             av_log(matroska->ctx, AV_LOG_INFO,
1866                    "EBML block data error\n");
1867             res = n;
1868             break;
1869         }
1870         data += n;
1871         size -= n;
1872         total = lace_size[0] = num;
1873         for (n = 1; res == 0 && n < *laces - 1; n++) {
1874             int64_t snum;
1875             int r;
1876             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1877             if (r < 0) {
1878                 av_log(matroska->ctx, AV_LOG_INFO,
1879                        "EBML block data error\n");
1880                 res = r;
1881                 break;
1882             }
1883             data += r;
1884             size -= r;
1885             lace_size[n] = lace_size[n - 1] + snum;
1886             total += lace_size[n];
1887         }
1888         if (size <= total) {
1889             res = AVERROR_INVALIDDATA;
1890             break;
1891         }
1892         lace_size[*laces - 1] = size - total;
1893         break;
1894     }
1895     }
1896
1897     *buf      = data;
1898     *lace_buf = lace_size;
1899     *buf_size = size;
1900
1901     return res;
1902 }
1903
1904 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
1905                                    MatroskaTrack *track,
1906                                    AVStream *st,
1907                                    uint8_t *data, int size,
1908                                    uint64_t timecode, uint64_t duration,
1909                                    int64_t pos)
1910 {
1911     int a = st->codec->block_align;
1912     int sps = track->audio.sub_packet_size;
1913     int cfs = track->audio.coded_framesize;
1914     int h = track->audio.sub_packet_h;
1915     int y = track->audio.sub_packet_cnt;
1916     int w = track->audio.frame_size;
1917     int x;
1918
1919     if (!track->audio.pkt_cnt) {
1920         if (track->audio.sub_packet_cnt == 0)
1921             track->audio.buf_timecode = timecode;
1922         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1923             if (size < cfs * h / 2) {
1924                 av_log(matroska->ctx, AV_LOG_ERROR,
1925                        "Corrupt int4 RM-style audio packet size\n");
1926                 return AVERROR_INVALIDDATA;
1927             }
1928             for (x=0; x<h/2; x++)
1929                 memcpy(track->audio.buf+x*2*w+y*cfs,
1930                        data+x*cfs, cfs);
1931         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1932             if (size < w) {
1933                 av_log(matroska->ctx, AV_LOG_ERROR,
1934                        "Corrupt sipr RM-style audio packet size\n");
1935                 return AVERROR_INVALIDDATA;
1936             }
1937             memcpy(track->audio.buf + y*w, data, w);
1938         } else {
1939             if (size < sps * w / sps) {
1940                 av_log(matroska->ctx, AV_LOG_ERROR,
1941                        "Corrupt generic RM-style audio packet size\n");
1942                 return AVERROR_INVALIDDATA;
1943             }
1944             for (x=0; x<w/sps; x++)
1945                 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1946         }
1947
1948         if (++track->audio.sub_packet_cnt >= h) {
1949             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1950                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1951             track->audio.sub_packet_cnt = 0;
1952             track->audio.pkt_cnt = h*w / a;
1953         }
1954     }
1955
1956     while (track->audio.pkt_cnt) {
1957         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1958         av_new_packet(pkt, a);
1959         memcpy(pkt->data, track->audio.buf
1960                + a * (h*w / a - track->audio.pkt_cnt--), a);
1961         pkt->pts = track->audio.buf_timecode;
1962         track->audio.buf_timecode = AV_NOPTS_VALUE;
1963         pkt->pos = pos;
1964         pkt->stream_index = st->index;
1965         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1966     }
1967
1968     return 0;
1969 }
1970
1971 /* reconstruct full wavpack blocks from mangled matroska ones */
1972 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
1973                                   uint8_t **pdst, int *size)
1974 {
1975     uint8_t *dst = NULL;
1976     int dstlen   = 0;
1977     int srclen   = *size;
1978     uint32_t samples;
1979     uint16_t ver;
1980     int ret, offset = 0;
1981
1982     if (srclen < 12 || track->stream->codec->extradata_size < 2)
1983         return AVERROR_INVALIDDATA;
1984
1985     ver = AV_RL16(track->stream->codec->extradata);
1986
1987     samples = AV_RL32(src);
1988     src    += 4;
1989     srclen -= 4;
1990
1991     while (srclen >= 8) {
1992         int multiblock;
1993         uint32_t blocksize;
1994         uint8_t *tmp;
1995
1996         uint32_t flags = AV_RL32(src);
1997         uint32_t crc   = AV_RL32(src + 4);
1998         src    += 8;
1999         srclen -= 8;
2000
2001         multiblock = (flags & 0x1800) != 0x1800;
2002         if (multiblock) {
2003             if (srclen < 4) {
2004                 ret = AVERROR_INVALIDDATA;
2005                 goto fail;
2006             }
2007             blocksize = AV_RL32(src);
2008             src    += 4;
2009             srclen -= 4;
2010         } else
2011             blocksize = srclen;
2012
2013         if (blocksize > srclen) {
2014             ret = AVERROR_INVALIDDATA;
2015             goto fail;
2016         }
2017
2018         tmp = av_realloc(dst, dstlen + blocksize + 32);
2019         if (!tmp) {
2020             ret = AVERROR(ENOMEM);
2021             goto fail;
2022         }
2023         dst     = tmp;
2024         dstlen += blocksize + 32;
2025
2026         AV_WL32(dst + offset,      MKTAG('w', 'v', 'p', 'k')); // tag
2027         AV_WL32(dst + offset + 4,  blocksize + 24);            // blocksize - 8
2028         AV_WL16(dst + offset + 8,  ver);                       // version
2029         AV_WL16(dst + offset + 10, 0);                         // track/index_no
2030         AV_WL32(dst + offset + 12, 0);                         // total samples
2031         AV_WL32(dst + offset + 16, 0);                         // block index
2032         AV_WL32(dst + offset + 20, samples);                   // number of samples
2033         AV_WL32(dst + offset + 24, flags);                     // flags
2034         AV_WL32(dst + offset + 28, crc);                       // crc
2035         memcpy (dst + offset + 32, src, blocksize);            // block data
2036
2037         src    += blocksize;
2038         srclen -= blocksize;
2039         offset += blocksize + 32;
2040     }
2041
2042     *pdst = dst;
2043     *size = dstlen;
2044
2045     return 0;
2046
2047 fail:
2048     av_freep(&dst);
2049     return ret;
2050 }
2051
2052 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2053                                 MatroskaTrack *track,
2054                                 AVStream *st,
2055                                 uint8_t *data, int pkt_size,
2056                                 uint64_t timecode, uint64_t duration,
2057                                 int64_t pos, int is_keyframe)
2058 {
2059     MatroskaTrackEncoding *encodings = track->encodings.elem;
2060     uint8_t *pkt_data = data;
2061     int offset = 0, res;
2062     AVPacket *pkt;
2063
2064     if (encodings && encodings->scope & 1) {
2065         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2066         if (res < 0)
2067             return res;
2068     }
2069
2070     if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2071         uint8_t *wv_data;
2072         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2073         if (res < 0) {
2074             av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
2075             goto fail;
2076         }
2077         if (pkt_data != data)
2078             av_freep(&pkt_data);
2079         pkt_data = wv_data;
2080     }
2081
2082     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2083         offset = 8;
2084
2085     pkt = av_mallocz(sizeof(AVPacket));
2086     /* XXX: prevent data copy... */
2087     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2088         av_free(pkt);
2089         return AVERROR(ENOMEM);
2090     }
2091
2092     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2093         uint8_t *buf = pkt->data;
2094         bytestream_put_be32(&buf, pkt_size);
2095         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2096     }
2097
2098     memcpy(pkt->data + offset, pkt_data, pkt_size);
2099
2100     if (pkt_data != data)
2101         av_free(pkt_data);
2102
2103     pkt->flags = is_keyframe;
2104     pkt->stream_index = st->index;
2105
2106     if (track->ms_compat)
2107         pkt->dts = timecode;
2108     else
2109         pkt->pts = timecode;
2110     pkt->pos = pos;
2111     if (st->codec->codec_id == AV_CODEC_ID_TEXT)
2112         pkt->convergence_duration = duration;
2113     else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
2114         pkt->duration = duration;
2115
2116     if (st->codec->codec_id == AV_CODEC_ID_SSA)
2117         matroska_fix_ass_packet(matroska, pkt, duration);
2118
2119     if (matroska->prev_pkt &&
2120         timecode != AV_NOPTS_VALUE &&
2121         matroska->prev_pkt->pts == timecode &&
2122         matroska->prev_pkt->stream_index == st->index &&
2123         st->codec->codec_id == AV_CODEC_ID_SSA)
2124         matroska_merge_packets(matroska->prev_pkt, pkt);
2125     else {
2126         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2127         matroska->prev_pkt = pkt;
2128     }
2129
2130     return 0;
2131 fail:
2132     if (pkt_data != data)
2133         av_freep(&pkt_data);
2134     return res;
2135 }
2136
2137 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2138                                 int size, int64_t pos, uint64_t cluster_time,
2139                                 uint64_t block_duration, int is_keyframe,
2140                                 int64_t cluster_pos)
2141 {
2142     uint64_t timecode = AV_NOPTS_VALUE;
2143     MatroskaTrack *track;
2144     int res = 0;
2145     AVStream *st;
2146     int16_t block_time;
2147     uint32_t *lace_size = NULL;
2148     int n, flags, laces = 0;
2149     uint64_t num, duration;
2150
2151     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2152         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2153         return n;
2154     }
2155     data += n;
2156     size -= n;
2157
2158     track = matroska_find_track_by_num(matroska, num);
2159     if (!track || !track->stream) {
2160         av_log(matroska->ctx, AV_LOG_INFO,
2161                "Invalid stream %"PRIu64" or size %u\n", num, size);
2162         return AVERROR_INVALIDDATA;
2163     } else if (size <= 3)
2164         return 0;
2165     st = track->stream;
2166     if (st->discard >= AVDISCARD_ALL)
2167         return res;
2168
2169     block_time = AV_RB16(data);
2170     data += 2;
2171     flags = *data++;
2172     size -= 3;
2173     if (is_keyframe == -1)
2174         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2175
2176     if (cluster_time != (uint64_t)-1
2177         && (block_time >= 0 || cluster_time >= -block_time)) {
2178         timecode = cluster_time + block_time;
2179         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2180             && timecode < track->end_timecode)
2181             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2182         if (is_keyframe)
2183             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2184     }
2185
2186     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2187         if (!is_keyframe || timecode < matroska->skip_to_timecode)
2188             return res;
2189         matroska->skip_to_keyframe = 0;
2190     }
2191
2192     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2193                                &lace_size, &laces);
2194
2195     if (res)
2196         goto end;
2197
2198     if (block_duration != AV_NOPTS_VALUE) {
2199         duration = block_duration / laces;
2200         if (block_duration != duration * laces) {
2201             av_log(matroska->ctx, AV_LOG_WARNING,
2202                    "Incorrect block_duration, possibly corrupted container");
2203         }
2204     } else {
2205         duration = track->default_duration / matroska->time_scale;
2206         block_duration = duration * laces;
2207     }
2208
2209     if (timecode != AV_NOPTS_VALUE)
2210         track->end_timecode =
2211             FFMAX(track->end_timecode, timecode + block_duration);
2212
2213     for (n = 0; n < laces; n++) {
2214         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2215              st->codec->codec_id == AV_CODEC_ID_COOK ||
2216              st->codec->codec_id == AV_CODEC_ID_SIPR ||
2217              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2218              st->codec->block_align && track->audio.sub_packet_size) {
2219
2220             res = matroska_parse_rm_audio(matroska, track, st, data,
2221                                           lace_size[n],
2222                                           timecode, duration, pos);
2223             if (res)
2224                 goto end;
2225
2226         } else {
2227             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2228                                       timecode, duration,
2229                                       pos, !n? is_keyframe : 0);
2230             if (res)
2231                 goto end;
2232         }
2233
2234         if (timecode != AV_NOPTS_VALUE)
2235             timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2236         data += lace_size[n];
2237     }
2238
2239 end:
2240     av_free(lace_size);
2241     return res;
2242 }
2243
2244 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2245 {
2246     EbmlList *blocks_list;
2247     MatroskaBlock *blocks;
2248     int i, res;
2249     res = ebml_parse(matroska,
2250                      matroska_cluster_incremental_parsing,
2251                      &matroska->current_cluster);
2252     if (res == 1) {
2253         /* New Cluster */
2254         if (matroska->current_cluster_pos)
2255             ebml_level_end(matroska);
2256         ebml_free(matroska_cluster, &matroska->current_cluster);
2257         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2258         matroska->current_cluster_num_blocks = 0;
2259         matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2260         matroska->prev_pkt = NULL;
2261         /* sizeof the ID which was already read */
2262         if (matroska->current_id)
2263             matroska->current_cluster_pos -= 4;
2264         res = ebml_parse(matroska,
2265                          matroska_clusters_incremental,
2266                          &matroska->current_cluster);
2267         /* Try parsing the block again. */
2268         if (res == 1)
2269             res = ebml_parse(matroska,
2270                              matroska_cluster_incremental_parsing,
2271                              &matroska->current_cluster);
2272     }
2273
2274     if (!res &&
2275         matroska->current_cluster_num_blocks <
2276             matroska->current_cluster.blocks.nb_elem) {
2277         blocks_list = &matroska->current_cluster.blocks;
2278         blocks = blocks_list->elem;
2279
2280         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2281         i = blocks_list->nb_elem - 1;
2282         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2283             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2284             if (!blocks[i].non_simple)
2285                 blocks[i].duration = AV_NOPTS_VALUE;
2286             res = matroska_parse_block(matroska,
2287                                        blocks[i].bin.data, blocks[i].bin.size,
2288                                        blocks[i].bin.pos,
2289                                        matroska->current_cluster.timecode,
2290                                        blocks[i].duration, is_keyframe,
2291                                        matroska->current_cluster_pos);
2292         }
2293     }
2294
2295     if (res < 0)  matroska->done = 1;
2296     return res;
2297 }
2298
2299 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2300 {
2301     MatroskaCluster cluster = { 0 };
2302     EbmlList *blocks_list;
2303     MatroskaBlock *blocks;
2304     int i, res;
2305     int64_t pos;
2306     if (!matroska->contains_ssa)
2307         return matroska_parse_cluster_incremental(matroska);
2308     pos = avio_tell(matroska->ctx->pb);
2309     matroska->prev_pkt = NULL;
2310     if (matroska->current_id)
2311         pos -= 4;  /* sizeof the ID which was already read */
2312     res = ebml_parse(matroska, matroska_clusters, &cluster);
2313     blocks_list = &cluster.blocks;
2314     blocks = blocks_list->elem;
2315     for (i=0; i<blocks_list->nb_elem && !res; i++)
2316         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2317             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2318             if (!blocks[i].non_simple)
2319                 blocks[i].duration = AV_NOPTS_VALUE;
2320             res=matroska_parse_block(matroska,
2321                                      blocks[i].bin.data, blocks[i].bin.size,
2322                                      blocks[i].bin.pos,  cluster.timecode,
2323                                      blocks[i].duration, is_keyframe,
2324                                      pos);
2325         }
2326     ebml_free(matroska_cluster, &cluster);
2327     return res;
2328 }
2329
2330 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2331 {
2332     MatroskaDemuxContext *matroska = s->priv_data;
2333     int ret = 0;
2334
2335     while (!ret && matroska_deliver_packet(matroska, pkt)) {
2336         int64_t pos = avio_tell(matroska->ctx->pb);
2337         if (matroska->done)
2338             return AVERROR_EOF;
2339         if (matroska_parse_cluster(matroska) < 0)
2340             ret = matroska_resync(matroska, pos);
2341     }
2342
2343     if (ret == AVERROR_INVALIDDATA && pkt->data) {
2344         pkt->flags |= AV_PKT_FLAG_CORRUPT;
2345         return 0;
2346     }
2347
2348     return ret;
2349 }
2350
2351 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2352                               int64_t timestamp, int flags)
2353 {
2354     MatroskaDemuxContext *matroska = s->priv_data;
2355     MatroskaTrack *tracks = matroska->tracks.elem;
2356     AVStream *st = s->streams[stream_index];
2357     int i, index, index_sub, index_min;
2358
2359     /* Parse the CUES now since we need the index data to seek. */
2360     if (matroska->cues_parsing_deferred) {
2361         matroska_parse_cues(matroska);
2362         matroska->cues_parsing_deferred = 0;
2363     }
2364
2365     if (!st->nb_index_entries)
2366         return 0;
2367     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2368
2369     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2370         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2371         matroska->current_id = 0;
2372         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2373             matroska_clear_queue(matroska);
2374             if (matroska_parse_cluster(matroska) < 0)
2375                 break;
2376         }
2377     }
2378
2379     matroska_clear_queue(matroska);
2380     if (index < 0)
2381         return 0;
2382
2383     index_min = index;
2384     for (i=0; i < matroska->tracks.nb_elem; i++) {
2385         tracks[i].audio.pkt_cnt = 0;
2386         tracks[i].audio.sub_packet_cnt = 0;
2387         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2388         tracks[i].end_timecode = 0;
2389         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2390             && !tracks[i].stream->discard != AVDISCARD_ALL) {
2391             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2392             if (index_sub >= 0
2393                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2394                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2395                 index_min = index_sub;
2396         }
2397     }
2398
2399     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2400     matroska->current_id = 0;
2401     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2402     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2403     matroska->done = 0;
2404     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2405     return 0;
2406 }
2407
2408 static int matroska_read_close(AVFormatContext *s)
2409 {
2410     MatroskaDemuxContext *matroska = s->priv_data;
2411     MatroskaTrack *tracks = matroska->tracks.elem;
2412     int n;
2413
2414     matroska_clear_queue(matroska);
2415
2416     for (n=0; n < matroska->tracks.nb_elem; n++)
2417         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2418             av_free(tracks[n].audio.buf);
2419     ebml_free(matroska_cluster, &matroska->current_cluster);
2420     ebml_free(matroska_segment, matroska);
2421
2422     return 0;
2423 }
2424
2425 AVInputFormat ff_matroska_demuxer = {
2426     .name           = "matroska,webm",
2427     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2428     .priv_data_size = sizeof(MatroskaDemuxContext),
2429     .read_probe     = matroska_probe,
2430     .read_header    = matroska_read_header,
2431     .read_packet    = matroska_read_packet,
2432     .read_close     = matroska_read_close,
2433     .read_seek      = matroska_read_seek,
2434 };