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