OSDN Git Service

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