]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
bcd7d1acc26c02e4807e0d975593a0e70746bc4a
[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 + FF_INPUT_BUFFER_PADDING_SIZE)))
738         return AVERROR(ENOMEM);
739
740     memset(bin->data + length, 0, FF_INPUT_BUFFER_PADDING_SIZE);
741
742     bin->size = length;
743     bin->pos  = avio_tell(pb);
744     if (avio_read(pb, bin->data, length) != length) {
745         av_freep(&bin->data);
746         return AVERROR(EIO);
747     }
748
749     return 0;
750 }
751
752 /*
753  * Read the next element, but only the header. The contents
754  * are supposed to be sub-elements which can be read separately.
755  * 0 is success, < 0 is failure.
756  */
757 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
758 {
759     AVIOContext *pb = matroska->ctx->pb;
760     MatroskaLevel *level;
761
762     if (matroska->num_levels >= EBML_MAX_DEPTH) {
763         av_log(matroska->ctx, AV_LOG_ERROR,
764                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
765         return AVERROR(ENOSYS);
766     }
767
768     level = &matroska->levels[matroska->num_levels++];
769     level->start = avio_tell(pb);
770     level->length = length;
771
772     return 0;
773 }
774
775 /*
776  * Read signed/unsigned "EBML" numbers.
777  * Return: number of bytes processed, < 0 on error
778  */
779 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
780                                  uint8_t *data, uint32_t size, uint64_t *num)
781 {
782     AVIOContext pb;
783     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
784     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
785 }
786
787 /*
788  * Same as above, but signed.
789  */
790 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
791                                  uint8_t *data, uint32_t size, int64_t *num)
792 {
793     uint64_t unum;
794     int res;
795
796     /* read as unsigned number first */
797     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
798         return res;
799
800     /* make signed (weird way) */
801     *num = unum - ((1LL << (7*res - 1)) - 1);
802
803     return res;
804 }
805
806 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
807                            EbmlSyntax *syntax, void *data);
808
809 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
810                          uint32_t id, void *data)
811 {
812     int i;
813     for (i=0; syntax[i].id; i++)
814         if (id == syntax[i].id)
815             break;
816     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
817         matroska->num_levels > 0 &&
818         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
819         return 0;  // we reached the end of an unknown size cluster
820     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
821         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
822         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
823             return AVERROR_INVALIDDATA;
824     }
825     return ebml_parse_elem(matroska, &syntax[i], data);
826 }
827
828 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
829                       void *data)
830 {
831     if (!matroska->current_id) {
832         uint64_t id;
833         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
834         if (res < 0)
835             return res;
836         matroska->current_id = id | 1 << 7*res;
837     }
838     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
839 }
840
841 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
842                            void *data)
843 {
844     int i, res = 0;
845
846     for (i=0; syntax[i].id; i++)
847         switch (syntax[i].type) {
848         case EBML_UINT:
849             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
850             break;
851         case EBML_FLOAT:
852             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
853             break;
854         case EBML_STR:
855         case EBML_UTF8:
856             // the default may be NULL
857             if (syntax[i].def.s) {
858                 uint8_t **dst = (uint8_t**)((uint8_t*)data + syntax[i].data_offset);
859                 *dst = av_strdup(syntax[i].def.s);
860                 if (!*dst)
861                     return AVERROR(ENOMEM);
862             }
863             break;
864         }
865
866     while (!res && !ebml_level_end(matroska))
867         res = ebml_parse(matroska, syntax, data);
868
869     return res;
870 }
871
872 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
873                            EbmlSyntax *syntax, void *data)
874 {
875     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
876         [EBML_UINT]  = 8,
877         [EBML_FLOAT] = 8,
878         // max. 16 MB for strings
879         [EBML_STR]   = 0x1000000,
880         [EBML_UTF8]  = 0x1000000,
881         // max. 256 MB for binary data
882         [EBML_BIN]   = 0x10000000,
883         // no limits for anything else
884     };
885     AVIOContext *pb = matroska->ctx->pb;
886     uint32_t id = syntax->id;
887     uint64_t length;
888     int res;
889
890     data = (char *)data + syntax->data_offset;
891     if (syntax->list_elem_size) {
892         EbmlList *list = data;
893         if ((res = av_reallocp_array(&list->elem,
894                                      list->nb_elem + 1,
895                                      syntax->list_elem_size)) < 0) {
896             list->nb_elem = 0;
897             return res;
898         }
899         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
900         memset(data, 0, syntax->list_elem_size);
901         list->nb_elem++;
902     }
903
904     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
905         matroska->current_id = 0;
906         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
907             return res;
908         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
909             av_log(matroska->ctx, AV_LOG_ERROR,
910                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
911                    length, max_lengths[syntax->type], syntax->type);
912             return AVERROR_INVALIDDATA;
913         }
914     }
915
916     switch (syntax->type) {
917     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
918     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
919     case EBML_STR:
920     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
921     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
922     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
923                          return res;
924                      if (id == MATROSKA_ID_SEGMENT)
925                          matroska->segment_start = avio_tell(matroska->ctx->pb);
926                      return ebml_parse_nest(matroska, syntax->def.n, data);
927     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
928     case EBML_STOP:  return 1;
929     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
930     }
931     if (res == AVERROR_INVALIDDATA)
932         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
933     else if (res == AVERROR(EIO))
934         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
935     return res;
936 }
937
938 static void ebml_free(EbmlSyntax *syntax, void *data)
939 {
940     int i, j;
941     for (i=0; syntax[i].id; i++) {
942         void *data_off = (char *)data + syntax[i].data_offset;
943         switch (syntax[i].type) {
944         case EBML_STR:
945         case EBML_UTF8:  av_freep(data_off);                      break;
946         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
947         case EBML_NEST:
948             if (syntax[i].list_elem_size) {
949                 EbmlList *list = data_off;
950                 char *ptr = list->elem;
951                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
952                     ebml_free(syntax[i].def.n, ptr);
953                 av_free(list->elem);
954             } else
955                 ebml_free(syntax[i].def.n, data_off);
956         default:  break;
957         }
958     }
959 }
960
961
962 /*
963  * Autodetecting...
964  */
965 static int matroska_probe(AVProbeData *p)
966 {
967     uint64_t total = 0;
968     int len_mask = 0x80, size = 1, n = 1, i;
969
970     /* EBML header? */
971     if (AV_RB32(p->buf) != EBML_ID_HEADER)
972         return 0;
973
974     /* length of header */
975     total = p->buf[4];
976     while (size <= 8 && !(total & len_mask)) {
977         size++;
978         len_mask >>= 1;
979     }
980     if (size > 8)
981       return 0;
982     total &= (len_mask - 1);
983     while (n < size)
984         total = (total << 8) | p->buf[4 + n++];
985
986     /* Does the probe data contain the whole header? */
987     if (p->buf_size < 4 + size + total)
988       return 0;
989
990     /* The header should contain a known document type. For now,
991      * we don't parse the whole header but simply check for the
992      * availability of that array of characters inside the header.
993      * Not fully fool-proof, but good enough. */
994     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
995         int probelen = strlen(matroska_doctypes[i]);
996         if (total < probelen)
997             continue;
998         for (n = 4+size; n <= 4+size+total-probelen; n++)
999             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
1000                 return AVPROBE_SCORE_MAX;
1001     }
1002
1003     // probably valid EBML header but no recognized doctype
1004     return AVPROBE_SCORE_EXTENSION;
1005 }
1006
1007 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1008                                                  int num)
1009 {
1010     MatroskaTrack *tracks = matroska->tracks.elem;
1011     int i;
1012
1013     for (i=0; i < matroska->tracks.nb_elem; i++)
1014         if (tracks[i].num == num)
1015             return &tracks[i];
1016
1017     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1018     return NULL;
1019 }
1020
1021 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1022                                   MatroskaTrack *track)
1023 {
1024     MatroskaTrackEncoding *encodings = track->encodings.elem;
1025     uint8_t* data = *buf;
1026     int isize = *buf_size;
1027     uint8_t* pkt_data = NULL;
1028     uint8_t av_unused *newpktdata;
1029     int pkt_size = isize;
1030     int result = 0;
1031     int olen;
1032
1033     if (pkt_size >= 10000000)
1034         return AVERROR_INVALIDDATA;
1035
1036     switch (encodings[0].compression.algo) {
1037     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
1038         int header_size = encodings[0].compression.settings.size;
1039         uint8_t *header = encodings[0].compression.settings.data;
1040
1041         if (!header_size)
1042             return 0;
1043
1044         pkt_size = isize + header_size;
1045         pkt_data = av_malloc(pkt_size);
1046         if (!pkt_data)
1047             return AVERROR(ENOMEM);
1048
1049         memcpy(pkt_data, header, header_size);
1050         memcpy(pkt_data + header_size, data, isize);
1051         break;
1052     }
1053 #if CONFIG_LZO
1054     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1055         do {
1056             olen = pkt_size *= 3;
1057             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1058             if (!newpktdata) {
1059                 result = AVERROR(ENOMEM);
1060                 goto failed;
1061             }
1062             pkt_data = newpktdata;
1063             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1064         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1065         if (result) {
1066             result = AVERROR_INVALIDDATA;
1067             goto failed;
1068         }
1069         pkt_size -= olen;
1070         break;
1071 #endif
1072 #if CONFIG_ZLIB
1073     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1074         z_stream zstream = {0};
1075         if (inflateInit(&zstream) != Z_OK)
1076             return -1;
1077         zstream.next_in = data;
1078         zstream.avail_in = isize;
1079         do {
1080             pkt_size *= 3;
1081             newpktdata = av_realloc(pkt_data, pkt_size);
1082             if (!newpktdata) {
1083                 inflateEnd(&zstream);
1084                 goto failed;
1085             }
1086             pkt_data = newpktdata;
1087             zstream.avail_out = pkt_size - zstream.total_out;
1088             zstream.next_out = pkt_data + zstream.total_out;
1089             result = inflate(&zstream, Z_NO_FLUSH);
1090         } while (result==Z_OK && pkt_size<10000000);
1091         pkt_size = zstream.total_out;
1092         inflateEnd(&zstream);
1093         if (result != Z_STREAM_END) {
1094             if (result == Z_MEM_ERROR)
1095                 result = AVERROR(ENOMEM);
1096             else
1097                 result = AVERROR_INVALIDDATA;
1098             goto failed;
1099         }
1100         break;
1101     }
1102 #endif
1103 #if CONFIG_BZLIB
1104     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1105         bz_stream bzstream = {0};
1106         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1107             return -1;
1108         bzstream.next_in = data;
1109         bzstream.avail_in = isize;
1110         do {
1111             pkt_size *= 3;
1112             newpktdata = av_realloc(pkt_data, pkt_size);
1113             if (!newpktdata) {
1114                 BZ2_bzDecompressEnd(&bzstream);
1115                 goto failed;
1116             }
1117             pkt_data = newpktdata;
1118             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1119             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1120             result = BZ2_bzDecompress(&bzstream);
1121         } while (result==BZ_OK && pkt_size<10000000);
1122         pkt_size = bzstream.total_out_lo32;
1123         BZ2_bzDecompressEnd(&bzstream);
1124         if (result != BZ_STREAM_END) {
1125             if (result == BZ_MEM_ERROR)
1126                 result = AVERROR(ENOMEM);
1127             else
1128                 result = AVERROR_INVALIDDATA;
1129             goto failed;
1130         }
1131         break;
1132     }
1133 #endif
1134     default:
1135         return AVERROR_INVALIDDATA;
1136     }
1137
1138     *buf = pkt_data;
1139     *buf_size = pkt_size;
1140     return 0;
1141  failed:
1142     av_free(pkt_data);
1143     return result;
1144 }
1145
1146 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1147                                     AVPacket *pkt, uint64_t display_duration)
1148 {
1149     AVBufferRef *line;
1150     char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1151     for (; *ptr!=',' && ptr<end-1; ptr++);
1152     if (*ptr == ',')
1153         layer = ++ptr;
1154     for (; *ptr!=',' && ptr<end-1; ptr++);
1155     if (*ptr == ',') {
1156         int64_t end_pts = pkt->pts + display_duration;
1157         int sc = matroska->time_scale * pkt->pts / 10000000;
1158         int ec = matroska->time_scale * end_pts  / 10000000;
1159         int sh, sm, ss, eh, em, es, len;
1160         sh = sc/360000;  sc -= 360000*sh;
1161         sm = sc/  6000;  sc -=   6000*sm;
1162         ss = sc/   100;  sc -=    100*ss;
1163         eh = ec/360000;  ec -= 360000*eh;
1164         em = ec/  6000;  ec -=   6000*em;
1165         es = ec/   100;  ec -=    100*es;
1166         *ptr++ = '\0';
1167         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1168         if (!(line = av_buffer_alloc(len)))
1169             return;
1170         snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1171                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1172         av_buffer_unref(&pkt->buf);
1173         pkt->buf  = line;
1174         pkt->data = line->data;
1175         pkt->size = strlen(line->data);
1176     }
1177 }
1178
1179 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1180 {
1181     int old_size = out->size;
1182     int ret = av_grow_packet(out, in->size);
1183     if (ret < 0)
1184         return ret;
1185
1186     memcpy(out->data + old_size, in->data, in->size);
1187
1188     av_free_packet(in);
1189     av_free(in);
1190     return 0;
1191 }
1192
1193 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1194                                  AVDictionary **metadata, char *prefix)
1195 {
1196     MatroskaTag *tags = list->elem;
1197     char key[1024];
1198     int i;
1199
1200     for (i=0; i < list->nb_elem; i++) {
1201         const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
1202                            tags[i].lang : NULL;
1203
1204         if (!tags[i].name) {
1205             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1206             continue;
1207         }
1208         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1209         else         av_strlcpy(key, tags[i].name, sizeof(key));
1210         if (tags[i].def || !lang) {
1211         av_dict_set(metadata, key, tags[i].string, 0);
1212         if (tags[i].sub.nb_elem)
1213             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1214         }
1215         if (lang) {
1216             av_strlcat(key, "-", sizeof(key));
1217             av_strlcat(key, lang, sizeof(key));
1218             av_dict_set(metadata, key, tags[i].string, 0);
1219             if (tags[i].sub.nb_elem)
1220                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1221         }
1222     }
1223     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1224 }
1225
1226 static void matroska_convert_tags(AVFormatContext *s)
1227 {
1228     MatroskaDemuxContext *matroska = s->priv_data;
1229     MatroskaTags *tags = matroska->tags.elem;
1230     int i, j;
1231
1232     for (i=0; i < matroska->tags.nb_elem; i++) {
1233         if (tags[i].target.attachuid) {
1234             MatroskaAttachement *attachment = matroska->attachments.elem;
1235             for (j=0; j<matroska->attachments.nb_elem; j++)
1236                 if (attachment[j].uid == tags[i].target.attachuid
1237                     && attachment[j].stream)
1238                     matroska_convert_tag(s, &tags[i].tag,
1239                                          &attachment[j].stream->metadata, NULL);
1240         } else if (tags[i].target.chapteruid) {
1241             MatroskaChapter *chapter = matroska->chapters.elem;
1242             for (j=0; j<matroska->chapters.nb_elem; j++)
1243                 if (chapter[j].uid == tags[i].target.chapteruid
1244                     && chapter[j].chapter)
1245                     matroska_convert_tag(s, &tags[i].tag,
1246                                          &chapter[j].chapter->metadata, NULL);
1247         } else if (tags[i].target.trackuid) {
1248             MatroskaTrack *track = matroska->tracks.elem;
1249             for (j=0; j<matroska->tracks.nb_elem; j++)
1250                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1251                     matroska_convert_tag(s, &tags[i].tag,
1252                                          &track[j].stream->metadata, NULL);
1253         } else {
1254             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1255                                  tags[i].target.type);
1256         }
1257     }
1258 }
1259
1260 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1261 {
1262     EbmlList *seekhead_list = &matroska->seekhead;
1263     MatroskaSeekhead *seekhead = seekhead_list->elem;
1264     uint32_t level_up = matroska->level_up;
1265     int64_t before_pos = avio_tell(matroska->ctx->pb);
1266     uint32_t saved_id = matroska->current_id;
1267     MatroskaLevel level;
1268     int64_t offset;
1269     int ret = 0;
1270
1271     if (idx >= seekhead_list->nb_elem
1272             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1273             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1274         return 0;
1275
1276     /* seek */
1277     offset = seekhead[idx].pos + matroska->segment_start;
1278     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1279         /* We don't want to lose our seekhead level, so we add
1280          * a dummy. This is a crude hack. */
1281         if (matroska->num_levels == EBML_MAX_DEPTH) {
1282             av_log(matroska->ctx, AV_LOG_INFO,
1283                    "Max EBML element depth (%d) reached, "
1284                    "cannot parse further.\n", EBML_MAX_DEPTH);
1285             ret = AVERROR_INVALIDDATA;
1286         } else {
1287             level.start = 0;
1288             level.length = (uint64_t)-1;
1289             matroska->levels[matroska->num_levels] = level;
1290             matroska->num_levels++;
1291             matroska->current_id = 0;
1292
1293             ret = ebml_parse(matroska, matroska_segment, matroska);
1294
1295             /* remove dummy level */
1296             while (matroska->num_levels) {
1297                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1298                 if (length == (uint64_t)-1)
1299                     break;
1300             }
1301         }
1302     }
1303     /* seek back */
1304     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1305     matroska->level_up = level_up;
1306     matroska->current_id = saved_id;
1307
1308     return ret;
1309 }
1310
1311 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1312 {
1313     EbmlList *seekhead_list = &matroska->seekhead;
1314     int64_t before_pos = avio_tell(matroska->ctx->pb);
1315     int i;
1316
1317     // we should not do any seeking in the streaming case
1318     if (!matroska->ctx->pb->seekable ||
1319         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1320         return;
1321
1322     for (i = 0; i < seekhead_list->nb_elem; i++) {
1323         MatroskaSeekhead *seekhead = seekhead_list->elem;
1324         if (seekhead[i].pos <= before_pos)
1325             continue;
1326
1327         // defer cues parsing until we actually need cue data.
1328         if (seekhead[i].id == MATROSKA_ID_CUES) {
1329             matroska->cues_parsing_deferred = 1;
1330             continue;
1331         }
1332
1333         if (matroska_parse_seekhead_entry(matroska, i) < 0)
1334             break;
1335     }
1336 }
1337
1338 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1339     EbmlList *seekhead_list = &matroska->seekhead;
1340     MatroskaSeekhead *seekhead = seekhead_list->elem;
1341     EbmlList *index_list;
1342     MatroskaIndex *index;
1343     int index_scale = 1;
1344     int i, j;
1345
1346     for (i = 0; i < seekhead_list->nb_elem; i++)
1347         if (seekhead[i].id == MATROSKA_ID_CUES)
1348             break;
1349     assert(i <= seekhead_list->nb_elem);
1350
1351     matroska_parse_seekhead_entry(matroska, i);
1352
1353     index_list = &matroska->index;
1354     index = index_list->elem;
1355     if (index_list->nb_elem
1356         && index[0].time > 1E14/matroska->time_scale) {
1357         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1358         index_scale = matroska->time_scale;
1359     }
1360     for (i = 0; i < index_list->nb_elem; i++) {
1361         EbmlList *pos_list = &index[i].pos;
1362         MatroskaIndexPos *pos = pos_list->elem;
1363         for (j = 0; j < pos_list->nb_elem; j++) {
1364             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1365             if (track && track->stream)
1366                 av_add_index_entry(track->stream,
1367                                    pos[j].pos + matroska->segment_start,
1368                                    index[i].time/index_scale, 0, 0,
1369                                    AVINDEX_KEYFRAME);
1370         }
1371     }
1372 }
1373
1374 static int matroska_aac_profile(char *codec_id)
1375 {
1376     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1377     int profile;
1378
1379     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1380         if (strstr(codec_id, aac_profiles[profile]))
1381             break;
1382     return profile + 1;
1383 }
1384
1385 static int matroska_aac_sri(int samplerate)
1386 {
1387     int sri;
1388
1389     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1390         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1391             break;
1392     return sri;
1393 }
1394
1395 static int matroska_read_header(AVFormatContext *s)
1396 {
1397     MatroskaDemuxContext *matroska = s->priv_data;
1398     EbmlList *attachements_list = &matroska->attachments;
1399     MatroskaAttachement *attachements;
1400     EbmlList *chapters_list = &matroska->chapters;
1401     MatroskaChapter *chapters;
1402     MatroskaTrack *tracks;
1403     uint64_t max_start = 0;
1404     int64_t pos;
1405     Ebml ebml = { 0 };
1406     AVStream *st;
1407     int i, j, res;
1408
1409     matroska->ctx = s;
1410
1411     /* First read the EBML header. */
1412     if (ebml_parse(matroska, ebml_syntax, &ebml)
1413         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1414         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1415         av_log(matroska->ctx, AV_LOG_ERROR,
1416                "EBML header using unsupported features\n"
1417                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1418                ebml.version, ebml.doctype, ebml.doctype_version);
1419         ebml_free(ebml_syntax, &ebml);
1420         return AVERROR_PATCHWELCOME;
1421     }
1422     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1423         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1424             break;
1425     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1426         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1427         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1428             ebml_free(ebml_syntax, &ebml);
1429             return AVERROR_INVALIDDATA;
1430         }
1431     }
1432     ebml_free(ebml_syntax, &ebml);
1433
1434     /* The next thing is a segment. */
1435     pos = avio_tell(matroska->ctx->pb);
1436     res = ebml_parse(matroska, matroska_segments, matroska);
1437     // try resyncing until we find a EBML_STOP type element.
1438     while (res != 1) {
1439         res = matroska_resync(matroska, pos);
1440         if (res < 0)
1441             return res;
1442         pos = avio_tell(matroska->ctx->pb);
1443         res = ebml_parse(matroska, matroska_segment, matroska);
1444     }
1445     matroska_execute_seekhead(matroska);
1446
1447     if (!matroska->time_scale)
1448         matroska->time_scale = 1000000;
1449     if (matroska->duration)
1450         matroska->ctx->duration = matroska->duration * matroska->time_scale
1451                                   * 1000 / AV_TIME_BASE;
1452     av_dict_set(&s->metadata, "title", matroska->title, 0);
1453
1454     tracks = matroska->tracks.elem;
1455     for (i=0; i < matroska->tracks.nb_elem; i++) {
1456         MatroskaTrack *track = &tracks[i];
1457         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1458         EbmlList *encodings_list = &track->encodings;
1459         MatroskaTrackEncoding *encodings = encodings_list->elem;
1460         uint8_t *extradata = NULL;
1461         int extradata_size = 0;
1462         int extradata_offset = 0;
1463         AVIOContext b;
1464
1465         /* Apply some sanity checks. */
1466         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1467             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1468             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1469             av_log(matroska->ctx, AV_LOG_INFO,
1470                    "Unknown or unsupported track type %"PRIu64"\n",
1471                    track->type);
1472             continue;
1473         }
1474         if (track->codec_id == NULL)
1475             continue;
1476
1477         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1478             if (!track->default_duration && track->video.frame_rate > 0)
1479                 track->default_duration = 1000000000/track->video.frame_rate;
1480             if (!track->video.display_width)
1481                 track->video.display_width = track->video.pixel_width;
1482             if (!track->video.display_height)
1483                 track->video.display_height = track->video.pixel_height;
1484         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1485             if (!track->audio.out_samplerate)
1486                 track->audio.out_samplerate = track->audio.samplerate;
1487         }
1488         if (encodings_list->nb_elem > 1) {
1489             av_log(matroska->ctx, AV_LOG_ERROR,
1490                    "Multiple combined encodings not supported");
1491         } else if (encodings_list->nb_elem == 1) {
1492             if (encodings[0].type ||
1493                 (
1494 #if CONFIG_ZLIB
1495                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1496 #endif
1497 #if CONFIG_BZLIB
1498                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1499 #endif
1500 #if CONFIG_LZO
1501                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1502 #endif
1503                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1504                 encodings[0].scope = 0;
1505                 av_log(matroska->ctx, AV_LOG_ERROR,
1506                        "Unsupported encoding type");
1507             } else if (track->codec_priv.size && encodings[0].scope&2) {
1508                 uint8_t *codec_priv = track->codec_priv.data;
1509                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1510                                                  &track->codec_priv.size,
1511                                                  track);
1512                 if (ret < 0) {
1513                     track->codec_priv.data = NULL;
1514                     track->codec_priv.size = 0;
1515                     av_log(matroska->ctx, AV_LOG_ERROR,
1516                            "Failed to decode codec private data\n");
1517                 }
1518
1519                 if (codec_priv != track->codec_priv.data)
1520                     av_free(codec_priv);
1521             }
1522         }
1523
1524         for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1525             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1526                         strlen(ff_mkv_codec_tags[j].str))){
1527                 codec_id= ff_mkv_codec_tags[j].id;
1528                 break;
1529             }
1530         }
1531
1532         st = track->stream = avformat_new_stream(s, NULL);
1533         if (st == NULL)
1534             return AVERROR(ENOMEM);
1535
1536         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1537             && track->codec_priv.size >= 40
1538             && track->codec_priv.data != NULL) {
1539             track->ms_compat = 1;
1540             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1541             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1542             extradata_offset = 40;
1543         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1544                    && track->codec_priv.size >= 14
1545                    && track->codec_priv.data != NULL) {
1546             int ret;
1547             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1548                               0, NULL, NULL, NULL, NULL);
1549             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1550             if (ret < 0)
1551                 return ret;
1552             codec_id = st->codec->codec_id;
1553             extradata_offset = FFMIN(track->codec_priv.size, 18);
1554         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1555                    && (track->codec_priv.size >= 86)
1556                    && (track->codec_priv.data != NULL)) {
1557             track->video.fourcc = AV_RL32(track->codec_priv.data);
1558             codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
1559         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1560             switch (track->audio.bitdepth) {
1561             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1562             case 24:  codec_id = AV_CODEC_ID_PCM_S24BE;  break;
1563             case 32:  codec_id = AV_CODEC_ID_PCM_S32BE;  break;
1564             }
1565         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1566             switch (track->audio.bitdepth) {
1567             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1568             case 24:  codec_id = AV_CODEC_ID_PCM_S24LE;  break;
1569             case 32:  codec_id = AV_CODEC_ID_PCM_S32LE;  break;
1570             }
1571         } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1572             codec_id = AV_CODEC_ID_PCM_F64LE;
1573         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1574             int profile = matroska_aac_profile(track->codec_id);
1575             int sri = matroska_aac_sri(track->audio.samplerate);
1576             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1577             if (extradata == NULL)
1578                 return AVERROR(ENOMEM);
1579             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1580             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1581             if (strstr(track->codec_id, "SBR")) {
1582                 sri = matroska_aac_sri(track->audio.out_samplerate);
1583                 extradata[2] = 0x56;
1584                 extradata[3] = 0xE5;
1585                 extradata[4] = 0x80 | (sri<<3);
1586                 extradata_size = 5;
1587             } else
1588                 extradata_size = 2;
1589         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1590             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1591                Create the "atom size", "tag", and "tag version" fields the
1592                decoder expects manually. */
1593             extradata_size = 12 + track->codec_priv.size;
1594             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1595             if (extradata == NULL)
1596                 return AVERROR(ENOMEM);
1597             AV_WB32(extradata, extradata_size);
1598             memcpy(&extradata[4], "alac", 4);
1599             AV_WB32(&extradata[8], 0);
1600             memcpy(&extradata[12], track->codec_priv.data,
1601                                    track->codec_priv.size);
1602         } else if (codec_id == AV_CODEC_ID_TTA) {
1603             extradata_size = 30;
1604             extradata = av_mallocz(extradata_size);
1605             if (extradata == NULL)
1606                 return AVERROR(ENOMEM);
1607             ffio_init_context(&b, extradata, extradata_size, 1,
1608                           NULL, NULL, NULL, NULL);
1609             avio_write(&b, "TTA1", 4);
1610             avio_wl16(&b, 1);
1611             avio_wl16(&b, track->audio.channels);
1612             avio_wl16(&b, track->audio.bitdepth);
1613             avio_wl32(&b, track->audio.out_samplerate);
1614             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1615         } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1616                    codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1617             extradata_offset = 26;
1618         } else if (codec_id == AV_CODEC_ID_RA_144) {
1619             track->audio.out_samplerate = 8000;
1620             track->audio.channels = 1;
1621         } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1622                    codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1623             int flavor;
1624             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1625                           0, NULL, NULL, NULL, NULL);
1626             avio_skip(&b, 22);
1627             flavor                       = avio_rb16(&b);
1628             track->audio.coded_framesize = avio_rb32(&b);
1629             avio_skip(&b, 12);
1630             track->audio.sub_packet_h    = avio_rb16(&b);
1631             track->audio.frame_size      = avio_rb16(&b);
1632             track->audio.sub_packet_size = avio_rb16(&b);
1633             if (flavor <= 0 || track->audio.coded_framesize <= 0 ||
1634                 track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1635                 track->audio.sub_packet_size <= 0)
1636                 return AVERROR_INVALIDDATA;
1637             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1638             if (codec_id == AV_CODEC_ID_RA_288) {
1639                 st->codec->block_align = track->audio.coded_framesize;
1640                 track->codec_priv.size = 0;
1641             } else {
1642                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1643                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1644                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1645                     st->codec->bit_rate = sipr_bit_rate[flavor];
1646                 }
1647                 st->codec->block_align = track->audio.sub_packet_size;
1648                 extradata_offset = 78;
1649             }
1650         }
1651         track->codec_priv.size -= extradata_offset;
1652
1653         if (codec_id == AV_CODEC_ID_NONE)
1654             av_log(matroska->ctx, AV_LOG_INFO,
1655                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1656
1657         if (track->time_scale < 0.01)
1658             track->time_scale = 1.0;
1659         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1660
1661         st->codec->codec_id = codec_id;
1662         st->start_time = 0;
1663         if (strcmp(track->language, "und"))
1664             av_dict_set(&st->metadata, "language", track->language, 0);
1665         av_dict_set(&st->metadata, "title", track->name, 0);
1666
1667         if (track->flag_default)
1668             st->disposition |= AV_DISPOSITION_DEFAULT;
1669         if (track->flag_forced)
1670             st->disposition |= AV_DISPOSITION_FORCED;
1671
1672         if (!st->codec->extradata) {
1673             if(extradata){
1674                 st->codec->extradata = extradata;
1675                 st->codec->extradata_size = extradata_size;
1676             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1677                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1678                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1679                 if(st->codec->extradata == NULL)
1680                     return AVERROR(ENOMEM);
1681                 st->codec->extradata_size = track->codec_priv.size;
1682                 memcpy(st->codec->extradata,
1683                        track->codec_priv.data + extradata_offset,
1684                        track->codec_priv.size);
1685             }
1686         }
1687
1688         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1689             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1690             st->codec->codec_tag  = track->video.fourcc;
1691             st->codec->width  = track->video.pixel_width;
1692             st->codec->height = track->video.pixel_height;
1693             av_reduce(&st->sample_aspect_ratio.num,
1694                       &st->sample_aspect_ratio.den,
1695                       st->codec->height * track->video.display_width,
1696                       st->codec-> width * track->video.display_height,
1697                       255);
1698             if (st->codec->codec_id != AV_CODEC_ID_H264 &&
1699                 st->codec->codec_id != AV_CODEC_ID_HEVC)
1700                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1701             if (track->default_duration) {
1702                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1703                           1000000000, track->default_duration, 30000);
1704             }
1705         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1706             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1707             st->codec->sample_rate = track->audio.out_samplerate;
1708             st->codec->channels = track->audio.channels;
1709             if (st->codec->codec_id != AV_CODEC_ID_AAC)
1710             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1711         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1712             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1713             if (st->codec->codec_id == AV_CODEC_ID_SSA)
1714                 matroska->contains_ssa = 1;
1715         }
1716     }
1717
1718     attachements = attachements_list->elem;
1719     for (j=0; j<attachements_list->nb_elem; j++) {
1720         if (!(attachements[j].filename && attachements[j].mime &&
1721               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1722             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1723         } else {
1724             AVStream *st = avformat_new_stream(s, NULL);
1725             if (st == NULL)
1726                 break;
1727             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1728             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1729             st->codec->codec_id = AV_CODEC_ID_NONE;
1730             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1731             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1732             if(st->codec->extradata == NULL)
1733                 break;
1734             st->codec->extradata_size = attachements[j].bin.size;
1735             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1736
1737             for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1738                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1739                              strlen(ff_mkv_mime_tags[i].str))) {
1740                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1741                     break;
1742                 }
1743             }
1744             attachements[j].stream = st;
1745         }
1746     }
1747
1748     chapters = chapters_list->elem;
1749     for (i=0; i<chapters_list->nb_elem; i++)
1750         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1751             && (max_start==0 || chapters[i].start > max_start)) {
1752             chapters[i].chapter =
1753             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1754                            chapters[i].start, chapters[i].end,
1755                            chapters[i].title);
1756             av_dict_set(&chapters[i].chapter->metadata,
1757                              "title", chapters[i].title, 0);
1758             max_start = chapters[i].start;
1759         }
1760
1761     matroska_convert_tags(s);
1762
1763     return 0;
1764 }
1765
1766 /*
1767  * Put one packet in an application-supplied AVPacket struct.
1768  * Returns 0 on success or -1 on failure.
1769  */
1770 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1771                                    AVPacket *pkt)
1772 {
1773     if (matroska->num_packets > 0) {
1774         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1775         av_free(matroska->packets[0]);
1776         if (matroska->num_packets > 1) {
1777             void *newpackets;
1778             memmove(&matroska->packets[0], &matroska->packets[1],
1779                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1780             newpackets = av_realloc(matroska->packets,
1781                             (matroska->num_packets - 1) * sizeof(AVPacket *));
1782             if (newpackets)
1783                 matroska->packets = newpackets;
1784         } else {
1785             av_freep(&matroska->packets);
1786             matroska->prev_pkt = NULL;
1787         }
1788         matroska->num_packets--;
1789         return 0;
1790     }
1791
1792     return -1;
1793 }
1794
1795 /*
1796  * Free all packets in our internal queue.
1797  */
1798 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1799 {
1800     matroska->prev_pkt = NULL;
1801     if (matroska->packets) {
1802         int n;
1803         for (n = 0; n < matroska->num_packets; n++) {
1804             av_free_packet(matroska->packets[n]);
1805             av_free(matroska->packets[n]);
1806         }
1807         av_freep(&matroska->packets);
1808         matroska->num_packets = 0;
1809     }
1810 }
1811
1812 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
1813                                 int* buf_size, int type,
1814                                 uint32_t **lace_buf, int *laces)
1815 {
1816     int res = 0, n, size = *buf_size;
1817     uint8_t *data = *buf;
1818     uint32_t *lace_size;
1819
1820     if (!type) {
1821         *laces = 1;
1822         *lace_buf = av_mallocz(sizeof(int));
1823         if (!*lace_buf)
1824             return AVERROR(ENOMEM);
1825
1826         *lace_buf[0] = size;
1827         return 0;
1828     }
1829
1830     assert(size > 0);
1831     *laces = *data + 1;
1832     data += 1;
1833     size -= 1;
1834     lace_size = av_mallocz(*laces * sizeof(int));
1835     if (!lace_size)
1836         return AVERROR(ENOMEM);
1837
1838     switch (type) {
1839     case 0x1: /* Xiph lacing */ {
1840         uint8_t temp;
1841         uint32_t total = 0;
1842         for (n = 0; res == 0 && n < *laces - 1; n++) {
1843             while (1) {
1844                 if (size == 0) {
1845                     res = AVERROR_EOF;
1846                     break;
1847                 }
1848                 temp = *data;
1849                 lace_size[n] += temp;
1850                 data += 1;
1851                 size -= 1;
1852                 if (temp != 0xff)
1853                     break;
1854             }
1855             total += lace_size[n];
1856         }
1857         if (size <= total) {
1858             res = AVERROR_INVALIDDATA;
1859             break;
1860         }
1861
1862         lace_size[n] = size - total;
1863         break;
1864     }
1865
1866     case 0x2: /* fixed-size lacing */
1867         if (size % (*laces)) {
1868             res = AVERROR_INVALIDDATA;
1869             break;
1870         }
1871         for (n = 0; n < *laces; n++)
1872             lace_size[n] = size / *laces;
1873         break;
1874
1875     case 0x3: /* EBML lacing */ {
1876         uint64_t num;
1877         uint64_t total;
1878         n = matroska_ebmlnum_uint(matroska, data, size, &num);
1879         if (n < 0) {
1880             av_log(matroska->ctx, AV_LOG_INFO,
1881                    "EBML block data error\n");
1882             res = n;
1883             break;
1884         }
1885         data += n;
1886         size -= n;
1887         total = lace_size[0] = num;
1888         for (n = 1; res == 0 && n < *laces - 1; n++) {
1889             int64_t snum;
1890             int r;
1891             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1892             if (r < 0) {
1893                 av_log(matroska->ctx, AV_LOG_INFO,
1894                        "EBML block data error\n");
1895                 res = r;
1896                 break;
1897             }
1898             data += r;
1899             size -= r;
1900             lace_size[n] = lace_size[n - 1] + snum;
1901             total += lace_size[n];
1902         }
1903         if (size <= total) {
1904             res = AVERROR_INVALIDDATA;
1905             break;
1906         }
1907         lace_size[*laces - 1] = size - total;
1908         break;
1909     }
1910     }
1911
1912     *buf      = data;
1913     *lace_buf = lace_size;
1914     *buf_size = size;
1915
1916     return res;
1917 }
1918
1919 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
1920                                    MatroskaTrack *track,
1921                                    AVStream *st,
1922                                    uint8_t *data, int size,
1923                                    uint64_t timecode, uint64_t duration,
1924                                    int64_t pos)
1925 {
1926     int a = st->codec->block_align;
1927     int sps = track->audio.sub_packet_size;
1928     int cfs = track->audio.coded_framesize;
1929     int h = track->audio.sub_packet_h;
1930     int y = track->audio.sub_packet_cnt;
1931     int w = track->audio.frame_size;
1932     int x;
1933
1934     if (!track->audio.pkt_cnt) {
1935         if (track->audio.sub_packet_cnt == 0)
1936             track->audio.buf_timecode = timecode;
1937         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1938             if (size < cfs * h / 2) {
1939                 av_log(matroska->ctx, AV_LOG_ERROR,
1940                        "Corrupt int4 RM-style audio packet size\n");
1941                 return AVERROR_INVALIDDATA;
1942             }
1943             for (x=0; x<h/2; x++)
1944                 memcpy(track->audio.buf+x*2*w+y*cfs,
1945                        data+x*cfs, cfs);
1946         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1947             if (size < w) {
1948                 av_log(matroska->ctx, AV_LOG_ERROR,
1949                        "Corrupt sipr RM-style audio packet size\n");
1950                 return AVERROR_INVALIDDATA;
1951             }
1952             memcpy(track->audio.buf + y*w, data, w);
1953         } else {
1954             if (size < sps * w / sps) {
1955                 av_log(matroska->ctx, AV_LOG_ERROR,
1956                        "Corrupt generic RM-style audio packet size\n");
1957                 return AVERROR_INVALIDDATA;
1958             }
1959             for (x=0; x<w/sps; x++)
1960                 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1961         }
1962
1963         if (++track->audio.sub_packet_cnt >= h) {
1964             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1965                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1966             track->audio.sub_packet_cnt = 0;
1967             track->audio.pkt_cnt = h*w / a;
1968         }
1969     }
1970
1971     while (track->audio.pkt_cnt) {
1972         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1973         av_new_packet(pkt, a);
1974         memcpy(pkt->data, track->audio.buf
1975                + a * (h*w / a - track->audio.pkt_cnt--), a);
1976         pkt->pts = track->audio.buf_timecode;
1977         track->audio.buf_timecode = AV_NOPTS_VALUE;
1978         pkt->pos = pos;
1979         pkt->stream_index = st->index;
1980         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1981     }
1982
1983     return 0;
1984 }
1985
1986 /* reconstruct full wavpack blocks from mangled matroska ones */
1987 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
1988                                   uint8_t **pdst, int *size)
1989 {
1990     uint8_t *dst = NULL;
1991     int dstlen   = 0;
1992     int srclen   = *size;
1993     uint32_t samples;
1994     uint16_t ver;
1995     int ret, offset = 0;
1996
1997     if (srclen < 12 || track->stream->codec->extradata_size < 2)
1998         return AVERROR_INVALIDDATA;
1999
2000     ver = AV_RL16(track->stream->codec->extradata);
2001
2002     samples = AV_RL32(src);
2003     src    += 4;
2004     srclen -= 4;
2005
2006     while (srclen >= 8) {
2007         int multiblock;
2008         uint32_t blocksize;
2009         uint8_t *tmp;
2010
2011         uint32_t flags = AV_RL32(src);
2012         uint32_t crc   = AV_RL32(src + 4);
2013         src    += 8;
2014         srclen -= 8;
2015
2016         multiblock = (flags & 0x1800) != 0x1800;
2017         if (multiblock) {
2018             if (srclen < 4) {
2019                 ret = AVERROR_INVALIDDATA;
2020                 goto fail;
2021             }
2022             blocksize = AV_RL32(src);
2023             src    += 4;
2024             srclen -= 4;
2025         } else
2026             blocksize = srclen;
2027
2028         if (blocksize > srclen) {
2029             ret = AVERROR_INVALIDDATA;
2030             goto fail;
2031         }
2032
2033         tmp = av_realloc(dst, dstlen + blocksize + 32);
2034         if (!tmp) {
2035             ret = AVERROR(ENOMEM);
2036             goto fail;
2037         }
2038         dst     = tmp;
2039         dstlen += blocksize + 32;
2040
2041         AV_WL32(dst + offset,      MKTAG('w', 'v', 'p', 'k')); // tag
2042         AV_WL32(dst + offset + 4,  blocksize + 24);            // blocksize - 8
2043         AV_WL16(dst + offset + 8,  ver);                       // version
2044         AV_WL16(dst + offset + 10, 0);                         // track/index_no
2045         AV_WL32(dst + offset + 12, 0);                         // total samples
2046         AV_WL32(dst + offset + 16, 0);                         // block index
2047         AV_WL32(dst + offset + 20, samples);                   // number of samples
2048         AV_WL32(dst + offset + 24, flags);                     // flags
2049         AV_WL32(dst + offset + 28, crc);                       // crc
2050         memcpy (dst + offset + 32, src, blocksize);            // block data
2051
2052         src    += blocksize;
2053         srclen -= blocksize;
2054         offset += blocksize + 32;
2055     }
2056
2057     *pdst = dst;
2058     *size = dstlen;
2059
2060     return 0;
2061
2062 fail:
2063     av_freep(&dst);
2064     return ret;
2065 }
2066
2067 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2068                                 MatroskaTrack *track,
2069                                 AVStream *st,
2070                                 uint8_t *data, int pkt_size,
2071                                 uint64_t timecode, uint64_t duration,
2072                                 int64_t pos, int is_keyframe)
2073 {
2074     MatroskaTrackEncoding *encodings = track->encodings.elem;
2075     uint8_t *pkt_data = data;
2076     int offset = 0, res;
2077     AVPacket *pkt;
2078
2079     if (encodings && encodings->scope & 1) {
2080         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2081         if (res < 0)
2082             return res;
2083     }
2084
2085     if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2086         uint8_t *wv_data;
2087         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2088         if (res < 0) {
2089             av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
2090             goto fail;
2091         }
2092         if (pkt_data != data)
2093             av_freep(&pkt_data);
2094         pkt_data = wv_data;
2095     }
2096
2097     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2098         offset = 8;
2099
2100     pkt = av_mallocz(sizeof(AVPacket));
2101     /* XXX: prevent data copy... */
2102     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2103         av_free(pkt);
2104         return AVERROR(ENOMEM);
2105     }
2106
2107     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2108         uint8_t *buf = pkt->data;
2109         bytestream_put_be32(&buf, pkt_size);
2110         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2111     }
2112
2113     memcpy(pkt->data + offset, pkt_data, pkt_size);
2114
2115     if (pkt_data != data)
2116         av_free(pkt_data);
2117
2118     pkt->flags = is_keyframe;
2119     pkt->stream_index = st->index;
2120
2121     if (track->ms_compat)
2122         pkt->dts = timecode;
2123     else
2124         pkt->pts = timecode;
2125     pkt->pos = pos;
2126     if (st->codec->codec_id == AV_CODEC_ID_TEXT)
2127         pkt->convergence_duration = duration;
2128     else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
2129         pkt->duration = duration;
2130
2131     if (st->codec->codec_id == AV_CODEC_ID_SSA)
2132         matroska_fix_ass_packet(matroska, pkt, duration);
2133
2134     if (matroska->prev_pkt &&
2135         timecode != AV_NOPTS_VALUE &&
2136         matroska->prev_pkt->pts == timecode &&
2137         matroska->prev_pkt->stream_index == st->index &&
2138         st->codec->codec_id == AV_CODEC_ID_SSA)
2139         matroska_merge_packets(matroska->prev_pkt, pkt);
2140     else {
2141         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2142         matroska->prev_pkt = pkt;
2143     }
2144
2145     return 0;
2146 fail:
2147     if (pkt_data != data)
2148         av_freep(&pkt_data);
2149     return res;
2150 }
2151
2152 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2153                                 int size, int64_t pos, uint64_t cluster_time,
2154                                 uint64_t block_duration, int is_keyframe,
2155                                 int64_t cluster_pos)
2156 {
2157     uint64_t timecode = AV_NOPTS_VALUE;
2158     MatroskaTrack *track;
2159     int res = 0;
2160     AVStream *st;
2161     int16_t block_time;
2162     uint32_t *lace_size = NULL;
2163     int n, flags, laces = 0;
2164     uint64_t num, duration;
2165
2166     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2167         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2168         return n;
2169     }
2170     data += n;
2171     size -= n;
2172
2173     track = matroska_find_track_by_num(matroska, num);
2174     if (!track || !track->stream) {
2175         av_log(matroska->ctx, AV_LOG_INFO,
2176                "Invalid stream %"PRIu64" or size %u\n", num, size);
2177         return AVERROR_INVALIDDATA;
2178     } else if (size <= 3)
2179         return 0;
2180     st = track->stream;
2181     if (st->discard >= AVDISCARD_ALL)
2182         return res;
2183
2184     block_time = AV_RB16(data);
2185     data += 2;
2186     flags = *data++;
2187     size -= 3;
2188     if (is_keyframe == -1)
2189         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2190
2191     if (cluster_time != (uint64_t)-1
2192         && (block_time >= 0 || cluster_time >= -block_time)) {
2193         timecode = cluster_time + block_time;
2194         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2195             && timecode < track->end_timecode)
2196             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2197         if (is_keyframe)
2198             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2199     }
2200
2201     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2202         if (!is_keyframe || timecode < matroska->skip_to_timecode)
2203             return res;
2204         matroska->skip_to_keyframe = 0;
2205     }
2206
2207     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2208                                &lace_size, &laces);
2209
2210     if (res)
2211         goto end;
2212
2213     if (block_duration != AV_NOPTS_VALUE) {
2214         duration = block_duration / laces;
2215         if (block_duration != duration * laces) {
2216             av_log(matroska->ctx, AV_LOG_WARNING,
2217                    "Incorrect block_duration, possibly corrupted container");
2218         }
2219     } else {
2220         duration = track->default_duration / matroska->time_scale;
2221         block_duration = duration * laces;
2222     }
2223
2224     if (timecode != AV_NOPTS_VALUE)
2225         track->end_timecode =
2226             FFMAX(track->end_timecode, timecode + block_duration);
2227
2228     for (n = 0; n < laces; n++) {
2229         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2230              st->codec->codec_id == AV_CODEC_ID_COOK ||
2231              st->codec->codec_id == AV_CODEC_ID_SIPR ||
2232              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2233              st->codec->block_align && track->audio.sub_packet_size) {
2234
2235             res = matroska_parse_rm_audio(matroska, track, st, data,
2236                                           lace_size[n],
2237                                           timecode, duration, pos);
2238             if (res)
2239                 goto end;
2240
2241         } else {
2242             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2243                                       timecode, duration,
2244                                       pos, !n? is_keyframe : 0);
2245             if (res)
2246                 goto end;
2247         }
2248
2249         if (timecode != AV_NOPTS_VALUE)
2250             timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2251         data += lace_size[n];
2252     }
2253
2254 end:
2255     av_free(lace_size);
2256     return res;
2257 }
2258
2259 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2260 {
2261     EbmlList *blocks_list;
2262     MatroskaBlock *blocks;
2263     int i, res;
2264     res = ebml_parse(matroska,
2265                      matroska_cluster_incremental_parsing,
2266                      &matroska->current_cluster);
2267     if (res == 1) {
2268         /* New Cluster */
2269         if (matroska->current_cluster_pos)
2270             ebml_level_end(matroska);
2271         ebml_free(matroska_cluster, &matroska->current_cluster);
2272         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2273         matroska->current_cluster_num_blocks = 0;
2274         matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2275         matroska->prev_pkt = NULL;
2276         /* sizeof the ID which was already read */
2277         if (matroska->current_id)
2278             matroska->current_cluster_pos -= 4;
2279         res = ebml_parse(matroska,
2280                          matroska_clusters_incremental,
2281                          &matroska->current_cluster);
2282         /* Try parsing the block again. */
2283         if (res == 1)
2284             res = ebml_parse(matroska,
2285                              matroska_cluster_incremental_parsing,
2286                              &matroska->current_cluster);
2287     }
2288
2289     if (!res &&
2290         matroska->current_cluster_num_blocks <
2291             matroska->current_cluster.blocks.nb_elem) {
2292         blocks_list = &matroska->current_cluster.blocks;
2293         blocks = blocks_list->elem;
2294
2295         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2296         i = blocks_list->nb_elem - 1;
2297         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2298             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2299             if (!blocks[i].non_simple)
2300                 blocks[i].duration = AV_NOPTS_VALUE;
2301             res = matroska_parse_block(matroska,
2302                                        blocks[i].bin.data, blocks[i].bin.size,
2303                                        blocks[i].bin.pos,
2304                                        matroska->current_cluster.timecode,
2305                                        blocks[i].duration, is_keyframe,
2306                                        matroska->current_cluster_pos);
2307         }
2308     }
2309
2310     if (res < 0)  matroska->done = 1;
2311     return res;
2312 }
2313
2314 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2315 {
2316     MatroskaCluster cluster = { 0 };
2317     EbmlList *blocks_list;
2318     MatroskaBlock *blocks;
2319     int i, res;
2320     int64_t pos;
2321     if (!matroska->contains_ssa)
2322         return matroska_parse_cluster_incremental(matroska);
2323     pos = avio_tell(matroska->ctx->pb);
2324     matroska->prev_pkt = NULL;
2325     if (matroska->current_id)
2326         pos -= 4;  /* sizeof the ID which was already read */
2327     res = ebml_parse(matroska, matroska_clusters, &cluster);
2328     blocks_list = &cluster.blocks;
2329     blocks = blocks_list->elem;
2330     for (i=0; i<blocks_list->nb_elem && !res; i++)
2331         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2332             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2333             if (!blocks[i].non_simple)
2334                 blocks[i].duration = AV_NOPTS_VALUE;
2335             res=matroska_parse_block(matroska,
2336                                      blocks[i].bin.data, blocks[i].bin.size,
2337                                      blocks[i].bin.pos,  cluster.timecode,
2338                                      blocks[i].duration, is_keyframe,
2339                                      pos);
2340         }
2341     ebml_free(matroska_cluster, &cluster);
2342     return res;
2343 }
2344
2345 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2346 {
2347     MatroskaDemuxContext *matroska = s->priv_data;
2348     int ret = 0;
2349
2350     while (!ret && matroska_deliver_packet(matroska, pkt)) {
2351         int64_t pos = avio_tell(matroska->ctx->pb);
2352         if (matroska->done)
2353             return AVERROR_EOF;
2354         if (matroska_parse_cluster(matroska) < 0)
2355             ret = matroska_resync(matroska, pos);
2356     }
2357
2358     if (ret == AVERROR_INVALIDDATA && pkt->data) {
2359         pkt->flags |= AV_PKT_FLAG_CORRUPT;
2360         return 0;
2361     }
2362
2363     return ret;
2364 }
2365
2366 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2367                               int64_t timestamp, int flags)
2368 {
2369     MatroskaDemuxContext *matroska = s->priv_data;
2370     MatroskaTrack *tracks = matroska->tracks.elem;
2371     AVStream *st = s->streams[stream_index];
2372     int i, index, index_sub, index_min;
2373
2374     /* Parse the CUES now since we need the index data to seek. */
2375     if (matroska->cues_parsing_deferred) {
2376         matroska_parse_cues(matroska);
2377         matroska->cues_parsing_deferred = 0;
2378     }
2379
2380     if (!st->nb_index_entries)
2381         return 0;
2382     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2383
2384     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2385         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2386         matroska->current_id = 0;
2387         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2388             matroska_clear_queue(matroska);
2389             if (matroska_parse_cluster(matroska) < 0)
2390                 break;
2391         }
2392     }
2393
2394     matroska_clear_queue(matroska);
2395     if (index < 0)
2396         return 0;
2397
2398     index_min = index;
2399     for (i=0; i < matroska->tracks.nb_elem; i++) {
2400         tracks[i].audio.pkt_cnt = 0;
2401         tracks[i].audio.sub_packet_cnt = 0;
2402         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2403         tracks[i].end_timecode = 0;
2404         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2405             && !tracks[i].stream->discard != AVDISCARD_ALL) {
2406             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2407             if (index_sub >= 0
2408                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2409                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2410                 index_min = index_sub;
2411         }
2412     }
2413
2414     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2415     matroska->current_id = 0;
2416     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2417     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2418     matroska->done = 0;
2419     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2420     return 0;
2421 }
2422
2423 static int matroska_read_close(AVFormatContext *s)
2424 {
2425     MatroskaDemuxContext *matroska = s->priv_data;
2426     MatroskaTrack *tracks = matroska->tracks.elem;
2427     int n;
2428
2429     matroska_clear_queue(matroska);
2430
2431     for (n=0; n < matroska->tracks.nb_elem; n++)
2432         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2433             av_free(tracks[n].audio.buf);
2434     ebml_free(matroska_cluster, &matroska->current_cluster);
2435     ebml_free(matroska_segment, matroska);
2436
2437     return 0;
2438 }
2439
2440 AVInputFormat ff_matroska_demuxer = {
2441     .name           = "matroska,webm",
2442     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2443     .priv_data_size = sizeof(MatroskaDemuxContext),
2444     .read_probe     = matroska_probe,
2445     .read_header    = matroska_read_header,
2446     .read_packet    = matroska_read_packet,
2447     .read_close     = matroska_read_close,
2448     .read_seek      = matroska_read_seek,
2449 };